diff --git a/DNN Platform/Admin Modules/Dnn.Modules.Console/Components/BusinessController.cs b/DNN Platform/Admin Modules/Dnn.Modules.Console/Components/BusinessController.cs index 6665ad33661..ca28c2817b4 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/Components/BusinessController.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/Components/BusinessController.cs @@ -30,7 +30,7 @@ public string UpgradeModule(string version) break; } - + return "Success"; } catch (Exception) 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 b8f9dd8c1a6..cd677a4a681 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/Settings.ascx.cs @@ -42,7 +42,7 @@ public override void LoadSettings() // DefaultSize.Items.Add(new ListItem(Localization.GetString(val, LocalResourceFile), val)); this.DefaultSize.AddItem(Localization.GetString(val, this.LocalResourceFile), val); } - + this.SelectDropDownListItem(ref this.DefaultSize, "DefaultSize"); this.SelectDropDownListItem(ref this.modeList, "Mode"); @@ -51,39 +51,39 @@ public override void LoadSettings() { this.AllowResize.Checked = Convert.ToBoolean(this.Settings["AllowSizeChange"]); } - + foreach (var val in ConsoleController.GetViewValues()) { // DefaultView.Items.Add(new ListItem(Localization.GetString(val, LocalResourceFile), val)); this.DefaultView.AddItem(Localization.GetString(val, this.LocalResourceFile), val); } - + this.SelectDropDownListItem(ref this.DefaultView, "DefaultView"); if (this.Settings.ContainsKey("IncludeParent")) { this.IncludeParent.Checked = Convert.ToBoolean(this.Settings["IncludeParent"]); } - + if (this.Settings.ContainsKey("AllowViewChange")) { this.AllowViewChange.Checked = Convert.ToBoolean(this.Settings["AllowViewChange"]); } - + if (this.Settings.ContainsKey("ShowTooltip")) { this.ShowTooltip.Checked = Convert.ToBoolean(this.Settings["ShowTooltip"]); } - + if (this.Settings.ContainsKey("OrderTabsByHierarchy")) { this.OrderTabsByHierarchy.Checked = Convert.ToBoolean(this.Settings["OrderTabsByHierarchy"]); } - + if (this.Settings.ContainsKey("IncludeHiddenPages")) { this.IncludeHiddenPages.Checked = Convert.ToBoolean(this.Settings["IncludeHiddenPages"]); } - + if (this.Settings.ContainsKey("ConsoleWidth")) { this.ConsoleWidth.Text = Convert.ToString(this.Settings["ConsoleWidth"]); @@ -117,7 +117,7 @@ public override void UpdateSettings() throw new Exception("ConsoleWidth value is invalid. Value must be numeric."); } } - + if (this.ParentTab.SelectedItemValueAsInt == Null.NullInteger) { ModuleController.Instance.DeleteModuleSetting(this.ModuleId, "ParentTabID"); @@ -156,6 +156,21 @@ public override void UpdateSettings() } } + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.tabs.ItemDataBound += this.tabs_ItemDataBound; + this.modeList.SelectedIndexChanged += this.modeList_SelectedIndexChanged; + + this.ParentTab.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); + } + + protected void parentTab_SelectedIndexChanged(object sender, EventArgs e) + { + this.BindTabs(this.ParentTab.SelectedItemValueAsInt, this.IncludeParent.Checked); + } + private void BindTabs(int tabId, bool includeParent) { List tempTabs = TabController.GetTabsBySortOrder(this.PortalId).OrderBy(t => t.Level).ThenBy(t => t.HasChildren).ToList(); @@ -173,25 +188,25 @@ private void BindTabs(int tabId, bool includeParent) tabList.Add(consoleTab); } } - + foreach (TabInfo tab in tempTabs) { bool canShowTab = TabPermissionController.CanViewPage(tab) && - !tab.IsDeleted && - (tab.StartDate < DateTime.Now || tab.StartDate == Null.NullDate); + !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); } } @@ -207,7 +222,7 @@ private void SwitchMode() { parentTabId = Convert.ToInt32(this.Settings["ParentTabID"]); } - + switch (this.modeList.SelectedValue) { case "Normal": @@ -232,21 +247,6 @@ private void SwitchMode() this.BindTabs(parentTabId, this.IncludeParent.Checked); } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - this.tabs.ItemDataBound += this.tabs_ItemDataBound; - this.modeList.SelectedIndexChanged += this.modeList_SelectedIndexChanged; - - this.ParentTab.UndefinedItem = new ListItem(DynamicSharedConstants.Unspecified, string.Empty); - } - - protected void parentTab_SelectedIndexChanged(object sender, EventArgs e) - { - this.BindTabs(this.ParentTab.SelectedItemValueAsInt, this.IncludeParent.Checked); - } - private void modeList_SelectedIndexChanged(object sender, EventArgs e) { this.SwitchMode(); @@ -263,7 +263,7 @@ private void tabs_ItemDataBound(object Sender, RepeaterItemEventArgs e) var tabPathField = (HiddenField)e.Item.FindControl("tabPath"); visibilityDropDown.Items.Clear(); - + // visibilityDropDown.Items.Add(new ListItem(LocalizeString("AllUsers"), "AllUsers")); visibilityDropDown.AddItem(this.LocalizeString("AllUsers"), "AllUsers"); if (this.modeList.SelectedValue == "Profile") 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 c9eb81f52b2..b9d2af66126 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.Console/ViewConsole.ascx.cs @@ -40,8 +40,8 @@ public partial class ViewConsole : PortalModuleBase public ViewConsole() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + public bool AllowSizeChange { get { return !this.Settings.ContainsKey("AllowSizeChange") || bool.Parse(this.Settings["AllowSizeChange"].ToString()); } @@ -65,7 +65,7 @@ public ConsoleController ConsoleCtrl { this._consoleCtrl = new ConsoleController(); } - + return this._consoleCtrl; } } @@ -102,12 +102,12 @@ public string DefaultSize this._defaultSize = Convert.ToString(personalizedValue); } } - + if (this._defaultSize == string.Empty) { this._defaultSize = this.Settings.ContainsKey("DefaultSize") ? Convert.ToString(this.Settings["DefaultSize"]) : "IconFile"; } - + return this._defaultSize; } } @@ -124,12 +124,12 @@ public string DefaultView this._defaultView = Convert.ToString(personalizedValue); } } - + if (this._defaultView == string.Empty) { this._defaultView = this.Settings.ContainsKey("DefaultView") ? Convert.ToString(this.Settings["DefaultView"]) : "Hide"; } - + return this._defaultView; } } @@ -143,7 +143,7 @@ public int GroupId { groupId = int.Parse(this.Request.Params["GroupId"]); } - + return groupId; } } @@ -173,7 +173,7 @@ public int ProfileUserId { userId = int.Parse(this.Request.Params["UserId"]); } - + return userId; } } @@ -189,8 +189,8 @@ public bool OrderTabsByHierarchy { return this.Settings.ContainsKey("OrderTabsByHierarchy") && bool.Parse(this.Settings["OrderTabsByHierarchy"].ToString()); } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -224,12 +224,12 @@ protected override void OnLoad(EventArgs e) { 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; @@ -263,14 +263,14 @@ protected override void OnLoad(EventArgs e) { continue; } - + if (tabIdList.Contains(tab.ParentId)) { if (!tabIdList.Contains(tab.TabID)) { tabIdList.Add(tab.TabID); } - + this._tabs.Add(tab); } } @@ -287,11 +287,11 @@ protected override void OnLoad(EventArgs e) { 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); @@ -302,7 +302,92 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + + protected string GetHtml(TabInfo tab) + { + string returnValue = string.Empty; + if (this._groupTabID > -1 && this._groupTabID != tab.ParentId) + { + this._groupTabID = -1; + if (!tab.DisableLink) + { + returnValue = "

"; + } + } + + if (tab.DisableLink) + { + const string headerHtml = "

{0}


"; + returnValue += string.Format(headerHtml, tab.TabName); + this._groupTabID = tab.TabID; + } + else + { + var sb = new StringBuilder(); + if (tab.TabID == this.PortalSettings.ActiveTab.TabID) + { + sb.Append("
"); + } + else + { + sb.Append(""); + + // const string contentHtml = "
" + "\"{3}\"\"{3}\"" + "

{3}

" + "
{4}
" + "
"; + var tabUrl = tab.FullUrl; + if (this.ProfileUserId > -1) + { + tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "UserId=" + this.ProfileUserId.ToString(CultureInfo.InvariantCulture)); + } + + if (this.GroupId > -1) + { + tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "GroupId=" + this.GroupId.ToString(CultureInfo.InvariantCulture)); + } + + returnValue += string.Format( + sb.ToString(), + tabUrl, + this.GetIconUrl(tab.IconFile, "IconFile"), + this.GetIconUrl(tab.IconFileLarge, "IconFileLarge"), + tab.LocalizedTabName, + tab.Description); + } + + return returnValue; + } + + protected string GetClientSideSettings() + { + string tmid = "-1"; + if (this.UserId > -1) + { + tmid = this.TabModuleId.ToString(CultureInfo.InvariantCulture); + } + + return string.Format( + "allowIconSizeChange: {0}, allowDetailChange: {1}, selectedSize: '{2}', showDetails: '{3}', tabModuleID: {4}, showTooltip: {5}", + this.AllowSizeChange.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), + this.AllowViewChange.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), + this.DefaultSize, + this.DefaultView, + tmid, + this.ShowTooltip.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); + } + private bool CanShowTab(TabInfo tab) { bool canShowTab = TabPermissionController.CanViewPage(tab) && @@ -335,7 +420,7 @@ private bool CanShowTab(TabInfo tab) break; } } - + return canShowTab; } @@ -345,12 +430,12 @@ private string GetIconUrl(string iconURL, string size) { iconURL = (size == "IconFile") ? "~/images/icon_unknown_16px.gif" : "~/images/icon_unknown_32px.gif"; } - + if (iconURL.Contains("~") == false) { iconURL = Path.Combine(this.PortalSettings.HomeDirectory, iconURL); } - + return this.ResolveUrl(iconURL); } @@ -377,7 +462,7 @@ private bool IsHostTab() { returnValue = this.PortalSettings.ActiveTab.IsSuperTab; } - + return returnValue; } @@ -404,7 +489,7 @@ private void SavePersonalizedSettings() consoleModuleID = -1; } - + if (consoleModuleID == this.TabModuleId) { string consoleSize = string.Empty; @@ -412,18 +497,18 @@ private void SavePersonalizedSettings() { consoleSize = this.Request.QueryString["CS"]; } - + string consoleView = string.Empty; if (this.Request.QueryString["CV"] != null) { consoleView = this.Request.QueryString["CV"]; } - + if (consoleSize != string.Empty && ConsoleController.GetSizeValues().Contains(consoleSize)) { this.SaveUserSetting("DefaultSize", consoleSize); } - + if (consoleView != string.Empty && ConsoleController.GetViewValues().Contains(consoleView)) { this.SaveUserSetting("DefaultView", consoleView); @@ -435,91 +520,6 @@ private void SavePersonalizedSettings() private void SaveUserSetting(string key, object val) { Personalization.SetProfile(this.ModuleConfiguration.ModuleDefinition.FriendlyName, this.PersonalizationKey(key), val); - } - - protected string GetHtml(TabInfo tab) - { - string returnValue = string.Empty; - if (this._groupTabID > -1 && this._groupTabID != tab.ParentId) - { - this._groupTabID = -1; - if (!tab.DisableLink) - { - returnValue = "

"; - } - } - - if (tab.DisableLink) - { - const string headerHtml = "

{0}


"; - returnValue += string.Format(headerHtml, tab.TabName); - this._groupTabID = tab.TabID; - } - else - { - var sb = new StringBuilder(); - if (tab.TabID == this.PortalSettings.ActiveTab.TabID) - { - sb.Append("
"); - } - else - { - sb.Append(""); - - // const string contentHtml = "
" + "\"{3}\"\"{3}\"" + "

{3}

" + "
{4}
" + "
"; - var tabUrl = tab.FullUrl; - if (this.ProfileUserId > -1) - { - tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "UserId=" + this.ProfileUserId.ToString(CultureInfo.InvariantCulture)); - } - - if (this.GroupId > -1) - { - tabUrl = this._navigationManager.NavigateURL(tab.TabID, string.Empty, "GroupId=" + this.GroupId.ToString(CultureInfo.InvariantCulture)); - } - - returnValue += string.Format( - sb.ToString(), - tabUrl, - this.GetIconUrl(tab.IconFile, "IconFile"), - this.GetIconUrl(tab.IconFileLarge, "IconFileLarge"), - tab.LocalizedTabName, - tab.Description); - } - - return returnValue; - } - - protected string GetClientSideSettings() - { - string tmid = "-1"; - if (this.UserId > -1) - { - tmid = this.TabModuleId.ToString(CultureInfo.InvariantCulture); - } - - return string.Format( - "allowIconSizeChange: {0}, allowDetailChange: {1}, selectedSize: '{2}', showDetails: '{3}', tabModuleID: {4}, showTooltip: {5}", - this.AllowSizeChange.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), - this.AllowViewChange.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), - this.DefaultSize, - this.DefaultView, - tmid, - this.ShowTooltip.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()); } private void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e) diff --git a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Components/BusinessController.cs b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Components/BusinessController.cs index 3ea8bc4d11c..412c85bde46 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Components/BusinessController.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Components/BusinessController.cs @@ -30,7 +30,7 @@ public string UpgradeModule(string version) break; } - + return "Success"; } catch (Exception) 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 6ad015b98f7..de7fb703e0c 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/CreateModule.ascx.cs @@ -26,12 +26,12 @@ namespace Dnn.Module.ModuleCreator public partial class CreateModule : PortalModuleBase { private readonly INavigationManager _navigationManager; - + public CreateModule() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -53,7 +53,7 @@ protected override void OnLoad(EventArgs e) { this.txtOwner.Text = HostSettings["Owner"]; } - + this.LoadLanguages(); this.LoadModuleTemplates(); this.txtControl.Text = "View"; @@ -65,7 +65,36 @@ protected override void OnLoad(EventArgs e) this.createForm.Visible = false; } } - + + protected void optLanguage_SelectedIndexChanged(object sender, EventArgs e) + { + this.LoadModuleTemplates(); + } + + protected void cboTemplate_SelectedIndexChanged(object sender, EventArgs e) + { + this.LoadReadMe(); + } + + protected void cmdCreate_Click(object sender, EventArgs e) + { + if (this.UserInfo.IsSuperUser) + { + if (!string.IsNullOrEmpty(this.txtOwner.Text) && !string.IsNullOrEmpty(this.txtModule.Text) && this.cboTemplate.SelectedIndex > 0 && !string.IsNullOrEmpty(this.txtControl.Text)) + { + HostController.Instance.Update("Owner", this.txtOwner.Text, false); + if (this.CreateModuleDefinition()) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + } + else + { + DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InputValidation.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); + } + } + } + private void LoadReadMe() { var readMePath = this.Server.MapPath(this.ControlPath) + "Templates\\" + this.optLanguage.SelectedValue + "\\" + this.cboTemplate.SelectedItem.Value + "\\readme.txt"; @@ -94,7 +123,7 @@ private void LoadLanguages() { this.optLanguage.Items.Add(new ListItem(Path.GetFileName(folderPath))); } - + this.optLanguage.SelectedIndex = 0; } @@ -110,7 +139,7 @@ private void LoadModuleTemplates() this.cboTemplate.Items.Add(new ListItem(Path.GetFileName(folderPath))); } } - + this.cboTemplate.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty)); if (this.cboTemplate.Items.FindByText("Module - User Control") != null) { @@ -120,7 +149,7 @@ private void LoadModuleTemplates() { this.cboTemplate.SelectedIndex = 0; } - + this.LoadReadMe(); } @@ -139,7 +168,7 @@ private string CreateModuleControl() var moduleTemplatePath = this.Server.MapPath(this.ControlPath) + "Templates\\" + this.optLanguage.SelectedValue + "\\" + this.cboTemplate.SelectedValue + "\\"; EventLogController.Instance.AddLog("Processing Template Folder", moduleTemplatePath, this.PortalSettings, -1, EventLogController.EventLogType.HOST_ALERT); - + var controlName = Null.NullString; var fileName = Null.NullString; var modulePath = string.Empty; @@ -190,14 +219,14 @@ private string CreateModuleControl() { modulePath = modulePath.Replace("DesktopModules", "App_Code"); } - + break; case ".cs": if (filePath.ToLowerInvariant().IndexOf(".ascx") == -1) { modulePath = modulePath.Replace("DesktopModules", "App_Code"); } - + break; case ".js": modulePath = modulePath + "\\js\\"; @@ -246,7 +275,7 @@ private string GetFolderName() { var strFolder = Null.NullString; strFolder += this.txtOwner.Text + "/" + this.txtModule.Text; - + // return folder and remove any spaces that might appear in folder structure return strFolder.Replace(" ", string.Empty); } @@ -255,11 +284,11 @@ private string GetClassName() { var strClass = Null.NullString; strClass += this.txtOwner.Text + "." + this.txtModule.Text; - + // return class and remove any spaces that might appear in class name return strClass.Replace(" ", string.Empty); } - + /// /// /// @@ -327,12 +356,12 @@ private bool CreateModuleDefinition() termId = term.TermId; } } - + if (termId == -1) { termId = objTermController.AddTerm(new Term(vocabularyId) { Name = this.txtOwner.Text }); } - + var objTerm = objTermController.GetTerm(termId); var objContentController = DotNetNuke.Entities.Content.Common.Util.GetContentController(); var objContent = objContentController.GetContentItem(objDesktopModule.ContentItemId); @@ -345,10 +374,10 @@ private bool CreateModuleDefinition() var objModuleDefinition = new ModuleDefinitionInfo(); objModuleDefinition.ModuleDefID = Null.NullInteger; objModuleDefinition.DesktopModuleID = objDesktopModule.DesktopModuleID; - + // need core enhancement to have a unique DefinitionName objModuleDefinition.FriendlyName = this.GetClassName(); - + // objModuleDefinition.FriendlyName = txtModule.Text; // objModuleDefinition.DefinitionName = GetClassName(); objModuleDefinition.DefaultCacheTime = 0; @@ -402,35 +431,6 @@ private bool CreateModuleDefinition() DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.ToString(), ModuleMessage.ModuleMessageType.RedError); return false; } - } - - protected void optLanguage_SelectedIndexChanged(object sender, EventArgs e) - { - this.LoadModuleTemplates(); } - - protected void cboTemplate_SelectedIndexChanged(object sender, EventArgs e) - { - this.LoadReadMe(); - } - - protected void cmdCreate_Click(object sender, EventArgs e) - { - if (this.UserInfo.IsSuperUser) - { - if (!string.IsNullOrEmpty(this.txtOwner.Text) && !string.IsNullOrEmpty(this.txtModule.Text) && this.cboTemplate.SelectedIndex > 0 && !string.IsNullOrEmpty(this.txtControl.Text)) - { - HostController.Instance.Update("Owner", this.txtOwner.Text, false); - if (this.CreateModuleDefinition()) - { - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - } - else - { - DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("InputValidation.ErrorMessage", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); - } - } - } } } diff --git a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/C#/Module - Inline Script/template.ascx b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/C#/Module - Inline Script/template.ascx index ed674fa40d8..292e8c0f25b 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/C#/Module - Inline Script/template.ascx +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/C#/Module - Inline Script/template.ascx @@ -5,20 +5,18 @@ <%@ Import Namespace="DotNetNuke.Entities.Modules" %> diff --git a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/Web/Module - HTML/template.ascx b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/Web/Module - HTML/template.ascx index 879e816f5f3..7b9f29f4ee7 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/Web/Module - HTML/template.ascx +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/Templates/Web/Module - HTML/template.ascx @@ -7,8 +7,6 @@ <%@ Import Namespace="System.IO" %> 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 24579a9b814..40605360f02 100644 --- a/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs +++ b/DNN Platform/Admin Modules/Dnn.Modules.ModuleCreator/viewsource.ascx.cs @@ -25,12 +25,12 @@ namespace Dnn.Module.ModuleCreator public partial class ViewSource : PortalModuleBase { private readonly INavigationManager _navigationManager; - + public ViewSource() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + protected int ModuleControlId { get @@ -40,7 +40,7 @@ protected int ModuleControlId { moduleControlId = int.Parse(this.Request.QueryString["ctlid"]); } - + return moduleControlId; } } @@ -51,8 +51,8 @@ private string ReturnURL { return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -93,7 +93,7 @@ protected override void OnLoad(EventArgs e) { this.cboTemplate.Items.FindByText("Module - User Control").Selected = true; } - + this.LoadReadMe(); } } @@ -102,7 +102,17 @@ protected void OnFileIndexChanged(object sender, EventArgs e) { this.LoadFile(); } - + + protected void OnLanguageSelectedIndexChanged(object sender, EventArgs e) + { + this.LoadModuleTemplates(); + } + + protected void cboTemplate_SelectedIndexChanged(object sender, EventArgs e) + { + this.LoadReadMe(); + } + private void BindFiles(string controlSrc) { string[] fileList; @@ -130,7 +140,7 @@ private void BindFiles(string controlSrc) { this.cboFile.Items.Add(new ListItem(filePath.Substring(modulePath.Length), resxPath)); } - + break; case ".vb": case ".cs": @@ -153,7 +163,7 @@ private void BindFiles(string controlSrc) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("FolderNameInvalid", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } - + // iterate through files in app_code folder modulePath = Globals.ApplicationMapPath + "\\App_Code\\" + objDesktopModule.FolderName.Replace("/", "\\") + "\\"; if (Directory.Exists(modulePath)) @@ -219,7 +229,7 @@ private void SetFileType(string filePath) mimeType = "text/html"; break; } - + DotNetNuke.UI.Utilities.ClientAPI.RegisterClientVariable(this.Page, "mimeType", mimeType, true); } @@ -256,13 +266,13 @@ private void LoadLanguages() { language = "VB"; } - + if (objFile.Text.EndsWith(".cs")) { language = "C#"; } } - + if (language == string.Empty) { this.optLanguage.SelectedIndex = 0; @@ -282,7 +292,7 @@ private void LoadModuleTemplates() { this.cboTemplate.Items.Add(new ListItem(Path.GetFileName(folderPath))); } - + this.cboTemplate.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty)); } @@ -297,7 +307,7 @@ private void LoadReadMe() readMe = tr.ReadToEnd(); tr.Close(); } - + this.lblDescription.Text = readMe.Replace("\n", "
"); } else @@ -324,7 +334,7 @@ private void LoadReadMe() } } } - + this.txtControl.Text = controlName; this.txtControl.Enabled = controlNameRequired; if (this.txtControl.Enabled) @@ -347,9 +357,9 @@ private string CreateModuleControl() var objPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == objDesktopModule.PackageID); var moduleTemplatePath = this.Server.MapPath(this.ControlPath) + "Templates\\" + this.optLanguage.SelectedValue + "\\" + this.cboTemplate.SelectedValue + "\\"; - + EventLogController.Instance.AddLog("Processing Template Folder", moduleTemplatePath, this.PortalSettings, -1, EventLogController.EventLogType.HOST_ALERT); - + var controlName = Null.NullString; var fileName = Null.NullString; var modulePath = Null.NullString; @@ -374,7 +384,7 @@ private string CreateModuleControl() { owner = "DNN"; } - + sourceCode = sourceCode.Replace("_OWNER_", owner); sourceCode = sourceCode.Replace("_MODULE_", objDesktopModule.FriendlyName.Replace(" ", string.Empty)); sourceCode = sourceCode.Replace("_CONTROL_", this.GetControl()); @@ -406,14 +416,14 @@ private string CreateModuleControl() { modulePath = modulePath.Replace("DesktopModules", "App_Code"); } - + break; case ".cs": if (filePath.ToLowerInvariant().IndexOf(".ascx") == -1) { modulePath = modulePath.Replace("DesktopModules", "App_Code"); } - + break; case ".js": modulePath = modulePath + "\\js\\"; @@ -474,16 +484,6 @@ private string CreateModuleControl() private string GetControl() { return this.txtControl.Text.Replace(" ", string.Empty); - } - - protected void OnLanguageSelectedIndexChanged(object sender, EventArgs e) - { - this.LoadModuleTemplates(); - } - - protected void cboTemplate_SelectedIndexChanged(object sender, EventArgs e) - { - this.LoadReadMe(); } private void OnUpdateClick(object sender, EventArgs e) @@ -521,6 +521,6 @@ private void OnCreateClick(object sender, EventArgs e) { DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("AddControlError", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); } - } + } } } diff --git a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs index 40bab23156f..e9d31536988 100644 --- a/DNN Platform/Connectors/Azure/Components/AzureConnector.cs +++ b/DNN Platform/Connectors/Azure/Components/AzureConnector.cs @@ -21,7 +21,7 @@ namespace Dnn.AzureConnector.Components using Microsoft.WindowsAzure.Storage.RetryPolicies; public class AzureConnector : IConnector - { + { private const string DefaultDisplayName = "Azure Storage"; private static readonly DataProvider dataProvider = DataProvider.Instance(); @@ -31,23 +31,12 @@ public string Name { get { return "Azure"; } } - - public string DisplayName - { - get - { - return - string.IsNullOrEmpty(this._displayName) ? DefaultDisplayName : this._displayName; - } - - set { this._displayName = value; } - } public string IconUrl { get { return "~/DesktopModules/Connectors/Azure/Images/Azure.png"; } } - + public string PluginFolder { get { return "~/DesktopModules/Connectors/Azure/"; } @@ -61,12 +50,23 @@ public bool IsEngageConnector } } - public string Id { get; set; } - public ConnectorCategories Type => ConnectorCategories.FileSystem; - public bool SupportsMultiple => true; - + public bool SupportsMultiple => true; + + public string DisplayName + { + get + { + return + string.IsNullOrEmpty(this._displayName) ? DefaultDisplayName : this._displayName; + } + + set { this._displayName = value; } + } + + public string Id { get; set; } + public IEnumerable GetConnectors(int portalId) { var connectors = this.FindAzureFolderMappings(portalId); @@ -81,7 +81,7 @@ public IEnumerable GetConnectors(int portalId) }); return finalCon; } - + return new List { this }; } @@ -112,7 +112,7 @@ public IDictionary GetConfig(int portalId) var folderMapping = this.FindAzureFolderMapping(portalId, false); var settings = folderMapping != null ? folderMapping.FolderMappingSettings : new Hashtable(); - + configs.Add("AccountName", this.GetSetting(settings, Constants.AzureAccountName, true)); configs.Add("AccountKey", this.GetSetting(settings, Constants.AzureAccountKey, true)); configs.Add("Container", this.GetSetting(settings, Constants.AzureContainerName)); @@ -136,21 +136,21 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo validated = true; if (emptyFields) { - if (this.SupportsMultiple) - { - throw new Exception(Localization.GetString("ErrorRequiredFields", Constants.LocalResourceFile)); - } - + if (this.SupportsMultiple) + { + throw new Exception(Localization.GetString("ErrorRequiredFields", Constants.LocalResourceFile)); + } + DeleteAzureFolderMapping(portalId); return true; } - + if (!this.Validation(azureAccountName, azureAccountKey, azureContainerName)) { validated = false; return true; } - + if (this.FolderMappingNameExists(portalId, this.DisplayName, Convert.ToInt32(!string.IsNullOrEmpty(this.Id) ? this.Id : null))) { @@ -207,18 +207,18 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo { folderMapping.FolderMappingSettings[Constants.DirectLink] = "True"; } - + if (!folderMapping.FolderMappingSettings.ContainsKey(Constants.UseHttps)) { folderMapping.FolderMappingSettings[Constants.UseHttps] = "True"; } - + if (folderMapping.MappingName != this.DisplayName && !string.IsNullOrEmpty(this.DisplayName) && this.DisplayName != DefaultDisplayName) { folderMapping.MappingName = this.DisplayName; } - + if (!folderMapping.FolderMappingSettings.ContainsKey(Constants.SyncBatchSize)) { folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = Constants.DefaultSyncBatchSize.ToString(); @@ -233,7 +233,7 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo Exceptions.LogException(ex); return false; } - } + } internal static FolderMappingInfo FindAzureFolderMappingStatic(int portalId, int? folderMappingId = null, bool autoCreate = true) @@ -241,16 +241,16 @@ internal static FolderMappingInfo FindAzureFolderMappingStatic(int portalId, int var folderMappings = FolderMappingController.Instance.GetFolderMappings(portalId) .Where(f => f.FolderProviderType == Constants.FolderProviderType); - if (folderMappingId != null) - { - return folderMappings.FirstOrDefault(x => x.FolderMappingID == folderMappingId); - } - + if (folderMappingId != null) + { + return folderMappings.FirstOrDefault(x => x.FolderMappingID == folderMappingId); + } + if (!folderMappings.Any() && autoCreate) { return CreateAzureFolderMappingStatic(portalId); } - + return folderMappings.FirstOrDefault(); } @@ -273,25 +273,91 @@ 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) + .FirstOrDefault(f => f.FolderProviderType == Constants.FolderProviderType); + + if (folderMapping != null) + { + FolderMappingController.Instance.DeleteFolderMapping(portalId, folderMapping.FolderMappingID); + } + } + + private static void DeleteAzureFolders(int portalId, int folderMappingId) + { + var folderManager = FolderManager.Instance; + var folders = folderManager.GetFolders(portalId); + + var folderMappingFolders = folders.Where(f => f.FolderMappingID == folderMappingId); + + if (folderMappingFolders.Any()) + { + // Delete files in folders with the provided mapping (only in the database) + foreach ( + var file in + folderMappingFolders.Select>(folderManager.GetFiles) + .SelectMany(files => files)) + { + dataProvider.DeleteFile(portalId, file.FileName, file.FolderId); + } + + // Remove the folders with the provided mapping that doesn't have child folders with other mapping (only in the database and filesystem) + var folders1 = folders; // copy the variable to not access a modified closure + var removableFolders = + folders.Where( + f => f.FolderMappingID == folderMappingId && !folders1.Any(f2 => f2.FolderID != f.FolderID && + f2.FolderPath.StartsWith( + f.FolderPath) && + f2.FolderMappingID != + folderMappingId)); + + if (removableFolders.Count() > 0) + { + foreach (var removableFolder in removableFolders.OrderByDescending(rf => rf.FolderPath)) + { + DirectoryWrapper.Instance.Delete(removableFolder.PhysicalPath, false); + dataProvider.DeleteFolder(portalId, removableFolder.FolderPath); + } + } + + // Update the rest of folders with the provided mapping to use the standard mapping + folders = folderManager.GetFolders(portalId, false); // re-fetch the folders + + folderMappingFolders = folders.Where(f => f.FolderMappingID == folderMappingId); + + if (folderMappingFolders.Count() > 0) + { + var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); + + foreach (var folderMappingFolder in folderMappingFolders) + { + folderMappingFolder.FolderMappingID = defaultFolderMapping.FolderMappingID; + folderManager.UpdateFolder(folderMappingFolder); + } + } + } + } + private bool Validation(string azureAccountName, string azureAccountKey, string azureContainerName) { try { if (string.IsNullOrWhiteSpace(azureAccountName)) { - throw new ConnectorArgumentException(Localization.GetString( + throw new ConnectorArgumentException(Localization.GetString( "AccountNameCannotBeEmpty.ErrorMessage", Constants.LocalResourceFile)); } - + if (string.IsNullOrWhiteSpace(azureAccountKey)) { - throw new ConnectorArgumentException(Localization.GetString( + throw new ConnectorArgumentException(Localization.GetString( "AccountKeyCannotBeEmpty.ErrorMessage", Constants.LocalResourceFile)); } - + StorageCredentials sc = new StorageCredentials(azureAccountName, azureAccountKey); var csa = new CloudStorageAccount(sc, true); var blobClient = csa.CreateCloudBlobClient(); @@ -305,7 +371,7 @@ private bool Validation(string azureAccountName, string azureAccountKey, string { if (!containers.Any(container => container.Name == azureContainerName)) { - throw new Exception(Localization.GetString( + throw new Exception(Localization.GetString( "ErrorInvalidContainerName", Constants.LocalResourceFile)); } @@ -321,7 +387,7 @@ private bool Validation(string azureAccountName, string azureAccountKey, string } else { - throw new Exception(Localization.GetString( + throw new Exception(Localization.GetString( "AccountNotFound.ErrorMessage", Constants.LocalResourceFile)); } @@ -332,13 +398,13 @@ private bool Validation(string azureAccountName, string azureAccountKey, string { if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "AccountNotFound") { - throw new Exception(Localization.GetString( + throw new Exception(Localization.GetString( "AccountNotFound.ErrorMessage", Constants.LocalResourceFile)); } else if (ex.RequestInformation.ExtendedErrorInformation.ErrorCode == "AccessDenied") { - throw new Exception(Localization.GetString( + throw new Exception(Localization.GetString( "AccessDenied.ErrorMessage", Constants.LocalResourceFile)); } @@ -354,12 +420,12 @@ private bool Validation(string azureAccountName, string azureAccountKey, string { if (ex.GetType() == typeof(UriFormatException)) { - throw new ConnectorArgumentException(Localization.GetString( + throw new ConnectorArgumentException(Localization.GetString( "InvalidAccountName.ErrorMessage", Constants.LocalResourceFile)); } - - throw new ConnectorArgumentException(Localization.GetString( + + throw new ConnectorArgumentException(Localization.GetString( "InvalidAccountKey.ErrorMessage", Constants.LocalResourceFile)); } @@ -392,18 +458,18 @@ private FolderMappingInfo FindAzureFolderMapping(int portalId, bool autoCreate = return this.CreateAzureFolderMapping(portalId, DefaultDisplayName); } - if ((checkId && string.IsNullOrEmpty(this.Id)) || !this.SupportsMultiple) - { - return folderMappings.FirstOrDefault(); - } - + if ((checkId && string.IsNullOrEmpty(this.Id)) || !this.SupportsMultiple) + { + return folderMappings.FirstOrDefault(); + } + var folderMapping = folderMappings.FirstOrDefault(x => x.FolderMappingID.ToString() == this.Id); if (folderMapping == null && autoCreate) { folderMapping = this.CreateAzureFolderMapping(portalId); } - + return folderMapping; } @@ -428,71 +494,5 @@ private FolderMappingInfo CreateAzureFolderMapping(int portalId, string mappingN this.Id = folderMapping.FolderMappingID.ToString(); return folderMapping; } - - private static void DeleteAzureFolderMapping(int portalId) - { - var folderMapping = FolderMappingController.Instance.GetFolderMappings(portalId) - .FirstOrDefault(f => f.FolderProviderType == Constants.FolderProviderType); - - if (folderMapping != null) - { - FolderMappingController.Instance.DeleteFolderMapping(portalId, folderMapping.FolderMappingID); - } - } - - private static void DeleteAzureFolders(int portalId, int folderMappingId) - { - var folderManager = FolderManager.Instance; - var folders = folderManager.GetFolders(portalId); - - var folderMappingFolders = folders.Where(f => f.FolderMappingID == folderMappingId); - - if (folderMappingFolders.Any()) - { - // Delete files in folders with the provided mapping (only in the database) - foreach ( - var file in - folderMappingFolders.Select>(folderManager.GetFiles) - .SelectMany(files => files)) - { - dataProvider.DeleteFile(portalId, file.FileName, file.FolderId); - } - - // Remove the folders with the provided mapping that doesn't have child folders with other mapping (only in the database and filesystem) - var folders1 = folders; // copy the variable to not access a modified closure - var removableFolders = - folders.Where( - f => f.FolderMappingID == folderMappingId && !folders1.Any(f2 => f2.FolderID != f.FolderID && - f2.FolderPath.StartsWith( - f.FolderPath) && - f2.FolderMappingID != - folderMappingId)); - - if (removableFolders.Count() > 0) - { - foreach (var removableFolder in removableFolders.OrderByDescending(rf => rf.FolderPath)) - { - DirectoryWrapper.Instance.Delete(removableFolder.PhysicalPath, false); - dataProvider.DeleteFolder(portalId, removableFolder.FolderPath); - } - } - - // Update the rest of folders with the provided mapping to use the standard mapping - folders = folderManager.GetFolders(portalId, false); // re-fetch the folders - - folderMappingFolders = folders.Where(f => f.FolderMappingID == folderMappingId); - - if (folderMappingFolders.Count() > 0) - { - var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - - foreach (var folderMappingFolder in folderMappingFolders) - { - folderMappingFolder.FolderMappingID = defaultFolderMapping.FolderMappingID; - folderManager.UpdateFolder(folderMappingFolder); - } - } - } - } } } diff --git a/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs b/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs index 91e339f88b0..741eaa07914 100644 --- a/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Connectors/Azure/Services/ServiceRouteMapper.cs @@ -10,7 +10,7 @@ public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute routeManager) { - routeManager.MapHttpRoute( + routeManager.MapHttpRoute( "AzureConnector", "default", "{controller}/{action}", diff --git a/DNN Platform/Connectors/Azure/Services/ServicesController.cs b/DNN Platform/Connectors/Azure/Services/ServicesController.cs index cac68790f5c..7db2704a206 100644 --- a/DNN Platform/Connectors/Azure/Services/ServicesController.cs +++ b/DNN Platform/Connectors/Azure/Services/ServicesController.cs @@ -17,7 +17,7 @@ namespace Dnn.AzureConnector.Services [DnnAuthorize] public class ServicesController : DnnApiController - { + { [HttpGet] public HttpResponseMessage GetAllContainers(int id) { @@ -51,6 +51,6 @@ public HttpResponseMessage GetAllContainers(int id) public HttpResponseMessage GetFolderMappingId() { return this.Request.CreateResponse(HttpStatusCode.OK, Components.AzureConnector.FindAzureFolderMappingStatic(this.PortalSettings.PortalId).FolderMappingID); - } + } } } diff --git a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs index 94f4c297d43..2b176b52ad7 100644 --- a/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs +++ b/DNN Platform/Connectors/GoogleAnalytics/GoogleAnalyticsConnector.cs @@ -14,7 +14,7 @@ namespace DNN.Connectors.GoogleAnalytics using DotNetNuke.Services.Localization; public class GoogleAnalyticsConnector : IConnector - { + { private const string DefaultDisplayName = "Google Analytics"; private string _displayName; @@ -24,17 +24,6 @@ public string Name get { return "Core Google Analytics Connector"; } } - public string DisplayName - { - get - { - return - string.IsNullOrEmpty(this._displayName) ? DefaultDisplayName : this._displayName; - } - - set { this._displayName = value; } - } - public string IconUrl { get { return "~/DesktopModules/Connectors/GoogleAnalytics/Images/GoogleAnalytics_32X32_Standard.png"; } @@ -53,13 +42,24 @@ public bool IsEngageConnector } } - public string Id { get; set; } - public ConnectorCategories Type => ConnectorCategories.Analytics; // As of DNN 9.2.2 you need to support multiple to get access to the Delete Connection functionality - public bool SupportsMultiple => false; - + public bool SupportsMultiple => false; + + public string DisplayName + { + get + { + return + string.IsNullOrEmpty(this._displayName) ? DefaultDisplayName : this._displayName; + } + + set { this._displayName = value; } + } + + public string Id { get; set; } + public IEnumerable GetConnectors(int portalId) { return new List { this }; @@ -225,7 +225,7 @@ public bool SaveConfig(int portalId, IDictionary values, ref boo Exceptions.LogException(ex); return false; } - } + } /// /// Handles custom conversion from "true" => "true" @@ -239,7 +239,7 @@ private string HandleCustomBoolean(string value) { return "true"; } - + return string.Empty; } } diff --git a/DNN Platform/Controls/CountryListBox/CountryListBox.cs b/DNN Platform/Controls/CountryListBox/CountryListBox.cs index b958e2d6935..821446551b0 100644 --- a/DNN Platform/Controls/CountryListBox/CountryListBox.cs +++ b/DNN Platform/Controls/CountryListBox/CountryListBox.cs @@ -18,8 +18,8 @@ public class CountryListBox : DropDownList private string _LocalhostCountryCode; private string _TestIP; - [Bindable(true)] - [Category("Caching")] + [Bindable(true)] + [Category("Caching")] [DefaultValue(true)] public bool CacheGeoIPData { @@ -27,7 +27,7 @@ public bool CacheGeoIPData { return this._CacheGeoIPData; } - + set { this._CacheGeoIPData = value; @@ -38,8 +38,8 @@ public bool CacheGeoIPData } } - [Bindable(true)] - [Category("Appearance")] + [Bindable(true)] + [Category("Appearance")] [DefaultValue("")] public string GeoIPFile { @@ -47,15 +47,15 @@ public string GeoIPFile { return this._GeoIPFile; } - + set { this._GeoIPFile = value; } } - [Bindable(true)] - [Category("Appearance")] + [Bindable(true)] + [Category("Appearance")] [DefaultValue("")] public string TestIP { @@ -63,15 +63,15 @@ public string TestIP { return this._TestIP; } - + set { this._TestIP = value; } } - [Bindable(true)] - [Category("Appearance")] + [Bindable(true)] + [Category("Appearance")] [DefaultValue("")] public string LocalhostCountryCode { @@ -79,7 +79,7 @@ public string LocalhostCountryCode { return this._LocalhostCountryCode; } - + set { this._LocalhostCountryCode = value; @@ -97,9 +97,9 @@ protected override void OnDataBinding(EventArgs e) { this._GeoIPFile = "controls/CountryListBox/Data/GeoIP.dat"; } - + this.EnsureChildControls(); - + // Check to see if a TestIP is specified if (!string.IsNullOrEmpty(this._TestIP)) { @@ -110,7 +110,7 @@ protected override void OnDataBinding(EventArgs e) { // The country cannot be detected because the user is local. IsLocal = true; - + // Set the IP address in case they didn't specify LocalhostCountryCode IP = this.Page.Request.UserHostAddress; } @@ -133,7 +133,7 @@ protected override void OnDataBinding(EventArgs e) { // Bing the data base.OnDataBinding(e); - + // Pre-Select the value in the drop-down based // on the LocalhostCountryCode specified. if (this.Items.FindByValue(this._LocalhostCountryCode) != null) @@ -159,7 +159,7 @@ protected override void OnDataBinding(EventArgs e) // No, get it from file _CountryLookup = new CountryLookup(this.Context.Server.MapPath(this._GeoIPFile)); } - + // Get the country code based on the IP address string _UserCountryCode = _CountryLookup.LookupCountryCode(IP); @@ -184,7 +184,7 @@ protected override void OnDataBinding(EventArgs e) newItem.Value = _UserCountryCode; newItem.Text = _UserCountry; this.Items.Insert(0, newItem); - + // Now let's Pre-Select it this.Items.FindByValue(_UserCountryCode).Selected = true; } diff --git a/DNN Platform/Controls/CountryListBox/CountryLookup.cs b/DNN Platform/Controls/CountryListBox/CountryLookup.cs index 41c676e5270..ef444bd6830 100644 --- a/DNN Platform/Controls/CountryListBox/CountryLookup.cs +++ b/DNN Platform/Controls/CountryListBox/CountryLookup.cs @@ -9,8 +9,6 @@ namespace DotNetNuke.UI.WebControls public class CountryLookup { - private static long CountryBegin = 16776960; - private static readonly string[] CountryName = new[] { "N/A", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", @@ -59,6 +57,8 @@ public class CountryLookup "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "YU", "ZA", "ZM", "ZR", "ZW", "A1", "A2", }; + private static long CountryBegin = 16776960; + public CountryLookup(MemoryStream ms) { this.m_MemoryStream = ms; @@ -77,7 +77,7 @@ public CountryLookup(string FileLocation) { this.m_MemoryStream.Write(_Byte, 0, _Byte.Length); } - + _FileStream.Close(); } } @@ -98,7 +98,7 @@ public static MemoryStream FileToMemory(string FileLocation) { _MemStream.Write(_Byte, 0, _Byte.Length); } - + _FileStream.Close(); } } @@ -107,7 +107,7 @@ public static MemoryStream FileToMemory(string FileLocation) throw new Exception(exc.Message + " Please set the \"GeoIPFile\" Property to specify the location of this file. The property value must be set to the virtual path to GeoIP.dat (i.e. \"/controls/CountryListBox/Data/GeoIP.dat\")"); } - + return _MemStream; } @@ -117,30 +117,6 @@ 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 @@ -153,7 +129,7 @@ public string LookupCountryCode(string _IPAddress) { return "--"; } - + return this.LookupCountryCode(_Address); } @@ -175,7 +151,7 @@ public string LookupCountryName(string _IPAddress) { return "N/A"; } - + return this.LookupCountryName(_Address); } @@ -192,7 +168,7 @@ public int SeekCountry(int Offset, long Ipnum, short Depth) { throw new Exception(); } - + this.m_MemoryStream.Seek(6 * Offset, 0); var len = this.m_MemoryStream.Read(Buffer, 0, 6); if (len == 6) @@ -207,7 +183,7 @@ public int SeekCountry(int Offset, long Ipnum, short Depth) { Y = Convert.ToByte(Y + 256); } - + X[I] = Convert.ToInt32(X[I] + (Y << (J * 8))); } } @@ -226,7 +202,7 @@ public int SeekCountry(int Offset, long Ipnum, short Depth) { return Convert.ToInt32(X[1] - CountryBegin); } - + return this.SeekCountry(X[1], Ipnum, Convert.ToInt16(Depth - 1)); } else @@ -235,7 +211,7 @@ public int SeekCountry(int Offset, long Ipnum, short Depth) { return Convert.ToInt32(X[0] - CountryBegin); } - + return this.SeekCountry(X[0], Ipnum, Convert.ToInt16(Depth - 1)); } } @@ -244,5 +220,29 @@ public int SeekCountry(int Offset, long Ipnum, short Depth) throw new Exception("Error seeking country: " + exc.Message); } } + + 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; + } } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs b/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs index 465c0466e7b..9cb16b9dc78 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Auth/JwtAuthMessageHandler.cs @@ -21,11 +21,11 @@ namespace Dnn.AuthServices.Jwt.Auth /// - Introduction to JSON Web Tokens http://jwt.io/introduction/. /// public class JwtAuthMessageHandler : AuthMessageHandlerBase - { + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JwtAuthMessageHandler)); - - private readonly IJwtController _jwtController = JwtController.Instance; - + + private readonly IJwtController _jwtController = JwtController.Instance; + public JwtAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { @@ -33,14 +33,14 @@ public JwtAuthMessageHandler(bool includeByDefault, bool forceSsl) // ServicesRoutingManager.RegisterAuthenticationHandlers() // 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) { if (this.NeedsAuthentication(request)) @@ -58,11 +58,11 @@ private void TryToAuthenticate(HttpRequestMessage request) var username = this._jwtController.ValidateToken(request); if (!string.IsNullOrEmpty(username)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace($"Authenticated user '{username}'"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace($"Authenticated user '{username}'"); + } + SetCurrentPrincipal(new GenericPrincipal(new GenericIdentity(username, this.AuthScheme), null), request); } } @@ -70,6 +70,6 @@ private void TryToAuthenticate(HttpRequestMessage request) { Logger.Error("Unexpected error in authenticating the user. " + ex); } - } + } } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/IJwtController.cs b/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/IJwtController.cs index e73b003b0bd..cb7dcefed46 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/IJwtController.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/IJwtController.cs @@ -11,13 +11,13 @@ namespace Dnn.AuthServices.Jwt.Components.Common.Controllers public interface IJwtController { string SchemeType { get; } - + string ValidateToken(HttpRequestMessage request); - + bool LogoutUser(HttpRequestMessage request); - + LoginResultData LoginUser(HttpRequestMessage request, LoginData loginData); - + LoginResultData RenewToken(HttpRequestMessage request, string renewalToken); } } 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 b0f5754a8d6..52f03ba7ed4 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Common/Controllers/JwtController.cs @@ -26,27 +26,27 @@ namespace Dnn.AuthServices.Jwt.Components.Common.Controllers using Newtonsoft.Json; internal class JwtController : ServiceLocator, IJwtController - { + { public const string AuthScheme = "Bearer"; + public readonly IDataService DataProvider = DataService.Instance; - 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 ILog Logger = LoggerSource.Instance.GetLogger(typeof(JwtController)); + private static readonly HashAlgorithm Hasher = SHA384.Create(); private static readonly Encoding TextEncoder = Encoding.UTF8; - - public string SchemeType => "JWT"; - + + public string SchemeType => "JWT"; + 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. - /// + /// /// public string ValidateToken(HttpRequestMessage request) { @@ -78,26 +78,21 @@ public bool LogoutUser(HttpRequestMessage request) var sessionId = GetJwtSessionValue(jwt); if (string.IsNullOrEmpty(sessionId)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Session ID not found in the claim"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Session ID not found in the claim"); + } + return false; } this.DataProvider.DeleteToken(sessionId); return true; } - - protected override Func GetFactory() - { - return () => new JwtController(); - } /// /// Validates user login credentials and returns result when successful. - /// + /// /// public LoginResultData LoginUser(HttpRequestMessage request, LoginData loginData) { @@ -116,7 +111,7 @@ public LoginResultData LoginUser(HttpRequestMessage request, LoginData loginData var status = UserLoginStatus.LOGIN_FAILURE; var ipAddress = request.GetIPAddress() ?? string.Empty; - var userInfo = UserController.ValidateUser( + var userInfo = UserController.ValidateUser( portalSettings.PortalId, loginData.Username, loginData.Password, "DNN", string.Empty, AuthScheme, ipAddress, ref status); @@ -190,79 +185,84 @@ public LoginResultData RenewToken(HttpRequestMessage request, string renewalToke var sessionId = GetJwtSessionValue(jwt); if (string.IsNullOrEmpty(sessionId)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Session ID not found in the claim"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Session ID not found in the claim"); + } + return EmptyWithError("bad-claims"); } var ptoken = this.DataProvider.GetTokenById(sessionId); if (ptoken == null) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token not found in DB"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token not found in DB"); + } + return EmptyWithError("not-found"); } if (ptoken.RenewalExpiry <= DateTime.UtcNow) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token can't bwe renewed anymore"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token can't bwe renewed anymore"); + } + return EmptyWithError("not-more-renewal"); } if (ptoken.RenewalHash != GetHashedStr(renewalToken)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Invalid renewal token"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Invalid renewal token"); + } + return EmptyWithError("bad-token"); } if (ptoken.TokenHash != GetHashedStr(rawToken)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Invalid access token"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Invalid access token"); + } + return EmptyWithError("bad-token"); } var userInfo = this.TryGetUser(jwt, false); if (userInfo == null) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("User not found in DB"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("User not found in DB"); + } + return EmptyWithError("not-found"); } if (ptoken.UserId != userInfo.UserID) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Mismatch token and user"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mismatch token and user"); + } + return EmptyWithError("bad-token"); } return this.UpdateToken(renewalToken, ptoken, userInfo); } + protected override Func GetFactory() + { + return () => new JwtController(); + } + private static LoginResultData EmptyWithError(string error) { return new LoginResultData { Error = error }; @@ -287,35 +287,6 @@ private static JwtSecurityToken CreateJwtToken(byte[] symmetricKey, string issue return token; } - private LoginResultData UpdateToken(string renewalToken, PersistedToken ptoken, UserInfo userInfo) - { - var expiry = DateTime.UtcNow.AddMinutes(SessionTokenTtl); - if (expiry > ptoken.RenewalExpiry) - { - // don't extend beyond renewal expiry and make sure it is marked in UTC - expiry = new DateTime(ptoken.RenewalExpiry.Ticks, DateTimeKind.Utc); - } - - ptoken.TokenExpiry = expiry; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var secret = ObtainSecret(ptoken.TokenId, portalSettings.GUID, userInfo.Membership.LastPasswordChangeDate); - var jwt = CreateJwtToken(secret, portalSettings.PortalAlias.HTTPAlias, ptoken, userInfo.Roles); - var accessToken = jwt.RawData; - - // save hash values in DB so no one with access can create JWT header from existing data - ptoken.TokenHash = GetHashedStr(accessToken); - this.DataProvider.UpdateToken(ptoken); - - return new LoginResultData - { - UserId = userInfo.UserID, - DisplayName = userInfo.DisplayName, - AccessToken = accessToken, - RenewalToken = renewalToken, - }; - } - private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExpiry) { JwtSecurityToken jwt; @@ -334,11 +305,11 @@ private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExp var now = DateTime.UtcNow; if (now < jwt.ValidFrom || now > jwt.ValidTo) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token is expired"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token is expired"); + } + return null; } } @@ -346,11 +317,11 @@ private static JwtSecurityToken GetAndValidateJwt(string rawToken, bool checkExp var sessionId = GetJwtSessionValue(jwt); if (string.IsNullOrEmpty(sessionId)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Invaid session ID claim"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Invaid session ID claim"); + } + return null; } @@ -370,6 +341,57 @@ private static byte[] ObtainSecret(string sessionId, Guid portalGuid, DateTime u return TextEncoder.GetBytes(stext); } + 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)); + } + + private static string EncodeBase64(byte[] data) + { + return Convert.ToBase64String(data).TrimEnd('='); + } + + private static string GetHashedStr(string data) + { + return EncodeBase64(Hasher.ComputeHash(TextEncoder.GetBytes(data))); + } + + private LoginResultData UpdateToken(string renewalToken, PersistedToken ptoken, UserInfo userInfo) + { + var expiry = DateTime.UtcNow.AddMinutes(SessionTokenTtl); + if (expiry > ptoken.RenewalExpiry) + { + // don't extend beyond renewal expiry and make sure it is marked in UTC + expiry = new DateTime(ptoken.RenewalExpiry.Ticks, DateTimeKind.Utc); + } + + ptoken.TokenExpiry = expiry; + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var secret = ObtainSecret(ptoken.TokenId, portalSettings.GUID, userInfo.Membership.LastPasswordChangeDate); + var jwt = CreateJwtToken(secret, portalSettings.PortalAlias.HTTPAlias, ptoken, userInfo.Roles); + var accessToken = jwt.RawData; + + // save hash values in DB so no one with access can create JWT header from existing data + ptoken.TokenHash = GetHashedStr(accessToken); + this.DataProvider.UpdateToken(ptoken); + + return new LoginResultData + { + UserId = userInfo.UserID, + DisplayName = userInfo.DisplayName, + AccessToken = accessToken, + RenewalToken = renewalToken, + }; + } + /// /// Checks for Authorization header and validates it is JWT scheme. If successful, it returns the token string. /// @@ -385,22 +407,22 @@ private string ValidateAuthHeader(AuthenticationHeaderValue authHdr) if (!string.Equals(authHdr.Scheme, AuthScheme, StringComparison.CurrentCultureIgnoreCase)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Authorization header scheme in the request is not equal to " + this.SchemeType); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Authorization header scheme in the request is not equal to " + this.SchemeType); + } + return null; } var authorization = authHdr.Parameter; if (string.IsNullOrEmpty(authorization)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Missing authorization header value in the request"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Missing authorization header value in the request"); + } + return null; } @@ -412,37 +434,37 @@ private string ValidateAuthorizationValue(string authorization) var parts = authorization.Split('.'); if (parts.Length < 3) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token must have [header:claims:signature] parts at least"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token must have [header:claims:signature] parts at least"); + } + return null; } var decoded = DecodeBase64(parts[0]); if (decoded.IndexOf("\"" + this.SchemeType + "\"", StringComparison.InvariantCultureIgnoreCase) < 0) { - if (Logger.IsTraceEnabled) - { - Logger.Trace($"This is not a {this.SchemeType} autentication scheme."); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace($"This is not a {this.SchemeType} autentication scheme."); + } + return null; } var header = JsonConvert.DeserializeObject(decoded); - if (!this.IsValidSchemeType(header)) - { - return null; - } - + if (!this.IsValidSchemeType(header)) + { + return null; + } + var jwt = GetAndValidateJwt(authorization, true); - if (jwt == null) - { - return null; - } - + if (jwt == null) + { + return null; + } + var userInfo = this.TryGetUser(jwt, true); return userInfo?.Username; } @@ -451,11 +473,11 @@ private bool IsValidSchemeType(JwtHeader header) { if (!this.SchemeType.Equals(header["typ"] as string, StringComparison.OrdinalIgnoreCase)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Unsupported authentication scheme type " + header.Typ); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Unsupported authentication scheme type " + header.Typ); + } + return false; } @@ -469,11 +491,11 @@ private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) var ptoken = this.DataProvider.GetTokenById(sessionId); if (ptoken == null) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Token not found in DB"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Token not found in DB"); + } + return null; } @@ -482,22 +504,22 @@ private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) var now = DateTime.UtcNow; if (now > ptoken.TokenExpiry || now > ptoken.RenewalExpiry) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("DB Token is expired"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("DB Token is expired"); + } + return null; } } if (ptoken.TokenHash != GetHashedStr(jwt.RawData)) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Mismatch data in received token"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mismatch data in received token"); + } + return null; } @@ -511,11 +533,11 @@ private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) var userInfo = UserController.GetUserById(portalSettings.PortalId, ptoken.UserId); if (userInfo == null) { - if (Logger.IsTraceEnabled) - { - Logger.Trace("Invalid user"); - } - + if (Logger.IsTraceEnabled) + { + Logger.Trace("Invalid user"); + } + return null; } @@ -533,27 +555,5 @@ private UserInfo TryGetUser(JwtSecurityToken jwt, bool checkExpiry) return userInfo; } - - 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)); - } - - private static string EncodeBase64(byte[] data) - { - return Convert.ToBase64String(data).TrimEnd('='); - } - - private static string GetHashedStr(string data) - { - return EncodeBase64(Hasher.ComputeHash(TextEncoder.GetBytes(data))); - } } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginData.cs b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginData.cs index 97113827d85..61bb48f3d24 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginData.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginData.cs @@ -14,6 +14,7 @@ public struct LoginData { [JsonProperty("u")] public string Username; + [JsonProperty("p")] public string Password; } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginResultData.cs b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginResultData.cs index 2ed3f4a2bd9..4a5a8353431 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginResultData.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/LoginResultData.cs @@ -11,16 +11,16 @@ public class LoginResultData { [JsonProperty("userId")] public int UserId { get; set; } - + [JsonProperty("displayName")] public string DisplayName { get; set; } - + [JsonProperty("accessToken")] public string AccessToken { get; set; } - + [JsonProperty("renewalToken")] public string RenewalToken { get; set; } - + [JsonIgnore] public string Error { get; set; } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/PersistedToken.cs b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/PersistedToken.cs index 7c98416a828..a2f14d5eec7 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/PersistedToken.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Components/Entity/PersistedToken.cs @@ -10,17 +10,17 @@ namespace Dnn.AuthServices.Jwt.Components.Entity public class PersistedToken { public string TokenId { get; set; } - + public int UserId { get; set; } - + public int RenewCount { get; set; } - + public DateTime TokenExpiry { get; set; } - + public DateTime RenewalExpiry { get; set; } - + public string TokenHash { get; set; } - + public string RenewalHash { get; set; } } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Data/DataService.cs b/DNN Platform/Dnn.AuthServices.Jwt/Data/DataService.cs index 7c5cf566357..fd919cd91e0 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Data/DataService.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Data/DataService.cs @@ -19,8 +19,8 @@ namespace Dnn.AuthServices.Jwt.Data /// public class DataService : ComponentBase, IDataService { - private readonly DataProvider _dataProvider = DataProvider.Instance(); - + private readonly DataProvider _dataProvider = DataProvider.Instance(); + public virtual PersistedToken GetTokenById(string tokenId) { try @@ -74,11 +74,11 @@ public virtual void DeleteExpiredTokens() { // don't worry aabout caching; these will already be invalidated by cache manager this._dataProvider.ExecuteNonQuery("JsonWebTokens_DeleteExpired"); - } - + } + private static string GetCacheKey(string tokenId) { return string.Join(":", "JsonWebTokens", tokenId); - } + } } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Data/IDataService.cs b/DNN Platform/Dnn.AuthServices.Jwt/Data/IDataService.cs index ccf3bad2a89..440ea428650 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Data/IDataService.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Data/IDataService.cs @@ -11,17 +11,17 @@ namespace Dnn.AuthServices.Jwt.Data public interface IDataService { PersistedToken GetTokenById(string tokenId); - + IList GetUserTokens(int userId); - + void AddToken(PersistedToken token); - + void UpdateToken(PersistedToken token); - + void DeleteToken(string tokenId); - + void DeleteUserTokens(int userId); - + void DeleteExpiredTokens(); } } diff --git a/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs b/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs index 86e7be10c57..89e508a9958 100644 --- a/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs +++ b/DNN Platform/Dnn.AuthServices.Jwt/Services/MobileController.cs @@ -14,10 +14,10 @@ namespace Dnn.AuthServices.Jwt.Services [DnnAuthorize(AuthTypes = "JWT")] public class MobileController : DnnApiController - { + { /// /// Clients that used JWT login should use this API call to logout and invalidate the tokens. - /// + /// /// [HttpGet] public IHttpActionResult Logout() @@ -31,7 +31,7 @@ public IHttpActionResult Logout() /// secure API endpoints afterwards. /// /// AllowAnonymous attribute must stay in this call even though the - /// DnnAuthorize attribute is present at a class level. + /// DnnAuthorize attribute is present at a class level.
/// [HttpPost] [AllowAnonymous] @@ -49,7 +49,7 @@ public IHttpActionResult Login(LoginData loginData) /// The access token is allowed to get renewed one time only.
/// AllowAnonymous attribute must stay in this call even though the /// DnnAuthorize attribute is present at a class level. - ///
+ /// /// [HttpPost] [AllowAnonymous] @@ -57,9 +57,9 @@ public IHttpActionResult ExtendToken(RenewalDto rtoken) { var result = JwtController.Instance.RenewToken(this.Request, rtoken.RenewalToken); return this.ReplyWith(result); - } - - // Test API Method 1 + } + + // Test API Method 1 [HttpGet] public IHttpActionResult TestGet() { @@ -78,7 +78,7 @@ public IHttpActionResult TestPost(TestPostData something) $" You said: ({something.Text})"; return this.Ok(new { reply }); } - + private IHttpActionResult ReplyWith(LoginResultData result) { if (result == null) @@ -93,13 +93,13 @@ private IHttpActionResult ReplyWith(LoginResultData result) } return this.Ok(result); - } + } [JsonObject] public class TestPostData { [JsonProperty("text")] public string Text; - } + } } } diff --git a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs index a2f23d0ce34..d7ab297d022 100644 --- a/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs +++ b/DNN Platform/DotNetNuke.Abstractions/Portals/IPortalSettings.cs @@ -7,13 +7,13 @@ namespace DotNetNuke.Abstractions.Portals public interface IPortalSettings { int PortalId { get; } - + bool ContentLocalizationEnabled { get; } - + bool EnableUrlLanguage { get; } - + bool SSLEnabled { get; } - + string SSLURL { get; } } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs index fd2afe204f7..8982cd75533 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLog.cs @@ -16,12 +16,12 @@ namespace DotNetNuke.Instrumentation public static class DnnLog { private const string ConfigFile = "DotNetNuke.log4net.config"; - private static bool _configured; - - // use a single static logger to avoid the performance impact of type reflection on every call for logging private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(DnnLog)); private static readonly object ConfigLock = new object(); + private static bool _configured; + + // use a single static logger to avoid the performance impact of type reflection on every call for logging private static StackFrame CallingFrame { @@ -39,10 +39,10 @@ private static StackFrame CallingFrame frameDepth++; reflectedType = stack[frameDepth].GetMethod().ReflectedType; } - + frame = stack[frameDepth]; } - + return frame; } } @@ -86,32 +86,6 @@ 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. /// @@ -123,8 +97,8 @@ public static void MethodExit() { Logger.TraceFormat("Method [{0}] Returned", CallingFrame.GetMethod().Name); } - } - + } + public static void Trace(string message) { EnsureConfig(); @@ -153,8 +127,8 @@ public static void Trace(IFormatProvider provider, string format, params object[ { Logger.TraceFormat(provider, format, args); } - } - + } + public static void Debug(object message) { EnsureConfig(); @@ -190,8 +164,8 @@ public static void Debug(IFormatProvider provider, string format, params object[ { Logger.DebugFormat(provider, format, args); } - } - + } + public static void Info(object message) { EnsureConfig(); @@ -224,8 +198,8 @@ public static void Info(string format, params object[] args) Logger.InfoFormat(format, args); } } - } - + } + public static void Warn(string message, Exception exception) { EnsureConfig(); @@ -252,7 +226,7 @@ public static void Warn(IFormatProvider provider, string format, params object[] Logger.WarnFormat(provider, format, args); } } - + public static void Warn(string format, params object[] args) { EnsureConfig(); @@ -267,8 +241,8 @@ public static void Warn(string format, params object[] args) Logger.WarnFormat(format, args); } } - } - + } + public static void Error(string message, Exception exception) { EnsureConfig(); @@ -320,8 +294,8 @@ public static void Error(string format, params object[] args) Logger.ErrorFormat(format, args); } } - } - + } + public static void Fatal(string message, Exception exception) { EnsureConfig(); @@ -363,6 +337,32 @@ public static void Fatal(string format, params object[] args) Logger.FatalFormat(format, args); } } - } + } + + 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; + } + } + } + } } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs b/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs index 8bf8fa91c3c..e502da43d0b 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/DnnLogger.cs @@ -19,17 +19,17 @@ namespace DotNetNuke.Instrumentation /// Please use LoggerSource.Instance as a more unit testable way to create loggers. /// public sealed class DnnLogger : LoggerWrapperImpl - { + { internal static Level LevelTrace; internal static Level LevelDebug; internal static Level LevelInfo; internal static Level LevelWarn; internal static Level LevelError; internal static Level LevelFatal; - + // 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"); + internal static Level LevelLogError = new Level(10002, "LogError"); private readonly Type _dnnExceptionType = BuildManager.GetType("DotNetNuke.Services.Exceptions.Exceptions", false); private readonly Type _stackBoundary = typeof(DnnLogger); @@ -41,9 +41,9 @@ private DnnLogger(ILogger logger) if (stack != null) { int frameDepth = 0; - Type methodType = stack[frameDepth].GetMethod().ReflectedType; + Type methodType = stack[frameDepth].GetMethod().ReflectedType; #pragma warning disable 612, 618 - while (methodType == this._dnnExceptionType || methodType == typeof(DnnLogger) || methodType == typeof(DnnLog) || methodType == typeof(Control)) + while (methodType == this._dnnExceptionType || methodType == typeof(DnnLogger) || methodType == typeof(DnnLog) || methodType == typeof(Control)) #pragma warning restore 612, 618 { frameDepth++; @@ -68,35 +68,8 @@ public static DnnLogger GetClassLogger(Type type) public static DnnLogger GetLogger(string name) { return new DnnLogger(LogManager.GetLogger(name).Logger); - } - - /// - /// Virtual method called when the configuration of the repository changes. - /// - /// the repository holding the levels. - /// - /// - /// Virtual method called when the configuration of the repository changes. - /// - /// - private static void ReloadLevels(ILoggerRepository repository) - { - LevelMap levelMap = repository.LevelMap; - - LevelTrace = levelMap.LookupWithDefault(Level.Trace); - LevelDebug = levelMap.LookupWithDefault(Level.Debug); - LevelInfo = levelMap.LookupWithDefault(Level.Info); - LevelWarn = levelMap.LookupWithDefault(Level.Warn); - LevelError = levelMap.LookupWithDefault(Level.Error); - 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); } - + /// /// Logs a message object with the DEBUG level. /// @@ -124,7 +97,7 @@ public void Debug(object message) { this.Logger.Log(this._stackBoundary, LevelDebug, message, null); } - + /// /// Logs a formatted message string with the DEBUG level. /// @@ -202,7 +175,7 @@ public void Info(object message) { this.Logger.Log(this._stackBoundary, LevelInfo, message, null); } - + /// /// Logs a formatted message string with the INFO level. /// @@ -229,7 +202,7 @@ public void InfoFormat(string format, params object[] args) { this.Logger.Log(this._stackBoundary, LevelInfo, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null); } - + /// /// Logs a formatted message string with the INFO level. /// @@ -252,7 +225,7 @@ public void InfoFormat(IFormatProvider provider, string format, params object[] { this.Logger.Log(this._stackBoundary, LevelInfo, new SystemStringFormat(provider, format, args), null); } - + /// /// Logs a message object with the WARN level. /// @@ -302,21 +275,6 @@ 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. /// @@ -563,8 +521,8 @@ public void FatalFormat(string format, params object[] args) public void FatalFormat(IFormatProvider provider, string format, params object[] args) { this.Logger.Log(this._stackBoundary, LevelFatal, new SystemStringFormat(provider, format, args), null); - } - + } + public void InstallLogError(object message) { this.Logger.Log(this._stackBoundary, LevelLogError, message, null); @@ -598,6 +556,48 @@ public void InstallLogInfoFormat(string format, params object[] args) public void InstallLogInfoFormat(IFormatProvider provider, string format, params object[] args) { this.Logger.Log(this._stackBoundary, LevelLogInfo, 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); + } + + /// + /// Virtual method called when the configuration of the repository changes. + /// + /// the repository holding the levels. + /// + /// + /// Virtual method called when the configuration of the repository changes. + /// + /// + private static void ReloadLevels(ILoggerRepository repository) + { + LevelMap levelMap = repository.LevelMap; + + LevelTrace = levelMap.LookupWithDefault(Level.Trace); + LevelDebug = levelMap.LookupWithDefault(Level.Debug); + LevelInfo = levelMap.LookupWithDefault(Level.Info); + LevelWarn = levelMap.LookupWithDefault(Level.Warn); + LevelError = levelMap.LookupWithDefault(Level.Error); + 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); + } } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/ILog.cs b/DNN Platform/DotNetNuke.Instrumentation/ILog.cs index eb6c4d0ff27..f47f4f282dc 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/ILog.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/ILog.cs @@ -9,63 +9,63 @@ namespace DotNetNuke.Instrumentation public interface ILog { bool IsDebugEnabled { get; } - + bool IsInfoEnabled { get; } - + bool IsTraceEnabled { get; } - + bool IsWarnEnabled { get; } - + bool IsErrorEnabled { get; } - + bool IsFatalEnabled { get; } void Debug(object message); - + void Debug(object message, Exception exception); - + void DebugFormat(string format, params object[] args); - + void DebugFormat(IFormatProvider provider, string format, params object[] args); void Info(object message); - + void Info(object message, Exception exception); - + void InfoFormat(string format, params object[] args); - + void InfoFormat(IFormatProvider provider, string format, params object[] args); void Trace(object message); - + void Trace(object message, Exception exception); - + void TraceFormat(string format, params object[] args); - + void TraceFormat(IFormatProvider provider, string format, params object[] args); void Warn(object message); - + void Warn(object message, Exception exception); - + void WarnFormat(string format, params object[] args); - + void WarnFormat(IFormatProvider provider, string format, params object[] args); void Error(object message); - + void Error(object message, Exception exception); - + void ErrorFormat(string format, params object[] args); - + void ErrorFormat(IFormatProvider provider, string format, params object[] args); void Fatal(object message); - + void Fatal(object message, Exception exception); - + void FatalFormat(string format, params object[] args); - + void FatalFormat(IFormatProvider provider, string format, params object[] args); } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/ILoggerSource.cs b/DNN Platform/DotNetNuke.Instrumentation/ILoggerSource.cs index 7246ef6c281..b63de8943f3 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/ILoggerSource.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/ILoggerSource.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Instrumentation public interface ILoggerSource { ILog GetLogger(Type type); - + ILog GetLogger(string name); } } diff --git a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs index e9f384f9b35..8e9c4f760fe 100644 --- a/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs +++ b/DNN Platform/DotNetNuke.Instrumentation/LoggerSourceImpl.cs @@ -32,21 +32,21 @@ public ILog GetLogger(string name) private class Logger : LoggerWrapperImpl, ILog { private const string ConfigFile = "DotNetNuke.log4net.config"; + private static readonly object ConfigLock = new object(); 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 static readonly object ConfigLock = new object(); - internal Logger(ILogger logger, Type type) + internal Logger(ILogger logger, Type type) : base(logger) { this._stackBoundary = type ?? typeof(Logger); @@ -54,114 +54,35 @@ 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); } - } + public bool IsDebugEnabled + { + get { return this.Logger.IsEnabledFor(_levelDebug); } + } - private static void EnsureConfig() + public bool IsInfoEnabled { - 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); - } + get { return this.Logger.IsEnabledFor(_levelInfo); } + } - if (File.Exists(configPath)) - { - AddGlobalContext(); - XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath)); - } - - _configured = true; - } - } - } + public bool IsTraceEnabled + { + get { return this.Logger.IsEnabledFor(_levelTrace); } } - private static void ReloadLevels(ILoggerRepository repository) + public bool IsWarnEnabled { - LevelMap levelMap = repository.LevelMap; + get { return this.Logger.IsEnabledFor(_levelWarn); } + } - _levelTrace = levelMap.LookupWithDefault(Level.Trace); - _levelDebug = levelMap.LookupWithDefault(Level.Debug); - _levelInfo = levelMap.LookupWithDefault(Level.Info); - _levelWarn = levelMap.LookupWithDefault(Level.Warn); - _levelError = levelMap.LookupWithDefault(Level.Error); - _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); + public bool IsErrorEnabled + { + get { return this.Logger.IsEnabledFor(_levelError); } } - private static void AddGlobalContext() + public bool IsFatalEnabled { - try - { - GlobalContext.Properties["appdomain"] = AppDomain.CurrentDomain.Id.ToString("D"); - - // bool isFullTrust = false; - // try - // { - // CodeAccessPermission securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted); - // securityTest.Demand(); - // isFullTrust = true; - // } - // catch - // { - // //code access security error - // isFullTrust = false; - // } - // if (isFullTrust) - // { - // GlobalContext.Properties["processid"] = Process.GetCurrentProcess().Id.ToString("D"); - // } - } - - // ReSharper disable EmptyGeneralCatchClause - catch - - // ReSharper restore EmptyGeneralCatchClause - { - // do nothing but just make sure no exception here. - } + get { return this.Logger.IsEnabledFor(_levelFatal); } } - - public bool IsWarnEnabled - { - get { return this.Logger.IsEnabledFor(_levelWarn); } - } - - public bool IsErrorEnabled - { - get { return this.Logger.IsEnabledFor(_levelError); } - } - - public bool IsFatalEnabled - { - get { return this.Logger.IsEnabledFor(_levelFatal); } - } public void Debug(object message) { @@ -282,6 +203,85 @@ public void FatalFormat(IFormatProvider provider, string format, params object[] { this.Logger.Log(this._stackBoundary, _levelFatal, new SystemStringFormat(provider, format, args), null); } + + 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)) + { + AddGlobalContext(); + XmlConfigurator.ConfigureAndWatch(new FileInfo(configPath)); + } + + _configured = true; + } + } + } + } + + private static void ReloadLevels(ILoggerRepository repository) + { + LevelMap levelMap = repository.LevelMap; + + _levelTrace = levelMap.LookupWithDefault(Level.Trace); + _levelDebug = levelMap.LookupWithDefault(Level.Debug); + _levelInfo = levelMap.LookupWithDefault(Level.Info); + _levelWarn = levelMap.LookupWithDefault(Level.Warn); + _levelError = levelMap.LookupWithDefault(Level.Error); + _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); + } + + private static void AddGlobalContext() + { + try + { + GlobalContext.Properties["appdomain"] = AppDomain.CurrentDomain.Id.ToString("D"); + + // bool isFullTrust = false; + // try + // { + // CodeAccessPermission securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted); + // securityTest.Demand(); + // isFullTrust = true; + // } + // catch + // { + // //code access security error + // isFullTrust = false; + // } + // if (isFullTrust) + // { + // GlobalContext.Properties["processid"] = Process.GetCurrentProcess().Id.ToString("D"); + // } + } + + // ReSharper disable EmptyGeneralCatchClause + catch + + // ReSharper restore EmptyGeneralCatchClause + { + // do nothing but just make sure no exception here. + } + } } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs index 5e320bec516..6a0f75211c6 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceManager.cs @@ -32,8 +32,8 @@ public class ClientResourceManager private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ClientResourceManager)); private static Dictionary _fileExistsCache = new Dictionary(); - private static ReaderWriterLockSlim _lockFileExistsCache = new ReaderWriterLockSlim(); - + private static ReaderWriterLockSlim _lockFileExistsCache = new ReaderWriterLockSlim(); + /// /// Adds the neccessary configuration to website root web.config to use the Client Depenedecny componenet. /// @@ -71,7 +71,7 @@ public static void AddConfiguration() xmlDoc.DocumentElement.SelectSingleNode("system.webServer/modules").AppendChild(xmlFrag); } } - + // Handler Config var systemWebServerHandlersConfig = xmlDoc.DocumentElement.SelectSingleNode("system.webServer/handlers"); if (systemWebServerHandlersConfig != null) @@ -97,7 +97,7 @@ public static void AddConfiguration() xmlDoc.DocumentElement.SelectSingleNode("system.web/httpModules").AppendChild(xmlFrag); } } - + // HttpHandler Config var systemWebServerHttpHandlersConfig = xmlDoc.DocumentElement.SelectSingleNode("system.web/httpHandlers"); if (systemWebServerHttpHandlersConfig != null) @@ -164,51 +164,6 @@ 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) { @@ -455,6 +410,51 @@ public static void EnableAsyncPostBackHandler() { HttpContext.Current.Items.Add("AsyncPostBackHandlerEnabled", true); } - } + } + + 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; + } } } diff --git a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs index 23a4d344f1d..e4584c7d475 100644 --- a/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Client/ClientResourceSettings.cs @@ -76,6 +76,20 @@ private enum UpgradeStatus Unknown, } + private UpgradeStatus Status + { + get + { + if (!this._statusChecked) + { + this._status = this.GetStatusByReflection(); + this._statusChecked = true; + } + + return this._status; + } + } + /// /// /// @@ -155,34 +169,6 @@ public bool IsOverridingDefaultSettingsEnabled() return null; } - private bool? IsBooleanSettingEnabled(string settingKey) - { - if (this.Status != UpgradeStatus.None) - { - return false; - } - - var portalEnabled = GetBooleanSetting(PortalSettingsDictionaryKey, settingKey); - var overrideDefaultSettings = GetBooleanSetting(PortalSettingsDictionaryKey, OverrideDefaultSettingsKey); - - // if portal version is set - // and the portal "override default settings" flag is set and set to true - if (portalEnabled.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value) - { - return portalEnabled.Value; - } - - // otherwise return the host setting - var hostEnabled = GetBooleanSetting(HostSettingsDictionaryKey, settingKey); - if (hostEnabled.HasValue) - { - return hostEnabled.Value; - } - - // otherwise tell the calling method that nothing is set - return null; - } - private static string GetSetting(string dictionaryKey, string settingKey) { bool isHttpContext = HttpContext.Current != null && HttpContext.Current.Items.Contains(dictionaryKey); @@ -274,18 +260,32 @@ private static string GetHostSettingThroughReflection(string settingKey) return null; } - private UpgradeStatus Status + private bool? IsBooleanSettingEnabled(string settingKey) { - get + if (this.Status != UpgradeStatus.None) { - if (!this._statusChecked) - { - this._status = this.GetStatusByReflection(); - this._statusChecked = true; - } + return false; + } - return this._status; + var portalEnabled = GetBooleanSetting(PortalSettingsDictionaryKey, settingKey); + var overrideDefaultSettings = GetBooleanSetting(PortalSettingsDictionaryKey, OverrideDefaultSettingsKey); + + // if portal version is set + // and the portal "override default settings" flag is set and set to true + if (portalEnabled.HasValue && overrideDefaultSettings.HasValue && overrideDefaultSettings.Value) + { + return portalEnabled.Value; + } + + // otherwise return the host setting + var hostEnabled = GetBooleanSetting(HostSettingsDictionaryKey, settingKey); + if (hostEnabled.HasValue) + { + return hostEnabled.Value; } + + // otherwise tell the calling method that nothing is set + return null; } private UpgradeStatus GetStatusByReflection() diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs index 8747a833d4e..03048854a31 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceExclude.cs @@ -36,7 +36,7 @@ protected override void OnPreRender(EventArgs e) } } } - + if (ctlToRemove != null) { loader.Controls.Remove(ctlToRemove); diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs index d2036591ead..7f607b96937 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourceInclude.cs @@ -10,6 +10,5 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// Represents an included client resource. /// public class ClientResourceInclude : ClientDependencyInclude - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs index 93686ebd08a..eb76e0f3b49 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePath.cs @@ -10,6 +10,5 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// Defines the path to a client resource. /// public class ClientResourcePath : ClientDependencyPath - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs index 73ac80e7d1d..0032f0b2aa4 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/ClientResourcePathCollection.cs @@ -10,6 +10,5 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// Represents a collection of client resource paths. /// public class ClientResourcePathCollection : ClientDependencyPathCollection - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs index 78aecdeb8ec..964663682a4 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnHtmlInclude.cs @@ -10,6 +10,5 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// Allows for registration of CSS and JavaScript resources. /// public class DnnHtmlInclude : HtmlInclude - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs index a83223b20a6..2b9d9764f4e 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsInclude.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Web.Client.ClientResourceManagement /// Registers a JavaScript resource. /// public class DnnJsInclude : JsInclude - { - /// + { + /// /// Initializes a new instance of the class. /// Sets up default settings for the control. /// diff --git a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs index 94866edcad3..82988961d00 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Controls/DnnJsIncludeFallback.cs @@ -19,9 +19,9 @@ public DnnJsIncludeFallback(string objectName, string fileName) } public string ObjectName { get; set; } - + public string FileName { get; set; } - + public override void RenderControl(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript"); diff --git a/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs b/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs index 68ad8446e78..4613f0012ab 100644 --- a/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs +++ b/DNN Platform/DotNetNuke.Web.Client/FileOrder.cs @@ -24,7 +24,7 @@ public enum Js /// // ReSharper disable InconsistentNaming jQuery = 5, - + // ReSharper restore InconsistentNaming /// @@ -32,17 +32,17 @@ public enum Js /// // ReSharper disable InconsistentNaming jQueryMigrate = 6, - + // ReSharper restore InconsistentNaming /// /// jQuery UI (CDN or local file) has the priority of 10 /// // ReSharper disable InconsistentNaming - jQueryUI = 10, - - // ReSharper restore InconsistentNaming - + jQueryUI = 10, + + // ReSharper restore InconsistentNaming + /// /// /js/dnn.xml.js has the priority of 15 /// diff --git a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnBodyRenderProvider.cs b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnBodyRenderProvider.cs index dfa6766d761..9a4c60e37f2 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnBodyRenderProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnBodyRenderProvider.cs @@ -25,7 +25,7 @@ public class DnnBodyProvider : DnnFileRegistrationProvider /// The name of the provider. /// public const string DefaultName = "DnnBodyProvider"; - + /// /// The name of the placeholder in which the controls will be rendered. /// @@ -43,21 +43,21 @@ public class DnnBodyProvider : DnnFileRegistrationProvider public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { // Assign the provider a default name if it doesn't have one - if (string.IsNullOrEmpty(name)) - { - name = DefaultName; - } - + if (string.IsNullOrEmpty(name)) + { + name = DefaultName; + } + base.Initialize(name, config); } protected override string RenderJsDependencies(IEnumerable jsDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!jsDependencies.Any()) - { - return string.Empty; - } - + if (!jsDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -86,11 +86,11 @@ protected override string RenderSingleJsFile(string js, IDictionary cssDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!cssDependencies.Any()) - { - return string.Empty; - } - + if (!cssDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -134,14 +134,14 @@ protected override void RegisterDependencies(HttpContextBase http, string js, st { throw new InvalidOperationException("The current HttpHandler in a WebFormsFileRegistrationProvider must be of type Page"); } - + var page = (Page)http.CurrentHandler; - if (page.Header == null) - { - throw new NullReferenceException("DnnBodyProvider requires a runat='server' tag in the page's header tag"); - } - + if (page.Header == null) + { + throw new NullReferenceException("DnnBodyProvider requires a runat='server' tag in the page's header tag"); + } + var jsScriptBlock = new LiteralControl(js.Replace("&", "&")); var cssStyleBlock = new LiteralControl(css.Replace("&", "&")); diff --git a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnFormBottomRenderProvider.cs b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnFormBottomRenderProvider.cs index 909f0a2b477..6ed514c5cac 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnFormBottomRenderProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnFormBottomRenderProvider.cs @@ -29,25 +29,25 @@ public class DnnFormBottomProvider : DnnFileRegistrationProvider /// The name of the placeholder in which the controls will be rendered. /// public const string DnnFormBottomPlaceHolderName = "ClientResourcesFormBottom"; - + public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { // Assign the provider a default name if it doesn't have one - if (string.IsNullOrEmpty(name)) - { - name = DefaultName; - } - + if (string.IsNullOrEmpty(name)) + { + name = DefaultName; + } + base.Initialize(name, config); } protected override string RenderJsDependencies(IEnumerable jsDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!jsDependencies.Any()) - { - return string.Empty; - } - + if (!jsDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -76,11 +76,11 @@ protected override string RenderSingleJsFile(string js, IDictionary cssDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!cssDependencies.Any()) - { - return string.Empty; - } - + if (!cssDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -124,14 +124,14 @@ protected override void RegisterDependencies(HttpContextBase http, string js, st { throw new InvalidOperationException("The current HttpHandler in a WebFormsFileRegistrationProvider must be of type Page"); } - + var page = (Page)http.CurrentHandler; - if (page.Header == null) - { - throw new NullReferenceException("DnnFormBottomProvider requires a runat='server' tag in the page's header tag"); - } - + if (page.Header == null) + { + throw new NullReferenceException("DnnFormBottomProvider requires a runat='server' tag in the page's header tag"); + } + var jsScriptBlock = new LiteralControl(js.Replace("&", "&")); var cssStyleBlock = new LiteralControl(css.Replace("&", "&")); page.FindControl(DnnFormBottomPlaceHolderName).Controls.Add(jsScriptBlock); diff --git a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnPageHeaderProvider.cs b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnPageHeaderProvider.cs index c7d6e54f400..f6e597de9c6 100644 --- a/DNN Platform/DotNetNuke.Web.Client/Providers/DnnPageHeaderProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Client/Providers/DnnPageHeaderProvider.cs @@ -29,26 +29,27 @@ public class DnnPageHeaderProvider : DnnFileRegistrationProvider /// The name of the placeholder in which the controls will be rendered. /// public const string CssPlaceHolderName = "ClientDependencyHeadCss"; + public const string JsPlaceHolderName = "ClientDependencyHeadJs"; - + public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { // Assign the provider a default name if it doesn't have one - if (string.IsNullOrEmpty(name)) - { - name = DefaultName; - } - + if (string.IsNullOrEmpty(name)) + { + name = DefaultName; + } + base.Initialize(name, config); } protected override string RenderJsDependencies(IEnumerable jsDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!jsDependencies.Any()) - { - return string.Empty; - } - + if (!jsDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -77,11 +78,11 @@ protected override string RenderSingleJsFile(string js, IDictionary cssDependencies, HttpContextBase http, IDictionary htmlAttributes) { - if (!cssDependencies.Any()) - { - return string.Empty; - } - + if (!cssDependencies.Any()) + { + return string.Empty; + } + var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !this.EnableCompositeFiles) @@ -125,14 +126,14 @@ protected override void RegisterDependencies(HttpContextBase http, string js, st { throw new InvalidOperationException("The current HttpHandler in a WebFormsFileRegistrationProvider must be of type Page"); } - + var page = (Page)http.CurrentHandler; - if (page.Header == null) - { - throw new NullReferenceException("DnnPageHeaderProvider requires a runat='server' tag in the page's header tag"); - } - + if (page.Header == null) + { + throw new NullReferenceException("DnnPageHeaderProvider requires a runat='server' tag in the page's header tag"); + } + var jsScriptBlock = new LiteralControl(js.Replace("&", "&")); var cssStyleBlock = new LiteralControl(css.Replace("&", "&")); page.FindControl(JsPlaceHolderName).Controls.Add(jsScriptBlock); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/Core Wrappers/DnnRadTab.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/Core Wrappers/DnnRadTab.cs index eb71f6ec66d..1a367e47ebf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/Core Wrappers/DnnRadTab.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/Core Wrappers/DnnRadTab.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRadTab : RadTab - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxLoadingPanel.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxLoadingPanel.cs index 7d3fc45aecb..a9ecec869f4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxLoadingPanel.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxLoadingPanel.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnAjaxLoadingPanel : RadAjaxLoadingPanel - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxPanel.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxPanel.cs index 32fbf43fc44..9d3a5ef6f82 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxPanel.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxPanel.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnAjaxPanel : RadAjaxPanel - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAsyncUpload.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAsyncUpload.cs index 9b9830e73f1..7ed4beff03c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAsyncUpload.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAsyncUpload.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnAsyncUpload : RadAsyncUpload - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnBinaryImage.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnBinaryImage.cs index 5eb5a7103a6..bdf2c622e75 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnBinaryImage.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnBinaryImage.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnBinaryImage : RadBinaryImage - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendar.cs index 4698cc55267..2c6076e270e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendar.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnCalendar : RadCalendar - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendarDay.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendarDay.cs index 1eca87a63d3..55a1b6bd6c1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendarDay.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCalendarDay.cs @@ -11,7 +11,7 @@ public DnnCalendarDay() { } - public DnnCalendarDay(RadCalendar calendar) + public DnnCalendarDay(RadCalendar calendar) : base(calendar) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCaptcha.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCaptcha.cs index b11f8e73df5..cb6dd8933b7 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCaptcha.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCaptcha.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnCaptcha : RadCaptcha - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChart.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChart.cs index 96fca6ef78f..8fa7ee86331 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChart.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChart.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnChart : RadChart - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartAxisItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartAxisItem.cs index 5b5c67db9aa..e8b4226a125 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartAxisItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartAxisItem.cs @@ -13,27 +13,27 @@ public DnnChartAxisItem() { } - public DnnChartAxisItem(string labelText) + public DnnChartAxisItem(string labelText) : base(labelText) { } - public DnnChartAxisItem(string labelText, Color color) + public DnnChartAxisItem(string labelText, Color color) : base(labelText, color) { } - public DnnChartAxisItem(string labelText, Color color, bool visible) + public DnnChartAxisItem(string labelText, Color color, bool visible) : base(labelText, color, visible) { } - public DnnChartAxisItem(string labelText, Color color, bool visible, IContainer container) + public DnnChartAxisItem(string labelText, Color color, bool visible, IContainer container) : base(labelText, color, visible, container) { } - public DnnChartAxisItem(IContainer container) + public DnnChartAxisItem(IContainer container) : base(container) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeries.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeries.cs index ec9749f145d..d0b72d46755 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeries.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeries.cs @@ -12,17 +12,17 @@ public DnnChartSeries() { } - public DnnChartSeries(string name) + public DnnChartSeries(string name) : base(name) { } - public DnnChartSeries(string name, ChartSeriesType type) + public DnnChartSeries(string name, ChartSeriesType type) : base(name, type) { } - public DnnChartSeries(string name, ChartSeriesType type, ChartSeriesCollection parent) + public DnnChartSeries(string name, ChartSeriesType type, ChartSeriesCollection parent) : base(name, type, parent) { } @@ -38,7 +38,7 @@ public DnnChartSeries(string seriesName, ChartSeriesType chartSeriesType, ChartS { } - public DnnChartSeries(ChartSeriesCollection parent) + public DnnChartSeries(ChartSeriesCollection parent) : base(parent) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeriesItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeriesItem.cs index b3419219663..e5e8d72337d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeriesItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnChartSeriesItem.cs @@ -14,52 +14,52 @@ public DnnChartSeriesItem() { } - public DnnChartSeriesItem(bool isEmpty) + public DnnChartSeriesItem(bool isEmpty) : base(isEmpty) { } - public DnnChartSeriesItem(double value) + public DnnChartSeriesItem(double value) : base(value) { } - public DnnChartSeriesItem(double x, double y) + public DnnChartSeriesItem(double x, double y) : base(x, y) { } - public DnnChartSeriesItem(double x, double y, double x2, double y2) + public DnnChartSeriesItem(double x, double y, double x2, double y2) : base(x, y, x2, y2) { } - public DnnChartSeriesItem(double x, double y, double x2, double y2, double y3, double y4) + public DnnChartSeriesItem(double x, double y, double x2, double y2, double y3, double y4) : base(x, y, x2, y2, y3, y4) { } - public DnnChartSeriesItem(double x, double y, StyleSeriesItem style) + public DnnChartSeriesItem(double x, double y, StyleSeriesItem style) : base(x, y, style) { } - public DnnChartSeriesItem(double value, string labelText) + public DnnChartSeriesItem(double value, string labelText) : base(value, labelText) { } - public DnnChartSeriesItem(double value, string label, Color color) + public DnnChartSeriesItem(double value, string label, Color color) : base(value, label, color) { } - public DnnChartSeriesItem(double value, string label, Color color, bool exploded) + public DnnChartSeriesItem(double value, string label, Color color, bool exploded) : base(value, label, color, exploded) { } - public DnnChartSeriesItem(ChartSeries parent) + public DnnChartSeriesItem(ChartSeries parent) : base(parent) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCodeBlock.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCodeBlock.cs index ce3b888b685..55bb483c474 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCodeBlock.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnCodeBlock.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnCodeBlock : RadCodeBlock - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPicker.cs index f87035fbe80..83907c22ca1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPicker.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnColorPicker : RadColorPicker - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPickerItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPickerItem.cs index d8cb78f27e4..f0430b1d841 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPickerItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnColorPickerItem.cs @@ -13,12 +13,12 @@ public DnnColorPickerItem() { } - public DnnColorPickerItem(Color value) + public DnnColorPickerItem(Color value) : base(value) { } - public DnnColorPickerItem(Color value, string title) + public DnnColorPickerItem(Color value, string title) : base(value, title) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs index 5e472d0b53d..e2870375b53 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBox.cs @@ -20,30 +20,6 @@ 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); - this.EnableEmbeddedBaseStylesheet = false; - this.OnClientLoad = "$.dnnComboBoxLoaded"; - this.OnClientFocus = "$.dnnComboBoxHack"; - this.OnClientDropDownOpened = "$.dnnComboBoxScroll"; - this.OnClientItemsRequested = "$.dnnComboBoxItemRequested"; - this.MaxHeight = 240; - this.ZIndex = 100010; - this.Localization.ItemsCheckedString = Utilities.GetLocalizedString("ItemsCheckedString"); - this.Localization.CheckAllString = Utilities.GetLocalizedString("CheckAllString"); - this.Localization.AllItemsCheckedString = Utilities.GetLocalizedString("AllItemsCheckedString"); - this.Localization.NoMatches = Utilities.GetLocalizedString("NoMatches"); - this.Localization.ShowMoreFormatString = Utilities.GetLocalizedString("ShowMoreFormatString"); - } - - protected override void OnPreRender(EventArgs e) - { - Utilities.ApplySkin(this); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - base.OnPreRender(e); - } public void DataBind(string initialValue) { @@ -74,5 +50,29 @@ public void Select(string initial, bool findByText) } } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + this.EnableEmbeddedBaseStylesheet = false; + this.OnClientLoad = "$.dnnComboBoxLoaded"; + this.OnClientFocus = "$.dnnComboBoxHack"; + this.OnClientDropDownOpened = "$.dnnComboBoxScroll"; + this.OnClientItemsRequested = "$.dnnComboBoxItemRequested"; + this.MaxHeight = 240; + this.ZIndex = 100010; + this.Localization.ItemsCheckedString = Utilities.GetLocalizedString("ItemsCheckedString"); + this.Localization.CheckAllString = Utilities.GetLocalizedString("CheckAllString"); + this.Localization.AllItemsCheckedString = Utilities.GetLocalizedString("AllItemsCheckedString"); + this.Localization.NoMatches = Utilities.GetLocalizedString("NoMatches"); + this.Localization.ShowMoreFormatString = Utilities.GetLocalizedString("ShowMoreFormatString"); + } + + protected override void OnPreRender(EventArgs e) + { + Utilities.ApplySkin(this); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + base.OnPreRender(e); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBoxItem.cs index 4676115bcd9..9f8eae0309f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnComboBoxItem.cs @@ -12,17 +12,17 @@ public DnnComboBoxItem() { } - public DnnComboBoxItem(string text) + public DnnComboBoxItem(string text) : base(text) { } - public DnnComboBoxItem(string text, string value) + public DnnComboBoxItem(string text, string value) : base(text, value) { } - public string ResourceKey + public string ResourceKey { get { @@ -33,7 +33,7 @@ public string ResourceKey return string.Empty; } - + set { this.ViewState["ResourceKey"] = value; diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenu.cs index f06d86a86d0..cef8af574f6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenu.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnContextMenu : RadContextMenu - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuElementTarget.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuElementTarget.cs index f767c73af6c..b9290052686 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuElementTarget.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuElementTarget.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnContextMenuElementTarget : ContextMenuElementTarget - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuTagNameTarget.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuTagNameTarget.cs index f1225ced670..ae14ec87da3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuTagNameTarget.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnContextMenuTagNameTarget.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnContextMenuTagNameTarget : ContextMenuTagNameTarget - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPager.cs index f55a83e0c44..1a55078d72f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPager.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPager : RadDataPager - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerButtonField.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerButtonField.cs index 53d3dccf3a4..70e457e2926 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerButtonField.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerButtonField.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPagerButtonField : RadDataPagerButtonField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerGoToPageField.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerGoToPageField.cs index 1c0960a3a2b..001d9908c24 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerGoToPageField.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerGoToPageField.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPagerGoToPageField : RadDataPagerGoToPageField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerPageSizeField.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerPageSizeField.cs index 60c0b24bdd0..0c4beaba500 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerPageSizeField.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerPageSizeField.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPagerPageSizeField : RadDataPagerPageSizeField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerSliderField.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerSliderField.cs index df2b923087a..a6826412733 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerSliderField.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerSliderField.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPagerSliderField : RadDataPagerSliderField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerTemplatePageField.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerTemplatePageField.cs index b067aff1d3d..d6c03348693 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerTemplatePageField.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDataPagerTemplatePageField.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDataPagerTemplatePageField : RadDataPagerTemplatePageField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDateInput.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDateInput.cs index 074ad76f3f0..89e61df6fa0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDateInput.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDateInput.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDateInput : RadDateInput - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDock.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDock.cs index 063b18e6793..445e26fd501 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDock.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDock.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDock : RadDock - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCloseCommand.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCloseCommand.cs index 1383ea1779f..ec5d21acda3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCloseCommand.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCloseCommand.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDockCloseCommand : DockCloseCommand - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCommand.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCommand.cs index a962bf965d8..84b6afbc5ca 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCommand.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockCommand.cs @@ -11,7 +11,7 @@ public DnnDockCommand() { } - public DnnDockCommand(string clientTypeName, string cssClass, string name, string text, bool autoPostBack) + public DnnDockCommand(string clientTypeName, string cssClass, string name, string text, bool autoPostBack) : base(clientTypeName, cssClass, name, text, autoPostBack) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockLayout.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockLayout.cs index f0d2fc50e6e..7c545a291b1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockLayout.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockLayout.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDockLayout : RadDockLayout - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockZone.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockZone.cs index 3d803c85e0d..a2449f8165d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockZone.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnDockZone.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnDockZone : RadDockZone - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnEditor.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnEditor.cs index 3bf151e28f4..b81ef1cf5ba 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnEditor.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnEditor.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnEditor : RadEditor - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFileExplorer.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFileExplorer.cs index e67b3ab6a1c..6d74f5e000f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFileExplorer.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFileExplorer.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnFileExplorer : RadFileExplorer - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFilter.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFilter.cs index e987ee62a92..2be9c7400ba 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFilter.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFilter.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnFilter : RadFilter - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs index 0cb9c682e17..d5ed1502122 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormComboBoxItem.cs @@ -45,10 +45,10 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume // Reset SelectedValue // comboBox.Select(selectedValue); var selectedItem = comboBox.FindItemByValue(selectedValue); - if (selectedItem != null) - { - selectedItem.Selected = true; - } + if (selectedItem != null) + { + selectedItem.Selected = true; + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormDecorator.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormDecorator.cs index 666707bf321..ef30260742c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormDecorator.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormDecorator.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnFormDecorator : RadFormDecorator - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs index c1986f46e07..bbb14b8ac50 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormEnumItem.cs @@ -19,16 +19,16 @@ public string EnumType { return this._enumType; } - + set { this._enumType = value; - + // ReSharper disable AssignNullToNotNullAttribute - this.ListSource = (from object enumValue in Enum.GetValues(Type.GetType(this._enumType)) + 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 43b346de621..abe1e465968 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormNumericTextBoxItem.cs @@ -37,7 +37,7 @@ protected override WebControl CreateControlInternal(Control container) // _textBox = new DnnNumericTextBox {EmptyMessage = LocalizeString(ResourceKey + ".Hint"), ID = ID + "_TextBox", Width = TextBoxWidth }; this._textBox = new TextBox(); this._textBox.CssClass = "DnnNumericTextBox"; - + // _textBox.Style.Add("float", "none"); // _textBox.EmptyMessageStyle.CssClass += "dnnformHint"; // _textBox.Type = Type; diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs index 74b67e78fe3..2e9c5582bda 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormSkinsItem.cs @@ -17,7 +17,7 @@ public class DnnFormSkinsItem : DnnFormItemBase // private DropDownList _containerCombo; private DnnComboBox _containerCombo; private object _containerValue; - + // private DropDownList _skinCombo; private DnnComboBox _skinCombo; private object _skinValue; @@ -72,6 +72,17 @@ protected override void DataBindInternal() this.Value = new Pair { First = this._skinValue, Second = this._containerValue }; } + protected override void LoadControlState(object state) + { + base.LoadControlState(state); + var pair = this.Value as Pair; + if (pair != null) + { + this._skinValue = pair.First; + this._containerValue = pair.Second; + } + } + private void ContainerIndexChanged(object sender, EventArgs e) { this.UpdateDataSource(this._containerValue, this._containerCombo.SelectedValue, this.ContainerDataField); @@ -97,19 +108,8 @@ private Dictionary GetSkins(string skinRoot) skins.Add(skin.Key, skin.Value); } } - - return skins; - } - protected override void LoadControlState(object state) - { - base.LoadControlState(state); - var pair = this.Value as Pair; - if (pair != null) - { - this._skinValue = pair.First; - this._containerValue = pair.Second; - } + return skins; } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs index 5411f9222b5..a656e1f869b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnFormToggleButtonItem.cs @@ -10,21 +10,21 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnFormToggleButtonItem : DnnFormItemBase - { - // private DnnRadButton _checkBox; + { + // private DnnRadButton _checkBox; private CheckBox _checkBox; public DnnFormToggleButtonItem() { this.Mode = CheckBoxMode.TrueFalse; } - + public enum CheckBoxMode { TrueFalse = 0, YN = 1, YesNo = 2, - } + } public CheckBoxMode Mode { get; set; } @@ -40,7 +40,7 @@ protected override WebControl CreateControlInternal(Control container) if (!this._checkBox.Page.IsPostBack) { } - + switch (this.Mode) { case CheckBoxMode.YN: @@ -50,7 +50,7 @@ protected override WebControl CreateControlInternal(Control container) { this._checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); } - + break; default: this._checkBox.Checked = Convert.ToBoolean(this.Value); @@ -82,7 +82,7 @@ private void CheckedChanged(object sender, EventArgs e) newValue = this._checkBox.Checked ? "true" : "false"; break; } - + this.UpdateDataSource(this.Value, newValue, this.DataField); } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs index 5f10635351a..add61de6228 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGrid.cs @@ -11,11 +11,11 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGrid : RadGrid - { + { public int ScreenRowNumber { get; set; } - public int RowHeight { get; set; } - + public int RowHeight { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -35,22 +35,22 @@ protected override void OnInit(EventArgs e) private void DnnGrid_PreRender(object sender, EventArgs e) { var items = this.MasterTableView.Items; - if (this.ScreenRowNumber == 0) - { - this.ScreenRowNumber = 15; - } - + if (this.ScreenRowNumber == 0) + { + this.ScreenRowNumber = 15; + } + if (items.Count > this.ScreenRowNumber) { // need scroll this.ClientSettings.Scrolling.AllowScroll = true; this.ClientSettings.Scrolling.UseStaticHeaders = true; - if (this.RowHeight == 0) - { - this.RowHeight = 25; - } - + if (this.RowHeight == 0) + { + this.RowHeight = 25; + } + this.ClientSettings.Scrolling.ScrollHeight = this.RowHeight * this.ScreenRowNumber; } else diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs index 057142e930a..7f31c0475e0 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridAttachmentColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridGroupSplitterColumn : GridGroupSplitterColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridGroupSplitterColumn dnnGridColumn = new DnnGridGroupSplitterColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs index bc630b2c86e..9dcf81572ba 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBinaryImageColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridBinaryImageColumn : GridBinaryImageColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridBinaryImageColumn dnnGridColumn = new DnnGridBinaryImageColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs index b4c608a18a3..69d7de4aee8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridBoundColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridBoundColumn : GridBoundColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridBoundColumn dnnGridColumn = new DnnGridBoundColumn(); @@ -46,6 +46,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in button.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs index 6afbcd27d7f..93169d67d32 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridButtonColumn.cs @@ -10,14 +10,14 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridButtonColumn : GridButtonColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } + } /// ----------------------------------------------------------------------------- /// @@ -42,7 +42,25 @@ public string LocalResourceFile /// A String. /// ----------------------------------------------------------------------------- public string IconStyle { get; set; } - + + public override string ImageUrl + { + get + { + if (string.IsNullOrEmpty(base.ImageUrl)) + { + base.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + + return base.ImageUrl; + } + + set + { + base.ImageUrl = value; + } + } + public override GridColumn Clone() { DnnGridButtonColumn dnnGridColumn = new DnnGridButtonColumn(); @@ -61,23 +79,5 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } } - - public override string ImageUrl - { - get - { - if (string.IsNullOrEmpty(base.ImageUrl)) - { - base.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); - } - - return base.ImageUrl; - } - - set - { - base.ImageUrl = value; - } - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs index 9d39b4ca502..81353f03d21 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCalculatedColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridCalculatedColumn : GridCalculatedColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridCalculatedColumn dnnGridColumn = new DnnGridCalculatedColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs index f125bdf09b2..6429d70fdbc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridCheckBoxColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridCheckBoxColumn : GridCheckBoxColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridCheckBoxColumn dnnGridColumn = new DnnGridCheckBoxColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs index 69b4bcedaf4..53364b4ca8e 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridClientSelectColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridClientSelectColumn : GridClientSelectColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { var dnnGridColumn = new DnnGridClientSelectColumn(); @@ -39,6 +39,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs index c6ab0371be5..f18783aab64 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridColumn.cs @@ -10,29 +10,29 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridColumn : GridColumn - { + { private string _HeaderText; - + public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } + } public override string HeaderText { get { - if (string.IsNullOrEmpty(base.HeaderText)) - { - base.HeaderText = Localization.GetString(string.Format("{0}.Header", this._HeaderText), DotNetNuke.Web.UI.Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent)); - } - + if (string.IsNullOrEmpty(base.HeaderText)) + { + base.HeaderText = Localization.GetString(string.Format("{0}.Header", this._HeaderText), DotNetNuke.Web.UI.Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent)); + } + return base.HeaderText; } - + set { this._HeaderText = value; @@ -46,8 +46,8 @@ public string setHeaderText { base.HeaderText = value; } - } - + } + public override GridColumn Clone() { var dnnGridColumn = new DnnGridColumn(); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs index 2a5856e4c8f..926e853e134 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDataItem.cs @@ -7,12 +7,12 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridDataItem : GridDataItem { - public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) { } - public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) + public DnnGridDataItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) : base(ownerTableView, itemIndex, dataSetIndex, itemType) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs index d3edd19bad2..1055ec44882 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDateTimeColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridDateTimeColumn : GridDateTimeColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridDateTimeColumn dnnGridColumn = new DnnGridDateTimeColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs index 73fd7c2d0cd..59bd6ac59be 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridDropDownColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridDropDownColumn : GridDropDownColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridDropDownColumn dnnGridColumn = new DnnGridDropDownColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs index 3e43c9ad122..3f32e90dbec 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditColumn.cs @@ -6,15 +6,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridEditColumn : GridEditCommandColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridEditColumn dnnGridColumn = new DnnGridEditColumn(); @@ -23,6 +23,6 @@ public override GridColumn Clone() dnnGridColumn.CopyBaseProperties(this); return dnnGridColumn; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs index c26e1128369..fd2f5868a4f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridEditFormSettings.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridEditFormSettings : GridEditFormSettings { - public DnnGridEditFormSettings(DnnGridTableView owner) + public DnnGridEditFormSettings(DnnGridTableView owner) : base(owner) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs index 75833d51aa4..8a1ee51e863 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridExpandColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridExpandColumn : GridColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridExpandColumn dnnGridColumn = new DnnGridExpandColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs index e3247ddbb13..7627b7b80d4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridFooterItem.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridFooterItem : GridFooterItem { - public DnnGridFooterItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + public DnnGridFooterItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs index 6571c9477ed..3bb5725316c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridGroupSplitterColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridAttachmentColumn : GridAttachmentColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridAttachmentColumn dnnGridColumn = new DnnGridAttachmentColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs index 3db65db9141..ec8e9b392a5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHTMLEditorColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridHTMLEditorColumn : GridHTMLEditorColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridHTMLEditorColumn dnnGridColumn = new DnnGridHTMLEditorColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs index 45d8781c885..f6a3e590c0f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHeaderItem.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridHeaderItem : GridHeaderItem { - public DnnGridHeaderItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) + public DnnGridHeaderItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex) : base(ownerTableView, itemIndex, dataSetIndex) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs index 0706ce503d0..38fec61d694 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridHyperlinkColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridHyperLinkColumn : GridHyperLinkColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridHyperLinkColumn dnnGridColumn = new DnnGridHyperLinkColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs index be88c628b12..4d93a507ac8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridImageColumn : GridImageColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridImageColumn dnnGridColumn = new DnnGridImageColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs index be0027ae8cf..d7c772030de 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumn.cs @@ -23,7 +23,7 @@ public class DnnGridImageCommandColumn : DnnGridTemplateColumn /// /// A String. public string CommandName { get; set; } - + /// /// Gets or sets editMode for the Column. /// @@ -33,7 +33,7 @@ public ImageCommandColumnEditMode EditMode get { return this._editMode; } set { this._editMode = value; } } - + /// /// Gets or sets the URL of the Image. /// @@ -49,52 +49,52 @@ public string ImageURL return IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); } - + set { this._imageURL = value; } } - + /// /// Gets or sets the Icon Key to obtain ImageURL. /// /// A String. public string IconKey { get; set; } - + /// /// Gets or sets the Icon Siz to obtain ImageURL. /// /// A String. public string IconSize { get; set; } - + /// /// Gets or sets the Icon Style to obtain ImageURL. /// /// A String. public string IconStyle { get; set; } - + /// /// Gets or sets the Key Field that provides a Unique key to the data Item. /// /// A String. public string KeyField { get; set; } - + /// /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// /// A String. public string NavigateURL { get; set; } - + /// /// Gets or sets the URL Formatting string. /// /// A String. public string NavigateURLFormatString { get; set; } - + /// /// Gets or sets javascript text to attach to the OnClick Event. /// /// A String. public string OnClickJs { get; set; } - + /// /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// @@ -105,13 +105,13 @@ public bool ShowImage get { return this._showImage; } set { this._showImage = value; } } - + /// /// Gets or sets the Text (for Header/Footer Templates). /// /// A String. public string Text { get; set; } - + /// /// Gets or sets an flag that indicates whether the buttons are visible. /// @@ -133,11 +133,11 @@ public override void Initialize() 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. /// @@ -156,7 +156,7 @@ private DnnGridImageCommandColumnTemplate CreateTemplate(GridItemType type) template.KeyField = this.KeyField; } } - + template.EditMode = this.EditMode; template.NavigateURL = this.NavigateURL; template.NavigateURLFormatString = this.NavigateURLFormatString; diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs index 4a86cc60f9f..48b4b8abde3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridImageCommandColumnTemplate.cs @@ -31,19 +31,19 @@ public DnnGridImageCommandColumnTemplate(GridItemType itemType) { this.ItemType = itemType; } - + /// /// Gets or sets the CommandName for the Column. /// /// A String. public string CommandName { get; set; } - + /// /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. /// /// A Boolean. public bool DesignMode { get; set; } - + /// /// Gets or sets the CommandName for the Column. /// @@ -53,13 +53,13 @@ public ImageCommandColumnEditMode EditMode get { return this._editMode; } set { this._editMode = value; } } - + /// /// Gets or sets the URL of the Image. /// /// A String. public string ImageURL { get; set; } - + /// /// Gets or sets the type of Template to Create. /// @@ -69,31 +69,31 @@ public GridItemType ItemType get { return this._itemType; } set { this._itemType = value; } } - + /// /// Gets or sets the Key Field that provides a Unique key to the data Item. /// /// A String. public string KeyField { get; set; } - + /// /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// /// A String. public string NavigateURL { get; set; } - + /// /// Gets or sets the URL Formatting string. /// /// A String. public string NavigateURLFormatString { get; set; } - + /// /// Gets or sets javascript text to attach to the OnClick Event. /// /// A String. public string OnClickJs { get; set; } - + /// /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// @@ -104,13 +104,13 @@ public bool ShowImage get { return this._showImage; } set { this._showImage = value; } } - + /// /// Gets or sets the Text (for Header/Footer Templates). /// /// A String. public string Text { get; set; } - + /// /// Gets or sets a value indicating whether an flag that indicates whether the buttons are visible (this is overridden if /// the VisibleField is set) @@ -122,13 +122,13 @@ public bool Visible get { return this._visible; } set { this._visible = value; } } - + /// /// Gets or sets an flag that indicates whether the buttons are visible. /// /// A Boolean. - public string VisibleField { get; set; } - + public string VisibleField { get; set; } + /// /// InstantiateIn instantiates the template (implementation of ITemplate). /// @@ -156,7 +156,7 @@ public void InstantiateIn(Control container) { hypLink.Text = this.Text; } - + hypLink.DataBinding += this.ItemDataBinding; container.Controls.Add(hypLink); } @@ -164,18 +164,18 @@ public void InstantiateIn(Control container) { if (!string.IsNullOrEmpty(this.ImageURL) && this.ShowImage) { - var colIcon = new ImageButton + 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); } - + colIcon.CommandName = this.CommandName; colIcon.DataBinding += this.ItemDataBinding; container.Controls.Add(colIcon); } - + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { var colLink = new LinkButton { ToolTip = this.Text }; @@ -183,14 +183,14 @@ public void InstantiateIn(Control container) { ClientAPI.AddButtonConfirm(colLink, this.OnClickJs); } - + colLink.CommandName = this.CommandName; colLink.Text = this.Text; colLink.DataBinding += this.ItemDataBinding; container.Controls.Add(colLink); } } - + break; case GridItemType.Footer: case GridItemType.Header: @@ -204,8 +204,8 @@ public IOrderedDictionary ExtractValues(Control container) // do nothing we don't really support databinding // but the telerik grid trys to databind to all template columns regardless return new OrderedDictionary(); - } - + } + /// /// Gets whether theButton is visible. /// @@ -219,7 +219,7 @@ private bool GetIsVisible(GridItem container) return this.Visible; } - + /// /// Gets the value of the key. /// @@ -231,10 +231,10 @@ private int GetValue(GridItem container) { keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField)); } - + return keyValue; } - + /// /// Item_DataBinding runs when an Item of type GridItemType.Item is being data-bound. /// @@ -271,7 +271,7 @@ private void ItemDataBinding(object sender, EventArgs e) colIcon.CommandArgument = keyValue.ToString(CultureInfo.InvariantCulture); colIcon.Visible = this.GetIsVisible(container); } - + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { // Bind Link Button diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs index 11eabf7f8e6..30407cebb4d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItem.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridItem : GridItem { - public DnnGridItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) + public DnnGridItem(GridTableView ownerTableView, int itemIndex, int dataSetIndex, GridItemType itemType) : base(ownerTableView, itemIndex, dataSetIndex, itemType) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs index 89a70db3ebc..2a11751fe05 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridItemSelectedEventArgs.cs @@ -9,19 +9,19 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnGridItemSelectedEventArgs : EventArgs { - private readonly GridItemCollection _SelectedItems; - + private readonly GridItemCollection _SelectedItems; + public DnnGridItemSelectedEventArgs(GridItemCollection selectedItems) { this._SelectedItems = selectedItems; - } - + } + public GridItemCollection SelectedItems { get { return this._SelectedItems; } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs index 3c03130f814..5696b44a7f6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridMaskedColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridMaskedColumn : GridMaskedColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridMaskedColumn dnnGridColumn = new DnnGridMaskedColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs index 96df3eab746..1bcb89075e4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridNumericColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridNumericColumn : GridNumericColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridNumericColumn dnnGridColumn = new DnnGridNumericColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs index 18b6833b411..df154e8d529 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRatingColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridRatingColumn : GridRatingColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridRatingColumn dnnGridColumn = new DnnGridRatingColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs index bd868cfe396..f9b0b1ed25c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridRowIndicatorColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridRowIndicatorColumn : GridRowIndicatorColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridRowIndicatorColumn dnnGridColumn = new DnnGridRowIndicatorColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs index df8dc141566..dd6a8a1bece 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTableView.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridTableView : GridTableView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs index 131be71ded8..5d8fbbf33d1 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnGridTemplateColumn.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnGridTemplateColumn : GridTemplateColumn - { + { public string LocalResourceFile { get { return Utilities.GetLocalResourceFile(this.Owner.OwnerGrid.Parent); } - } - + } + public override GridColumn Clone() { DnnGridTemplateColumn dnnGridColumn = new DnnGridTemplateColumn(); @@ -36,6 +36,6 @@ public override void InitializeCell(TableCell cell, int columnIndex, GridItem in { cell.Text = Localization.GetString(string.Format("{0}.Header", this.HeaderText), this.LocalResourceFile); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs index 6ae8d035317..d46f2889cd4 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnInputManager.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnInputManager : RadInputManager - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs index a8581217a7f..520fc001e74 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnLanguageComboBox.cs @@ -24,7 +24,7 @@ public class DnnLanguageComboBox : WebControl private DnnComboBox _nativeCombo; private string _originalValue; - + public DnnLanguageComboBox() { this.AutoPostBack = Null.NullBoolean; @@ -34,38 +34,30 @@ public DnnLanguageComboBox() this.HideLanguagesList = new Dictionary(); this.FlagImageUrlFormatString = "~/images/Flags/{0}.gif"; this._viewTypePersonalizationKey = "ViewType" + this.PortalId; - } - - public event EventHandler ItemChanged; - - public event EventHandler ModeChanged; + } - public string FlagImageUrlFormatString { get; set; } + public event EventHandler ItemChanged; - public Dictionary HideLanguagesList { get; set; } + public event EventHandler ModeChanged; - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - - private string DisplayMode + public string SelectedValue { get { - string displayMode = Convert.ToString(Personalization.GetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey)); - if (string.IsNullOrEmpty(displayMode)) + string selectedValue = this.DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase) ? this._nativeCombo.SelectedValue : this._englishCombo.SelectedValue; + if (selectedValue == "None") { - displayMode = "NATIVE"; + selectedValue = Null.NullString; } - - return displayMode; + + return selectedValue; } } + public string FlagImageUrlFormatString { get; set; } + + public Dictionary HideLanguagesList { get; set; } + public bool IncludeNoneSpecified { get; set; } public LanguagesListType LanguagesListType @@ -74,7 +66,7 @@ public LanguagesListType LanguagesListType { return this._languagesListType; } - + set { this._languagesListType = value; @@ -83,20 +75,6 @@ public LanguagesListType LanguagesListType public int PortalId { get; set; } - public string SelectedValue - { - get - { - string selectedValue = this.DisplayMode.Equals("NATIVE", StringComparison.InvariantCultureIgnoreCase) ? this._nativeCombo.SelectedValue : this._englishCombo.SelectedValue; - if (selectedValue == "None") - { - selectedValue = Null.NullString; - } - - return selectedValue; - } - } - public bool ShowFlag { get; set; } public bool ShowModeButtons { get; set; } @@ -108,8 +86,30 @@ public string SelectedValue /// ----------------------------------------------------------------------------- public bool AutoPostBack { get; set; } - public bool CausesValidation { get; set; } - + public bool CausesValidation { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + + private string DisplayMode + { + get + { + string displayMode = Convert.ToString(Personalization.GetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey)); + if (string.IsNullOrEmpty(displayMode)) + { + displayMode = "NATIVE"; + } + + return displayMode; + } + } + public void BindData(bool refresh) { if (refresh) @@ -141,7 +141,7 @@ public void BindData(bool refresh) this._nativeCombo.DataSource = cultures.OrderBy(c => c.NativeName); this._englishCombo.DataSource = cultures.OrderBy(c => c.EnglishName); } - + this._nativeCombo.DataBind(); this._englishCombo.DataBind(); @@ -150,8 +150,8 @@ public void BindData(bool refresh) this._englishCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); this._nativeCombo.Items.Insert(0, new RadComboBoxItem(Localization.GetString("System_Default", Localization.SharedResourceFile), "None")); } - } - + } + public void SetLanguage(string code) { if (string.IsNullOrEmpty(code)) @@ -169,8 +169,8 @@ public void SetLanguage(string code) public override void DataBind() { this.BindData(!this.Page.IsPostBack); - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -217,7 +217,7 @@ protected void OnModeChanged(EventArgs e) this.ModeChanged(this, e); } } - + protected override void OnPreRender(EventArgs e) { if (this.DisplayMode.Equals("ENGLISH", StringComparison.InvariantCultureIgnoreCase)) @@ -241,7 +241,7 @@ protected override void OnPreRender(EventArgs e) { item.ImageUrl = string.Format(this.FlagImageUrlFormatString, item.Value); } - + foreach (RadComboBoxItem item in this._nativeCombo.Items) { item.ImageUrl = string.Format(this.FlagImageUrlFormatString, item.Value); @@ -261,8 +261,8 @@ protected override void OnPreRender(EventArgs e) this._nativeCombo.Width = this.Width; base.OnPreRender(e); - } - + } + private void ModeChangedInternal(object sender, EventArgs e) { Personalization.SetProfile("LanguageDisplayMode", this._viewTypePersonalizationKey, this._modeRadioButtonList.SelectedValue); @@ -276,6 +276,6 @@ private void ModeChangedInternal(object sender, EventArgs e) private void ItemChangedInternal(object sender, EventArgs e) { this.OnItemChanged(); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs index d0776e7427f..050e02e916a 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListBoxItem.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnListBoxItem : RadListBoxItem - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs index 8f50da1baf7..174aabf9a91 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListView.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnListView : RadListView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs index f32b7134299..01808baba44 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItem.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnListViewItem : RadListViewItem { - public DnnListViewItem(RadListViewItemType itemType, RadListView ownerView) + public DnnListViewItem(RadListViewItemType itemType, RadListView ownerView) : base(itemType, ownerView) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs index be1514a4a9e..5056d9f6440 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnListViewItemDragHandle.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnListViewItemDragHandle : RadListViewItemDragHandle - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs index 89b68b29fc2..23abdaa3329 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMaskedTextBox.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnMaskedTextBox : RadMaskedTextBox - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs index b8ae7ec29b5..49565bc2246 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenu.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnMenu : RadMenu - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs index dfce694f15b..d2f77890228 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItem.cs @@ -11,12 +11,12 @@ public DnnMenuItem() { } - public DnnMenuItem(string text) + public DnnMenuItem(string text) : base(text) { } - public DnnMenuItem(string text, string navigateUrl) + public DnnMenuItem(string text, string navigateUrl) : base(text, navigateUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs index 0dce6d38afd..b502420a80d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMenuItemBinding.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnMenuItemBinding : RadMenuItemBinding - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs index fc92438e2ae..bd02285bf03 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnModuleComboBox.cs @@ -20,14 +20,12 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnModuleComboBox : WebControl { - private const string DefaultExtensionImage = "icon_extensions_32px.png"; - + private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private DnnComboBox _moduleCombo; private string _originalValue; - - public event EventHandler ItemChanged; - - public Func, bool> Filter { get; set; } + + public event EventHandler ItemChanged; public int ItemCount { @@ -53,19 +51,21 @@ public string RadComboBoxClientId } } - public override bool Enabled + public Func, bool> Filter { get; set; } + + public override bool Enabled { get { return this._moduleCombo.Enabled; } - + set { this._moduleCombo.Enabled = value; } - } - + } + public void BindAllPortalDesktopModules() { this._moduleCombo.SelectedValue = null; @@ -81,7 +81,12 @@ public void BindTabModulesByTabID(int tabID) this._moduleCombo.DataBind(); this.BindTabModuleImages(tabID); } - + + public void SetModule(string code) + { + this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -97,6 +102,25 @@ protected override void OnLoad(EventArgs e) this._originalValue = this.SelectedValue; } + protected virtual void OnItemChanged() + { + if (this.ItemChanged != null) + { + this.ItemChanged(this, new EventArgs()); + } + } + + protected override void OnPreRender(EventArgs e) + { + if (this._moduleCombo.Items.FindItemByValue(this._originalValue) != null) + { + this._moduleCombo.Items.FindItemByValue(this._originalValue).Selected = true; + } + + this._moduleCombo.Width = this.Width; + base.OnPreRender(e); + } + private static Dictionary GetTabModules(int tabID) { var tabModules = ModuleController.Instance.GetTabModules(tabID); @@ -120,7 +144,7 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } - + private Dictionary GetPortalDesktopModules() { IOrderedEnumerable> portalModulesList; @@ -137,7 +161,7 @@ private Dictionary GetPortalDesktopModules() .OrderBy(c => c.Key); } - return portalModulesList.ToDictionary( + return portalModulesList.ToDictionary( portalModule => portalModule.Value.DesktopModuleID, portalModule => portalModule.Key); } @@ -177,30 +201,6 @@ where tabMods.Value.ModuleID.ToString() == item.Value item.ImageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; } - } - - protected virtual void OnItemChanged() - { - if (this.ItemChanged != null) - { - this.ItemChanged(this, new EventArgs()); - } } - - protected override void OnPreRender(EventArgs e) - { - if (this._moduleCombo.Items.FindItemByValue(this._originalValue) != null) - { - this._moduleCombo.Items.FindItemByValue(this._originalValue).Selected = true; - } - - this._moduleCombo.Width = this.Width; - base.OnPreRender(e); - } - - public void SetModule(string code) - { - this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs index a17ab66532d..4e308afecdf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnMonthYearPicker.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; internal class DnnMonthYearPicker : RadMonthYearPicker - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs index 3ed5b6e1184..4d0391c6190 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnNumericTextBox.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnNumericTextBox : RadNumericTextBox - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs index 7fa1f76fdf1..3a787a9c9b6 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPageView.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnPageView : RadPageView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs index 6ee036da2b4..89a63a43b20 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItem.cs @@ -11,12 +11,12 @@ public DnnPanelItem() { } - public DnnPanelItem(string text) + public DnnPanelItem(string text) : base(text) { } - public DnnPanelItem(string text, string navigateUrl) + public DnnPanelItem(string text, string navigateUrl) : base(text, navigateUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs index f2127fd2506..ebbf6742c16 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnPanelItemBinding.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnPanelItemBinding : RadPanelItemBinding - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs index 7c63de1d40c..8f664c7c1c7 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnProgressManager.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnProgressManager : RadProgressManager - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs index 8f57e43f1dc..67ea398b49c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadButton.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRadButton : RadButton - { - private bool _Localize = true; - + { + private bool _Localize = true; + public bool Localize { get @@ -21,18 +21,18 @@ public bool Localize { return false; } - + return this._Localize; } - + set { this._Localize = value; } - } - - public string LocalResourceFile { get; set; } - + } + + public string LocalResourceFile { get; set; } + public virtual void LocalizeStrings() { if (this.Localize) @@ -52,18 +52,18 @@ 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/DnnRadRibbonBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs index f9e9cc78423..786eceacb9d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRadRibbonBar.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRadRibbonBar : RadRibbonBar - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs index 97e1d407265..3bcb34b88f5 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRating.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRating : RadRating - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs index c245473e668..6b63156a7e7 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRatingItem.cs @@ -11,17 +11,17 @@ public DnnRatingItem() { } - public DnnRatingItem(string imageUrl) + public DnnRatingItem(string imageUrl) : base(imageUrl) { } - public DnnRatingItem(string imageUrl, string selectedImageUrl) + public DnnRatingItem(string imageUrl, string selectedImageUrl) : base(imageUrl, selectedImageUrl) { } - public DnnRatingItem(string imageUrl, string selectedImageUrl, string hoveredImageUrl) + public DnnRatingItem(string imageUrl, string selectedImageUrl, string hoveredImageUrl) : base(imageUrl, selectedImageUrl, hoveredImageUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs index d686ae6f368..d852486d132 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotator.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnRotator : RadRotator - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs index f18a9c0bda1..8e90b369e17 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnRotatorItem.cs @@ -11,7 +11,7 @@ public DnnRotatorItem() { } - public DnnRotatorItem(object dataItem) + public DnnRotatorItem(object dataItem) : base(dataItem) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs index dae995b8316..76dfd34390b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScheduler.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnScheduler : RadScheduler - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs index 779d53674e4..655843388ea 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerContextMenu.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSchedulerContextMenu : RadSchedulerContextMenu - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs index 437585a56a3..c8b2e0fb5aa 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceStyleMapping.cs @@ -11,12 +11,12 @@ public DnnSchedulerResourceStyleMapping() { } - public DnnSchedulerResourceStyleMapping(string type, string key, string applyCssClass) + public DnnSchedulerResourceStyleMapping(string type, string key, string applyCssClass) : base(type, key, applyCssClass) { } - public DnnSchedulerResourceStyleMapping(string type, string key, string text, string applyCssClass) + public DnnSchedulerResourceStyleMapping(string type, string key, string text, string applyCssClass) : base(type, key, text, applyCssClass) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs index 882a59c9458..32d87c37b81 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSchedulerResourceType.cs @@ -11,12 +11,12 @@ public DnnSchedulerResourceType() { } - public DnnSchedulerResourceType(string resourceTypeName) + public DnnSchedulerResourceType(string resourceTypeName) : base(resourceTypeName) { } - public DnnSchedulerResourceType(string resourceTypeName, bool allowMultipleResourceValues) + public DnnSchedulerResourceType(string resourceTypeName, bool allowMultipleResourceValues) : base(resourceTypeName, allowMultipleResourceValues) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs index bc4a9bf0535..6ef688d3ecd 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptBlock.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnScriptBlock : RadScriptBlock - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs index 301eadaa7fc..8c66b6d5e02 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; internal class DnnScriptManager : RadScriptManager - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs index 44250b68d62..cba7a519547 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMap.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSiteMap : RadSiteMap - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs index 7259057a2f0..c89dc2520cf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapLevelSetting.cs @@ -11,17 +11,17 @@ public DnnSiteMapLevelSetting() { } - public DnnSiteMapLevelSetting(int level) + public DnnSiteMapLevelSetting(int level) : base(level) { } - public DnnSiteMapLevelSetting(int level, SiteMapLayout layout) + public DnnSiteMapLevelSetting(int level, SiteMapLayout layout) : base(level, layout) { } - public DnnSiteMapLevelSetting(SiteMapLayout layout) + public DnnSiteMapLevelSetting(SiteMapLayout layout) : base(layout) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs index e61bcf2157d..1ee6cf6e75d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNode.cs @@ -11,7 +11,7 @@ public DnnSiteMapNode() { } - public DnnSiteMapNode(string text, string navigateUrl) + public DnnSiteMapNode(string text, string navigateUrl) : base(text, navigateUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs index b7d07479108..9209e0d7ead 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSiteMapNodeBinding.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSiteMapNodeBinding : RadSiteMapNodeBinding - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs index 8233bb6851f..32eb6103a1b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSkinComboBox.cs @@ -21,12 +21,12 @@ 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; } @@ -35,13 +35,13 @@ public DnnSkinComboBox() public bool IncludeNoneSpecificItem { get; set; } - public string NoneSpecificText { get; set; } - + public string NoneSpecificText { get; set; } + private PortalInfo Portal { get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -73,8 +73,8 @@ protected override void PerformDataBinding(IEnumerable dataSource) base.PerformDataBinding(dataSource); this.SelectedValue = selectedValue; - } - + } + private void AttachEvents() { if (!UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -113,6 +113,6 @@ private void AttachEvents() this.ToolTip = tooltip; } } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs index 6be6ff2eaaf..d971b9b7f6c 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSliderItem.cs @@ -11,12 +11,12 @@ public DnnSliderItem() { } - public DnnSliderItem(string text) + public DnnSliderItem(string text) : base(text) { } - public DnnSliderItem(string text, string value) + public DnnSliderItem(string text, string value) : base(text, value) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs index 3297e3ac946..bf98d73ee2a 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSpell.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSpell : RadSpell - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs index 1e5475a448a..1451f65609b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitBar.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSplitBar : RadSplitBar - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs index 6e13996e756..e338c263ed3 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitPane.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSplitPane : RadPane - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs index 62dd9a09144..2e5b161f045 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingPane.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSplitSlidingPane : RadSlidingPane - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs index 51cef78adf6..4b7da72df31 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitSlidingZone.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSplitSlidingZone : RadSlidingZone - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs index f38478fc828..9fbd0eb311d 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnSplitter.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnSplitter : RadSplitter - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs index ac091065266..bc4b0c7c9d8 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTagCloudItem.cs @@ -11,7 +11,7 @@ public DnnTagCloudItem() { } - public DnnTagCloudItem(string text) + public DnnTagCloudItem(string text) : base(text) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs index b7c23c310ee..75e4096cd4b 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTicker.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnTicker : RadTicker - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs index 8b5c238ba09..46d3b343346 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTickerItem.cs @@ -11,12 +11,12 @@ public DnnTickerItem() { } - public DnnTickerItem(string text) + public DnnTickerItem(string text) : base(text) { } - public DnnTickerItem(string text, string navigateUrl) + public DnnTickerItem(string text, string navigateUrl) : base(text, navigateUrl) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs index 98c2e56f1e3..6088ddd8d79 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTimeView.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnTimeView : RadTimeView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs index 8900449e819..639c9b4af95 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBar.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnToolBar : RadToolBar - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs index e556e4ad57c..543307bedbf 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarButton.cs @@ -11,12 +11,12 @@ public DnnToolBarButton() { } - public DnnToolBarButton(string text) + public DnnToolBarButton(string text) : base(text) { } - public DnnToolBarButton(string text, bool isChecked, string @group) + public DnnToolBarButton(string text, bool isChecked, string @group) : base(text, isChecked, @group) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs index 839add20ff6..5bc6bd7bffb 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarDropDown.cs @@ -11,7 +11,7 @@ public DnnToolBarDropDown() { } - public DnnToolBarDropDown(string text) + public DnnToolBarDropDown(string text) : base(text) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs index c7075754a01..5297f958494 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolBarSplitButton.cs @@ -11,7 +11,7 @@ public DnnToolBarSplitButton() { } - public DnnToolBarSplitButton(string text) + public DnnToolBarSplitButton(string text) : base(text) { } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs index e46bf6afea8..c73f2352935 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTip.cs @@ -35,12 +35,6 @@ public bool Localize 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))) @@ -61,5 +55,11 @@ public virtual void LocalizeStrings() } } } + + protected override void Render(HtmlTextWriter writer) + { + this.LocalizeStrings(); + base.Render(writer); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs index 46a2ed49d42..c7e5bec5745 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnToolTipManager.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnToolTipManager : RadToolTipManager - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs index ccfc3193831..132e3ae5b00 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeList.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnTreeList : RadTreeList - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs index 1accdd411b0..106989776dc 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeNode.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnTreeNode : RadTreeNode - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs index 90e0ab756d6..4be5ea9c44f 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnUpload.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnUpload : RadUpload - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs index 99464ea293e..afab5c19831 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindow.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnWindow : RadWindow - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs index 197a32f54a2..922e0edfa58 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnWindowManager.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Web.UI.WebControls using Telerik.Web.UI; public class DnnWindowManager : RadWindowManager - { - } + {} } 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 c9d135df542..82ed0d856ba 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateEditControl.cs @@ -31,30 +31,30 @@ namespace DotNetNuke.Web.UI.WebControls.PropertyEditorControls public class DateEditControl : EditControl { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); - private DnnDatePicker _dateControl; - + private DnnDatePicker _dateControl; + + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.DateInput.ClientID; + } + } + 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. @@ -75,7 +75,7 @@ protected DateTime DateValue { Logger.Error(exc); } - + return dteValue; } } @@ -120,7 +120,7 @@ protected virtual string Format } } } - + return _Format; } } @@ -149,7 +149,7 @@ protected DateTime OldDateValue { Logger.Error(exc); } - + return dteValue; } } @@ -166,16 +166,16 @@ protected override string StringValue { _StringValue = this.DateValue.ToString(this.Format); } - + return _StringValue; } - + set { this.Value = DateTime.Parse(value); } - } - + } + private DnnDatePicker DateControl { get @@ -187,7 +187,7 @@ private DnnDatePicker DateControl return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -208,15 +208,15 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo dataChanged = true; } } - + this.LoadDateControls(); return dataChanged; } - + protected override void CreateChildControls() { base.CreateChildControls(); - + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); this.DateControl.ID = base.ID + "_control"; 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 e2664d9d320..f519a8d6d04 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/PropertyEditorControls/DateTimeEditControl.cs @@ -35,21 +35,21 @@ namespace DotNetNuke.Web.UI.WebControls.PropertyEditorControls public class DateTimeEditControl : EditControl { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); - private DnnDateTimePicker _dateControl; - + 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. @@ -70,7 +70,7 @@ protected DateTime DateValue { Logger.Error(exc); } - + return dteValue; } } @@ -115,7 +115,7 @@ protected virtual string Format } } } - + return _Format; } } @@ -144,7 +144,7 @@ protected DateTime OldDateValue { Logger.Error(exc); } - + return dteValue; } } @@ -161,16 +161,16 @@ protected override string StringValue { _StringValue = this.DateValue.ToString(this.Format); } - + return _StringValue; } - + set { this.Value = DateTime.Parse(value); } - } - + } + private DnnDateTimePicker DateControl { get @@ -182,7 +182,7 @@ private DnnDateTimePicker DateControl return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -208,11 +208,11 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo } } } - + this.LoadDateControls(); return dataChanged; } - + protected override void CreateChildControls() { base.CreateChildControls(); diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs index fb5b16143a5..11fdf385f23 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsList.cs @@ -16,10 +16,10 @@ public class TermsList : WebControl private bool _IsHeirarchical; private DnnListBox _ListBox; - private DnnTreeView _TreeView; - - public event EventHandler SelectedTermChanged; - + private DnnTreeView _TreeView; + + public event EventHandler SelectedTermChanged; + public bool IsHeirarchical { get @@ -45,7 +45,7 @@ public Term SelectedTerm } } } - + return _SelectedTerm; } } @@ -63,7 +63,7 @@ public string SelectedValue { _SelectedValue = this._ListBox.SelectedValue; } - + return _SelectedValue; } } @@ -81,11 +81,11 @@ public List Terms { _DataSource = this._ListBox.DataSource; } - + return _DataSource as List; } - } - + } + public void BindTerms(List terms, bool isHeirarchical, bool dataBind) { this._IsHeirarchical = isHeirarchical; @@ -104,8 +104,8 @@ public void ClearSelectedTerm() { this._ListBox.SelectedIndex = Null.NullInteger; this._TreeView.UnselectAllNodes(); - } - + } + protected override void CreateChildControls() { this.Controls.Clear(); @@ -156,8 +156,8 @@ protected virtual void OnSelectedTermChanged(TermsEventArgs e) { this.SelectedTermChanged(this, e); } - } - + } + private void ListBoxSelectedIndexChanged(object sender, EventArgs e) { // Raise the SelectedTermChanged Event @@ -168,6 +168,6 @@ private void TreeViewNodeClick(object sender, RadTreeNodeEventArgs e) { // Raise the SelectedTermChanged Event this.OnSelectedTermChanged(new TermsEventArgs(this.SelectedTerm)); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs index 9b1e7dd7921..701efa3e5f2 100644 --- a/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/TermsSelector.cs @@ -27,16 +27,16 @@ public TermsSelector() this.IncludeSystemVocabularies = false; this.IncludeTags = true; this.EnableViewState = false; - } - + } + public int PortalId { get; set; } public bool IncludeSystemVocabularies { get; set; } public bool IncludeTags { get; set; } - public List Terms { get; set; } - + public List Terms { get; set; } + public string RaiseClientAPICallbackEvent(string eventArgument) { var parameters = eventArgument.Split('-'); @@ -47,8 +47,8 @@ public string RaiseClientAPICallbackEvent(string eventArgument) 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(); @@ -102,12 +102,12 @@ protected override void OnLoad(EventArgs e) } } } - + if (!this.Page.IsPostBack) { this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.js"); - ClientResourceManager.RegisterStyleSheet( + ClientResourceManager.RegisterStyleSheet( this.Page, this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "DotNetNuke.Web.UI.WebControls.Resources.TermsSelector.css")); @@ -124,12 +124,12 @@ protected override void OnPreRender(EventArgs e) { this.Attributes.Add("SelectedTerms", string.Join(",", this.Terms.Select(t => t.TermId.ToString()).ToArray())); } - + this.Attributes.Add("IncludeSystemVocabularies", this.IncludeSystemVocabularies.ToString().ToLowerInvariant()); this.Attributes.Add("IncludeTags", this.IncludeTags.ToString().ToLowerInvariant()); this.Attributes.Add("PortalId", this.PortalId.ToString()); - } - + } + private ArrayList GetTerms() { var vocabRep = Util.GetVocabularyController(); @@ -163,25 +163,25 @@ private void AddTerms(Vocabulary v, ArrayList terms) { terms.Add(new { termId = -v.VocabularyId, name = v.Name, parentTermId = Null.NullInteger }); } - + foreach (Term t in termRep.GetTermsByVocabulary(v.VocabularyId)) { if (v.Type == VocabularyType.Simple) { t.ParentTermId = -v.VocabularyId; } - + 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; - + private DnnTreeView _tree; + public void InstantiateIn(Control container) { this._container = (RadComboBoxItem)container; @@ -196,7 +196,7 @@ public void InstantiateIn(Control container) this._tree.OnClientNodeChecked = "webcontrols.termsSelector.OnClientNodeChecked"; this._container.Controls.Add(this._tree); - } - } + } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs index 8c47fc161fd..b0a993424bc 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/AntiForgeryImpl.cs @@ -6,11 +6,11 @@ namespace DotNetNuke.Web.Mvc.Common { internal class AntiForgeryImpl : IAntiForgery { - public string CookieName - { - get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } - } - + public string CookieName + { + get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } + } + public void Validate(string cookieToken, string headerToken) { System.Web.Helpers.AntiForgery.Validate(cookieToken, headerToken); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs index 041b6e714aa..42a26a13d95 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/DesktopModuleControllerAdapter.cs @@ -15,7 +15,7 @@ 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/DictionaryExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs index 2054890fb52..5966e9334f5 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/DictionaryExtensions.cs @@ -19,7 +19,7 @@ internal static class DictionaryExtensions public static void RemoveFromDictionary(this IDictionary dictionary, Func, bool> removeCondition) { // Pass the delegate as the state to avoid a delegate and closure - dictionary.RemoveFromDictionary( + dictionary.RemoveFromDictionary( (entry, innerCondition) => { return innerCondition(entry); @@ -47,7 +47,7 @@ public static void RemoveFromDictionary(this IDictionary 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 d7c633fb398..68cc54fadaf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/PropertyHelper.cs @@ -88,7 +88,7 @@ public object GetValue(object instance) return this._valueGetter(instance); } - protected static PropertyHelper[] GetProperties( + protected static PropertyHelper[] GetProperties( object instance, Func createPropertyHelper, ConcurrentDictionary cache) diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs index 161f0befea8..306639bcedf 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Common/TypeHelper.cs @@ -13,7 +13,7 @@ public static class TypeHelper /// /// This helper will cache accessors and types, and is intended when the anonymous object is accessed multiple /// times throughout the lifetime of the web application. - /// + /// /// public static RouteValueDictionary ObjectToDictionary(object value) { diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs index 570ebf4f341..823f7aea7dd 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcDependencyResolver.cs @@ -37,11 +37,11 @@ public object GetService(Type serviceType) { var accessor = this._serviceProvider.GetRequiredService(); var scope = accessor.GetScope(); - if (scope != null) - { - return scope.ServiceProvider.GetService(serviceType); - } - + if (scope != null) + { + return scope.ServiceProvider.GetService(serviceType); + } + throw new InvalidOperationException("IServiceScope not provided"); } @@ -58,11 +58,11 @@ public IEnumerable GetServices(Type serviceType) { var accessor = this._serviceProvider.GetRequiredService(); var scope = accessor.GetScope(); - if (scope != null) - { - return scope.ServiceProvider.GetServices(serviceType); - } - + if (scope != null) + { + return scope.ServiceProvider.GetServices(serviceType); + } + throw new InvalidOperationException("IServiceScope not provided"); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs index f0d547beb0e..2d42f94695f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcHandler.cs @@ -24,7 +24,7 @@ public class DnnMvcHandler : IHttpHandler, IRequiresSessionState public static readonly string MvcVersionHeaderName = "X-AspNetMvc-Version"; private ControllerBuilder _controllerBuilder; - + public DnnMvcHandler(RequestContext requestContext) { if (requestContext == null) @@ -37,6 +37,8 @@ public DnnMvcHandler(RequestContext requestContext) public static bool DisableMvcResponseHeader { get; set; } + public RequestContext RequestContext { get; private set; } + bool IHttpHandler.IsReusable { get { return this.IsReusable; } @@ -50,10 +52,10 @@ internal ControllerBuilder ControllerBuilder { this._controllerBuilder = ControllerBuilder.Current; } - + return this._controllerBuilder; } - + set { this._controllerBuilder = value; } } @@ -62,8 +64,6 @@ protected virtual bool IsReusable get { return false; } } - public RequestContext RequestContext { get; private set; } - void IHttpHandler.ProcessRequest(HttpContext httpContext) { MembershipModule.AuthenticateRequest(this.RequestContext.HttpContext, allowUnknownExtensions: true); @@ -75,7 +75,7 @@ protected internal virtual void ProcessRequest(HttpContextBase httpContext) try { var moduleExecutionEngine = this.GetModuleExecutionEngine(); - + // Check if the controller supports IDnnController var moduleResult = moduleExecutionEngine.ExecuteModule(this.GetModuleRequestContext(httpContext)); @@ -85,14 +85,14 @@ protected internal virtual void ProcessRequest(HttpContextBase httpContext) finally { } - } + } protected virtual void ProcessRequest(HttpContext httpContext) { HttpContextBase httpContextBase = new HttpContextWrapper(httpContext); this.ProcessRequest(httpContextBase); } - + private IModuleExecutionEngine GetModuleExecutionEngine() { var moduleExecutionEngine = ComponentFactory.GetComponent(); @@ -102,7 +102,7 @@ private IModuleExecutionEngine GetModuleExecutionEngine() moduleExecutionEngine = new ModuleExecutionEngine(); ComponentFactory.RegisterComponentInstance(moduleExecutionEngine); } - + return moduleExecutionEngine; } @@ -132,6 +132,6 @@ private void RenderModule(ModuleRequestResult moduleResult) var moduleExecutionEngine = ComponentFactory.GetComponent(); moduleExecutionEngine.ExecuteModuleResult(moduleResult, writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs index cc70bc66ce1..c8470799b39 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/DnnMvcRouteHandler.cs @@ -22,11 +22,11 @@ public DnnMvcRouteHandler(IControllerFactory controllerFactory) { this._controllerFactory = controllerFactory; } - + IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext) { return this.GetHttpHandler(requestContext); - } + } protected virtual IHttpHandler GetHttpHandler(RequestContext requestContext) { @@ -44,6 +44,6 @@ protected virtual SessionStateBehavior GetSessionStateBehavior(RequestContext re IControllerFactory controllerFactory = this._controllerFactory ?? ControllerBuilder.Current.GetControllerFactory(); return controllerFactory.GetControllerSessionBehavior(requestContext, controllerName); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs index a11e2e53138..2e9488700f2 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthFilterContext.cs @@ -22,7 +22,7 @@ public AuthFilterContext(AuthorizationContext filterContext, string authFailureM } public AuthorizationContext ActionContext { get; private set; } - + public string AuthFailureMessage { get; set; } /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs index 5ea5e45c7a3..c57def7f29d 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/AuthorizeAttributeBase.cs @@ -17,7 +17,7 @@ public static bool IsAnonymousAttributePresent(AuthorizationContext filterContex 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); @@ -36,7 +36,7 @@ public virtual void OnAuthorization(AuthorizationContext filterContext) this.HandleUnauthorizedRequest(filterContext); } } - + protected virtual bool AuthorizeCore(HttpContextBase httpContext) { return true; @@ -49,17 +49,12 @@ 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."; var authFilterContext = new AuthFilterContext(filterContext, failureMessage); authFilterContext.HandleUnauthorizedRequest(); - + // filterContext.HttpContext.Response.Redirect(Globals.AccessDeniedURL()); } @@ -80,5 +75,10 @@ protected virtual bool SkipAuthorization(AuthorizationContext filterContext) { return IsAnonymousAttributePresent(filterContext); } + + private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) + { + validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context)); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs index 5422140e7cf..b80ee47a9b8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/DnnAuthorizeAttribute.cs @@ -27,7 +27,7 @@ public class DnnAuthorizeAttribute : AuthorizeAttributeBase public string StaticRoles { get { return this._staticRoles; } - + set { this._staticRoles = value; @@ -41,7 +41,7 @@ public string StaticRoles public string DenyRoles { get { return this._denyRoles; } - + set { this._denyRoles = value; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs index c2ff7467c55..7823ca4f0b8 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ModuleActionAttribute.cs @@ -61,7 +61,7 @@ public override void OnActionExecuting(ActionExecutingContext filterContext) controller.ModuleActions = new ModuleActionCollection(); } - controller.ModuleActions.Add( + controller.ModuleActions.Add( -1, (!string.IsNullOrEmpty(this.TitleKey)) ? controller.LocalizeString(this.TitleKey) : this.Title, ModuleActionType.AddContent, diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs index df015229dda..eebfd78eac4 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionFilters/ValidateAntiForgeryTokenAttribute.cs @@ -25,7 +25,7 @@ public virtual bool IsAuthenticated(HttpContextBase httpContext) { var headers = httpContext.Request.Headers; var form = httpContext.Request.Form; - + // Try to fetch the token from Headers. (Used with Dnn service framework.). // If not found then fetch it from form fields. (Would be used with standard MVC call). var token = headers.AllKeys.Contains("RequestVerificationToken") ? headers.GetValues("RequestVerificationToken").FirstOrDefault() @@ -78,7 +78,7 @@ protected override bool AuthorizeCore(HttpContextBase httpContext) { return false; } - + return true; } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs index 6d79d51ed49..39312b01bca 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ActionResults/DnnRedirecttoRouteResult.cs @@ -30,12 +30,11 @@ public DnnRedirecttoRouteResult(string actionName, string controllerName, string } public DnnUrlHelper Url { get; private set; } - - protected INavigationManager NavigationManager { get; } public string ActionName { get; private set; } public string ControllerName { get; private set; } + protected INavigationManager NavigationManager { get; } public override void ExecuteResult(ControllerContext context) { diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs index d2c29dbc52e..a776deb9876 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/DnnController.cs @@ -38,26 +38,11 @@ public TabInfo ActivePage get { return (this.PortalSettings == null) ? null : this.PortalSettings.ActiveTab; } } - public Page DnnPage { get; set; } - - public new DnnUrlHelper Url { get; set; } - - public string LocalResourceFile { get; set; } - - public ModuleActionCollection ModuleActions { get; set; } - - public ModuleInstanceContext ModuleContext { get; set; } - public PortalSettings PortalSettings { get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } } - public string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - public ActionResult ResultOfLastExecute { get @@ -72,8 +57,23 @@ public ActionResult ResultOfLastExecute get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } } + public Page DnnPage { get; set; } + + public new DnnUrlHelper Url { get; set; } + + public string LocalResourceFile { get; set; } + + public ModuleActionCollection ModuleActions { get; set; } + + public ModuleInstanceContext ModuleContext { get; set; } + public ViewEngineCollection ViewEngineCollectionEx { get; set; } + public string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } + protected internal RedirectToRouteResult RedirectToDefaultRoute() { return new DnnRedirecttoRouteResult(string.Empty, string.Empty, string.Empty, null, false); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs index 3c2f1ba3b45..28cf2f4acd1 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Controllers/IDnnController.cs @@ -15,6 +15,8 @@ public interface IDnnController : IController { ControllerContext ControllerContext { get; } + ActionResult ResultOfLastExecute { get; } + Page DnnPage { get; set; } string LocalResourceFile { get; set; } @@ -23,14 +25,11 @@ public interface IDnnController : IController ModuleInstanceContext ModuleContext { get; set; } - ActionResult ResultOfLastExecute { get; } - - string LocalizeString(string key); - bool ValidateRequest { get; set; } ViewEngineCollection ViewEngineCollectionEx { get; set; } DnnUrlHelper Url { get; set; } + string LocalizeString(string key); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs index fadc409b3a8..01308e2f809 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ModuleDelegatingViewEngine.cs @@ -61,18 +61,18 @@ private static ModuleRequestResult GetCurrentModuleRequestResult(ControllerConte { return controllerContext.HttpContext.GetModuleRequestResult(); } - + return null; } private ViewEngineResult RunAgainstModuleViewEngines(ControllerContext controllerContext, Func engineRequest) { var controller = controllerContext.Controller as IDnnController; - if (controller == null || controller.ViewEngineCollectionEx == null) - { - return new ViewEngineResult(new string[0]); - } - + if (controller == null || controller.ViewEngineCollectionEx == null) + { + return new ViewEngineResult(new string[0]); + } + var result = engineRequest(controller.ViewEngineCollectionEx); // If there is a view, store the view<->viewengine mapping so release works correctly diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs index 488367a5958..421623069ea 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleApplication.cs @@ -21,7 +21,6 @@ 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"; @@ -33,32 +32,30 @@ public class ModuleApplication private bool _initialized; - public ModuleApplication() + public ModuleApplication() : this(null, false) { } - public RequestContext RequestContext { get; private set; } - - private static bool DisableMvcResponseHeader { get; set; } - - public ModuleApplication(bool disableMvcResponseHeader) + public ModuleApplication(bool disableMvcResponseHeader) : this(null, disableMvcResponseHeader) { } - + public ModuleApplication(RequestContext requestContext, bool disableMvcResponseHeader) { this.RequestContext = requestContext; - + // ReSharper disable once DoNotCallOverridableMethodsInConstructor DisableMvcResponseHeader = disableMvcResponseHeader; this.ControllerFactory = Globals.DependencyProvider.GetRequiredService(); this.ViewEngines = new ViewEngineCollection(); - + // ViewEngines.Add(new ModuleDelegatingViewEngine()); } + public RequestContext RequestContext { get; private set; } + public virtual IControllerFactory ControllerFactory { get; set; } public string DefaultActionName { get; set; } @@ -72,6 +69,7 @@ public ModuleApplication(RequestContext requestContext, bool disableMvcResponseH public string ModuleName { get; set; } public ViewEngineCollection ViewEngines { get; set; } + private static bool DisableMvcResponseHeader { get; set; } public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) { @@ -86,7 +84,7 @@ public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) ValidationUtility.EnableDynamicValidation(currentContext); } } - + this.AddVersionHeader(this.RequestContext.HttpContext); this.RemoveOptionalRoutingParameters(); @@ -112,14 +110,14 @@ public virtual ModuleRequestResult ExecuteRequest(ModuleRequestContext context) moduleController.ModuleContext = context.ModuleContext; - moduleController.LocalResourceFile = string.Format( + moduleController.LocalResourceFile = string.Format( "~/DesktopModules/MVC/{0}/{1}/{2}.resx", context.ModuleContext.Configuration.DesktopModule.FolderName, Localization.LocalResourceDirectory, controllerName); moduleController.ViewEngineCollectionEx = this.ViewEngines; - + // Execute the controller and capture the result // if our ActionFilter is executed after the ActionResult has triggered an Exception the filter // MUST explicitly flip the ExceptionHandled bit otherwise the view will not render @@ -127,13 +125,13 @@ 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 @@ -158,33 +156,12 @@ protected internal virtual void Init() string.Format(CultureInfo.InvariantCulture, SharedPartialFormat, prefix), }; - this.ViewEngines.Add(new RazorViewEngine - { - MasterLocationFormats = masterFormats, - ViewLocationFormats = viewFormats, - PartialViewLocationFormats = viewFormats, - }); - } - - 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) + this.ViewEngines.Add(new RazorViewEngine { - if (this._initialized) - { - return; - } - - this.Init(); - this._initialized = true; - } + MasterLocationFormats = masterFormats, + ViewLocationFormats = viewFormats, + PartialViewLocationFormats = viewFormats, + }); } protected internal virtual void AddVersionHeader(HttpContextBase httpContext) @@ -201,6 +178,27 @@ protected static string NormalizeFolderPath(string path) return !string.IsNullOrEmpty(path) ? path.Trim('/') : path; } + 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; + } + } + private static string GetMvcVersionString() { // DevDiv 216459: diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs index faaa5696a76..ce744c37de3 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ModuleExecutionEngine.cs @@ -21,7 +21,7 @@ public ModuleRequestResult ExecuteModule(ModuleRequestContext moduleRequestConte // Run the module return moduleRequestContext.ModuleApplication.ExecuteRequest(moduleRequestContext); } - + return null; } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs index 0f29b1be48f..c3b3d7c8630 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/Modules/ResultCapturingActionInvoker.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Web.Mvc.Framework.Modules public class ResultCapturingActionInvoker : ControllerActionInvoker { public ActionResult ResultOfLastInvoke { get; set; } - + protected override ActionExecutedContext InvokeActionMethodWithFilters(ControllerContext controllerContext, IList filters, ActionDescriptor actionDescriptor, IDictionary parameters) { var context = base.InvokeActionMethodWithFilters(controllerContext, filters, actionDescriptor, parameters); @@ -29,10 +29,10 @@ protected override ExceptionContext InvokeExceptionFilters(ControllerContext con protected override void InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) { // Do not invoke the action. Instead, store it for later retrieval - if (this.ResultOfLastInvoke == null) - { - this.ResultOfLastInvoke = actionResult; - } + if (this.ResultOfLastInvoke == null) + { + this.ResultOfLastInvoke = actionResult; + } } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs index 5f012848855..c089d5ff67d 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Framework/ViewEngineCollectionExt.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Web.Mvc.Framework public static class ViewEngineCollectionExt { // Enable the call to ViewEngineCollection FindView method with useCache=false - public static ViewEngineResult FindView( + public static ViewEngineResult FindView( this ViewEngineCollection viewEngineCollection, ControllerContext controllerContext, string viewName, string masterName, bool useCache) @@ -48,7 +48,7 @@ public static ViewEngineResult FindView( } // Enable the call to ViewEngineCollection FindPartialView method with useCache=false - public static ViewEngineResult FindPartialView( + public static ViewEngineResult FindPartialView( this ViewEngineCollection viewEngineCollection, ControllerContext controllerContext, string partialViewName, bool useCache) { @@ -79,7 +79,7 @@ private static ViewEngineResult CallFind(CacheItemArgs cacheItem) var target = cacheItem.Params[1]; var parameters = cacheItem.Params[2] as object[]; return - factoryType.InvokeMember( + factoryType.InvokeMember( name, BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, target, parameters) as ViewEngineResult; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs index dfe25e6642f..3e92f6d9212 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHelper.cs @@ -57,27 +57,14 @@ public TabInfo ActivePage get { return (this.PortalSettings == null) ? null : this.PortalSettings.ActiveTab; } } - public Page DnnPage { get; set; } - - public string LocalResourceFile { get; set; } - - public ModuleInstanceContext ModuleContext { get; set; } - - internal HtmlHelper HtmlHelper { get; set; } - public PortalSettings PortalSettings { get { return (this.ModuleContext == null) ? null : this.ModuleContext.PortalSettings; } } - public RouteCollection RouteCollection - { - get { return this.HtmlHelper.RouteCollection; } - } - - public string LocalizeString(string key) + public RouteCollection RouteCollection { - return Localization.GetString(key, this.LocalResourceFile); + get { return this.HtmlHelper.RouteCollection; } } public UserInfo User @@ -85,24 +72,37 @@ public UserInfo User get { return (this.PortalSettings == null) ? null : this.PortalSettings.UserInfo; } } - public dynamic ViewBag - { - get { return this.HtmlHelper.ViewBag; } - } - - public ViewContext ViewContext - { - get { return this.HtmlHelper.ViewContext; } - } - - public ViewDataDictionary ViewData - { - get { return this.HtmlHelper.ViewData; } - } - - public IViewDataContainer ViewDataContainer - { - get { return this.HtmlHelper.ViewDataContainer; } - } + public dynamic ViewBag + { + get { return this.HtmlHelper.ViewBag; } + } + + public ViewContext ViewContext + { + get { return this.HtmlHelper.ViewContext; } + } + + public ViewDataDictionary ViewData + { + get { return this.HtmlHelper.ViewData; } + } + + public IViewDataContainer ViewDataContainer + { + get { return this.HtmlHelper.ViewDataContainer; } + } + + public Page DnnPage { get; set; } + + public string LocalResourceFile { get; set; } + + public ModuleInstanceContext ModuleContext { get; set; } + + internal HtmlHelper HtmlHelper { get; set; } + + public string LocalizeString(string key) + { + return Localization.GetString(key, this.LocalResourceFile); + } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs index ef5d1819820..911174fd094 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnHtmlHelper.cs @@ -40,18 +40,8 @@ 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); - } - public dynamic ViewBag => this.HtmlHelper.ViewBag; public ViewContext ViewContext => this.HtmlHelper.ViewContext; @@ -60,6 +50,16 @@ public MvcHtmlString AntiForgeryToken() public IViewDataContainer ViewDataContainer => this.HtmlHelper.ViewDataContainer; + public ModuleInstanceContext ModuleContext { get; set; } + + internal HtmlHelper HtmlHelper { get; set; } + + public MvcHtmlString AntiForgeryToken() + { + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + return new MvcHtmlString(string.Empty); + } + public string AttributeEncode(string value) => this.HtmlHelper.AttributeEncode(value); public string AttributeEncode(object value) => this.HtmlHelper.AttributeEncode(value); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs index 74e7c975a90..08a9619f2b4 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnLabelExtensions.cs @@ -26,7 +26,7 @@ public static MvcHtmlString Label(this DnnHelper dnnHelper, stri { var htmlHelper = dnnHelper.HtmlHelper as HtmlHelper; - return LabelHelper( + return LabelHelper( htmlHelper, ModelMetadata.FromStringExpression(expression, htmlHelper.ViewData), expression, @@ -79,7 +79,7 @@ public static MvcHtmlString LabelFor(this DnnHelper dnnH { var htmlHelper = dnnHelper.HtmlHelper as HtmlHelper; - return LabelHelper( + return LabelHelper( htmlHelper, ModelMetadata.FromLambdaExpression(expression, dnnHelper.ViewData), ExpressionHelper.GetExpressionText(expression), @@ -138,7 +138,7 @@ public static MvcHtmlString LabelHelper(HtmlHelper html, string htmlFieldName, s toolTipTag.InnerHtml = toolTipContentTag.ToString(); divTag.InnerHtml += toolTipTag.ToString(); - + return new MvcHtmlString(divTag.ToString(TagRenderMode.Normal)); } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs index 6b3e9acdaef..4f82f865c91 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Helpers/DnnUrlHelper.cs @@ -20,7 +20,7 @@ public class DnnUrlHelper private readonly ViewContext _viewContext; private readonly IDnnController _controller; - + public DnnUrlHelper(ViewContext viewContext) : this(viewContext, RouteTable.Routes) { diff --git a/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs index 65f13d08e11..84064357e4f 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/ITabAndModuleInfoProvider.cs @@ -11,9 +11,9 @@ namespace DotNetNuke.Web.Mvc public interface ITabAndModuleInfoProvider { bool TryFindTabId(HttpRequestBase request, out int tabId); - + bool TryFindModuleId(HttpRequestBase request, out int moduleId); - + bool TryFindModuleInfo(HttpRequestBase request, out ModuleInfo moduleInfo); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs index 407d8448d4c..61ce21bbd81 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHostControl.cs @@ -25,10 +25,10 @@ namespace DotNetNuke.Web.Mvc using DotNetNuke.Web.Mvc.Routing; public class MvcHostControl : ModuleControlBase, IActionable - { + { private ModuleRequestResult _result; - private string _controlKey; - + private string _controlKey; + public MvcHostControl() { this._controlKey = string.Empty; @@ -37,11 +37,11 @@ public MvcHostControl() public MvcHostControl(string controlKey) { this._controlKey = controlKey; - } - + } + public ModuleActionCollection ModuleActions { get; private set; } - protected bool ExecuteModuleImmediately { get; set; } = true; + protected bool ExecuteModuleImmediately { get; set; } = true; protected void ExecuteModule() { @@ -61,8 +61,8 @@ protected void ExecuteModule() { Exceptions.ProcessModuleLoadException(this, exc); } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -72,7 +72,29 @@ protected override void OnInit(EventArgs e) this.ExecuteModule(); } } - + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + try + { + if (this._result == null) + { + return; + } + + var mvcString = this.RenderModule(this._result); + if (!string.IsNullOrEmpty(Convert.ToString(mvcString))) + { + this.Controls.Add(new LiteralControl(Convert.ToString(mvcString))); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private ModuleApplication GetModuleApplication(DesktopModuleInfo desktopModule, RouteData defaultRouteData) { ModuleApplication moduleApplication = null; @@ -100,13 +122,13 @@ 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, }; } @@ -164,13 +186,13 @@ 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; @@ -206,27 +228,5 @@ private MvcHtmlString RenderModule(ModuleRequestResult moduleResult) return moduleOutput; } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - try - { - if (this._result == null) - { - return; - } - - var mvcString = this.RenderModule(this._result); - if (!string.IsNullOrEmpty(Convert.ToString(mvcString))) - { - this.Controls.Add(new LiteralControl(Convert.ToString(mvcString))); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs index 423c8154e8a..a63a64d1259 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcHttpModule.cs @@ -39,7 +39,7 @@ public void Init(HttpApplication context) ComponentFactory.RegisterComponentInstance(new ModuleExecutionEngine()); context.BeginRequest += InitDnn; } - + public void Dispose() { } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs index 3dc28447d8d..0db45c1a2e5 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcModuleControlFactory.cs @@ -28,7 +28,7 @@ public override ModuleControlBase CreateModuleControl(ModuleInfo moduleConfigura var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - moduleControl.LocalResourceFile = string.Format( + moduleControl.LocalResourceFile = string.Format( "~/DesktopModules/MVC/{0}/{1}/{2}.resx", moduleConfiguration.DesktopModule.FolderName, Localization.LocalResourceDirectory, diff --git a/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs b/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs index 628ce56419e..8efa7c444cd 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/MvcSettingsControl.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Web.Mvc public class MvcSettingsControl : MvcHostControl, ISettingsControl { - public MvcSettingsControl() + public MvcSettingsControl() : base("Settings") { this.ExecuteModuleImmediately = false; diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs index f6a4a16feeb..30fbd7a670b 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/HttpRequestExtensions.cs @@ -19,7 +19,7 @@ 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); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs index a7b5c913f6b..1d54efe02e5 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/IPortalAliasMvcRouteManager.cs @@ -16,15 +16,15 @@ namespace DotNetNuke.Web.Mvc.Routing internal interface IPortalAliasMvcRouteManager { IEnumerable GetRoutePrefixCounts(); - + string GetRouteName(string moduleFolderName, string routeName, int count); - + string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias); - + RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues); - + string GetRouteUrl(string moduleFolderName, string url, int count); - + void ClearCachedData(); } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs index 24678e46e6f..d4e7f845aa7 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRouteExtensions.cs @@ -15,7 +15,7 @@ public static class MvcRouteExtensions { private const string NamespaceKey = "namespaces"; private const string NameKey = "name"; - + /// /// Get the name of the route. /// diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs index e7cda2d1251..7ef0f8c5d58 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/MvcRoutingManager.cs @@ -23,7 +23,7 @@ public sealed class MvcRoutingManager : IMapRoute private readonly RouteCollection _routes; private readonly PortalAliasMvcRouteManager _portalAliasMvcRouteManager; - public MvcRoutingManager() + public MvcRoutingManager() : this(RouteTable.Routes) { } @@ -35,8 +35,8 @@ internal MvcRoutingManager(RouteCollection routes) this.TypeLocator = new TypeLocator(); } - internal ITypeLocator TypeLocator { get; set; } - + internal ITypeLocator TypeLocator { get; set; } + public Route MapRoute(string moduleFolderName, string routeName, string url, string[] namespaces) { return this.MapRoute(moduleFolderName, routeName, url, null /* defaults */, null /* constraints */, namespaces); @@ -51,7 +51,7 @@ public Route MapRoute(string moduleFolderName, string routeName, string url, obj { if (namespaces == null || namespaces.Length == 0 || string.IsNullOrEmpty(namespaces[0])) { - throw new ArgumentException(Localization.GetExceptionMessage( + throw new ArgumentException(Localization.GetExceptionMessage( "ArgumentCannotBeNullOrEmpty", "The argument '{0}' cannot be null or empty.", "namespaces")); @@ -64,11 +64,11 @@ public Route MapRoute(string moduleFolderName, string routeName, string url, obj var prefixCounts = this._portalAliasMvcRouteManager.GetRoutePrefixCounts(); Route route = null; - if (url == null) - { - throw new ArgumentNullException(nameof(url)); - } - + if (url == null) + { + throw new ArgumentNullException(nameof(url)); + } + foreach (var count in prefixCounts) { var fullRouteName = this._portalAliasMvcRouteManager.GetRouteName(moduleFolderName, routeName, count); @@ -79,8 +79,8 @@ public Route MapRoute(string moduleFolderName, string routeName, string url, obj } return route; - } - + } + public void RegisterRoutes() { // add standard tab and module id provider @@ -90,7 +90,7 @@ public void RegisterRoutes() // _routes.Clear(); -- don't use; it will remove original WEP API maps this.LocateServicesAndMapRoutes(); } - + Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); } @@ -122,17 +122,23 @@ private static Route MapRouteWithNamespace(string name, string url, object defau { 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; + return dictionary != null ? new RouteValueDictionary(dictionary) : TypeHelper.ObjectToDictionary(values); + } + private void LocateServicesAndMapRoutes() { RegisterSystemRoutes(); @@ -187,11 +193,5 @@ private IEnumerable GetAllServiceRouteMapperTypes() { return this.TypeLocator.GetAllMatchingTypes(IsValidServiceRouteMapper); } - - private static RouteValueDictionary CreateRouteValueDictionaryUncached(object values) - { - var dictionary = values as IDictionary; - return dictionary != null ? new RouteValueDictionary(dictionary) : TypeHelper.ObjectToDictionary(values); - } } } diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs index 9212f6bb1cf..f7107f903ff 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/PortalAliasMvcRouteManager.cs @@ -40,7 +40,7 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia alias = alias.Remove(i, appPath.Length); } } - + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } @@ -50,11 +50,11 @@ public RouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, o var segments = portalAliasInfo.HTTPAlias.Split('/'); - if (segments.Length <= 1) - { - return allRouteValues; - } - + if (segments.Length <= 1) + { + return allRouteValues; + } + for (var i = 1; i < segments.Length; i++) { var key = "prefix" + (i - 1).ToString(CultureInfo.InvariantCulture); @@ -73,23 +73,6 @@ 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; @@ -97,37 +80,54 @@ public void ClearCachedData() public IEnumerable GetRoutePrefixCounts() { - if (this._prefixCounts != null) - { - return this._prefixCounts; - } - - // prefixCounts are required for each route that is mapped but they only change - // when a new portal is added so cache them until that time + if (this._prefixCounts != null) + { + return this._prefixCounts; + } + + // prefixCounts are required for each route that is mapped but they only change + // when a new portal is added so cache them until that time var portals = PortalController.Instance.GetPortals(); var segmentCounts1 = new List(); foreach ( var count in - portals.Cast() - .Select( - portal => - PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID) - .Select(x => x.HTTPAlias)) - .Select(this.StripApplicationPath) - .SelectMany( - aliases => - aliases.Select(CalcAliasPrefixCount).Where(count => !segmentCounts1.Contains(count)))) + portals.Cast() + .Select( + portal => + PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID) + .Select(x => x.HTTPAlias)) + .Select(this.StripApplicationPath) + .SelectMany( + aliases => + aliases.Select(CalcAliasPrefixCount).Where(count => !segmentCounts1.Contains(count)))) { segmentCounts1.Add(count); } - + IEnumerable segmentCounts = segmentCounts1; this._prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); return this._prefixCounts; } + 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; + } + private static int CalcAliasPrefixCount(string alias) { return alias.Count(c => c == '/'); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs index d814f713543..f9a4d4c40cc 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/Routing/StandardModuleRoutingProvider.cs @@ -21,14 +21,14 @@ public class StandardModuleRoutingProvider : ModuleRoutingProvider { private const string ExcludedQueryStringParams = "tabid,mid,ctl,language,popup,action,controller"; private const string ExcludedRouteValues = "mid,ctl,popup"; - + public StandardModuleRoutingProvider() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - + protected INavigationManager NavigationManager { get; } - + public override string GenerateUrl(RouteValueDictionary routeValues, ModuleInstanceContext moduleContext) { // Look for a module control @@ -88,7 +88,7 @@ public override RouteData GetRouteData(HttpContextBase httpContext, ModuleContro } } } - + if (!string.IsNullOrEmpty(routeNamespace)) { routeData.DataTokens.Add("namespaces", new string[] { routeNamespace }); diff --git a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs index 92940fb6b28..50daa947ded 100644 --- a/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web.Mvc/StandardTabAndModuleInfoProvider.cs @@ -18,11 +18,10 @@ public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { 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"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); public bool TryFindTabId(HttpRequestBase request, out int tabId) { diff --git a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs index 2904da99fde..49f043a3ae1 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs @@ -21,7 +21,7 @@ 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")] diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs index cca41cad8d8..2465b4d994a 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorEngine.cs @@ -47,6 +47,12 @@ 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 HttpContextBase HttpContext + { + get { return new HttpContextWrapper(System.Web.HttpContext.Current); } + } + [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected string RazorScriptFile { get; set; } @@ -56,12 +62,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")] - protected HttpContextBase HttpContext - { - get { return new HttpContextWrapper(System.Web.HttpContext.Current); } - } - [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public Type RequestedModelType() { diff --git a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs index 22effdb2320..81828e622bc 100644 --- a/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs +++ b/DNN Platform/DotNetNuke.Web.Razor/RazorHostControl.cs @@ -44,7 +44,7 @@ protected virtual string RazorScriptFile { get { return this._razorScriptFile; } } - + private RazorEngine Engine { get diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs index 09048d61bd5..4abc246d033 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/AuthMessageHandlerBase.cs @@ -25,11 +25,11 @@ protected AuthMessageHandlerBase(bool includeByDefault, bool forceSsl) } public abstract string AuthScheme { get; } - + public virtual bool BypassAntiForgeryToken => false; - + public bool DefaultInclude { get; } - + public bool ForceSsl { get; } /// @@ -54,18 +54,6 @@ public virtual HttpResponseMessage OnOutboundResponse(HttpResponseMessage respon return response; } - 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); - } - protected static bool IsXmlHttpRequest(HttpRequestMessage request) { string value = null; @@ -74,7 +62,7 @@ protected static bool IsXmlHttpRequest(HttpRequestMessage request) { value = values.FirstOrDefault(); } - + return !string.IsNullOrEmpty(value) && value.Equals("XmlHttpRequest", StringComparison.InvariantCultureIgnoreCase); } @@ -85,6 +73,18 @@ protected static void SetCurrentPrincipal(IPrincipal principal, HttpRequestMessa request.GetHttpContext().User = principal; } + 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); + } + protected bool NeedsAuthentication(HttpRequestMessage request) { if (this.MustEnforceSslInRequest(request)) diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs index 21b9b462621..cf4ccc5c87f 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/BasicAuthMessageHandler.cs @@ -25,7 +25,7 @@ public BasicAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } - + public override string AuthScheme => "Basic"; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) @@ -105,8 +105,8 @@ private UserCredentials GetCredentials(HttpRequestMessage request) } return new UserCredentials(parts[0], parts[1]); - } - + } + internal class UserCredentials { public UserCredentials(string userName, string password) @@ -116,8 +116,8 @@ public UserCredentials(string userName, string password) } public string Password { get; set; } - + public string UserName { get; set; } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs index d903da4cb50..f4ca58348fd 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Auth/DigestAuthMessageHandler.cs @@ -22,7 +22,7 @@ public DigestAuthMessageHandler(bool includeByDefault, bool forceSsl) : base(includeByDefault, forceSsl) { } - + public override string AuthScheme => DigestAuthentication.AuthenticationScheme; public override HttpResponseMessage OnInboundRequest(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs index e98ec9a7d49..a18f148d244 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthFilterBase.cs @@ -19,7 +19,7 @@ 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. /// diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs b/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs index a983167df84..681e6ac4a18 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthFilterContext.cs @@ -18,7 +18,7 @@ public AuthFilterContext(HttpActionContext actionContext, string authFailureMess } public HttpActionContext ActionContext { get; private set; } - + public string AuthFailureMessage { get; set; } /// diff --git a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs index 117d098c114..dad7e6a48c6 100644 --- a/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs +++ b/DNN Platform/DotNetNuke.Web/Api/AuthorizeAttributeBase.cs @@ -20,7 +20,7 @@ public static bool IsAnonymousAttributePresent(HttpActionContext actionContext) || (actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any() && actionContext.ActionDescriptor.GetCustomAttributes().All(t => t is SupportedModulesAttribute)); } - + /// /// Tests if the request passes the authorization requirements. /// diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs index f574289fb31..fd2db4a6e1d 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnApiController.cs @@ -35,16 +35,16 @@ public PortalSettings PortalSettings /// /// Gets userInfo for the current user. /// - public UserInfo UserInfo - { - get { return this.PortalSettings.UserInfo; } - } + public UserInfo UserInfo + { + get { return this.PortalSettings.UserInfo; } + } /// /// Gets moduleInfo for the current module. /// Will be null unless a valid pair of module and tab ids were provided in the request /// - public ModuleInfo ActiveModule + public ModuleInfo ActiveModule { get { return this._activeModule.Value; } } diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs index 81674351f8d..7600d6d67fd 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnAuthorizeAttribute.cs @@ -17,7 +17,7 @@ public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDef private static readonly List DefaultAuthTypes = new List(); private static readonly string[] EmptyArray = new string[0]; - + private string _staticRoles; private string[] _staticRolesSplit = new string[0]; @@ -33,7 +33,7 @@ public sealed class DnnAuthorizeAttribute : AuthorizeAttributeBase, IOverrideDef public string StaticRoles { get { return this._staticRoles; } - + set { this._staticRoles = value; @@ -47,7 +47,7 @@ public string StaticRoles public string DenyRoles { get { return this._denyRoles; } - + set { this._denyRoles = value; @@ -61,7 +61,7 @@ public string DenyRoles public string AuthTypes { get { return this._authTypes; } - + set { this._authTypes = value; @@ -69,14 +69,6 @@ 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); @@ -120,7 +112,15 @@ public override bool IsAuthorized(AuthFilterContext context) return true; } - + + internal static void AppendToDefaultAuthTypes(string authType) + { + if (!string.IsNullOrEmpty(authType)) + { + DefaultAuthTypes.Add(authType.Trim()); + } + } + private static string[] SplitString(string original) { if (string.IsNullOrEmpty(original)) diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs b/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs index 849eef08d7a..1a8961596d6 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnHttpControllerSelector.cs @@ -31,7 +31,7 @@ public DnnHttpControllerSelector(HttpConfiguration configuration) Requires.NotNull("configuration", configuration); this._configuration = configuration; - this._descriptorCache = new Lazy>( + this._descriptorCache = new Lazy>( this.InitTypeCache, isThreadSafe: true); } @@ -49,7 +49,7 @@ public HttpControllerDescriptor SelectController(HttpRequestMessage request) IEnumerable namespaces = this.GetNameSpaces(request); if (namespaces == null || !namespaces.Any() || string.IsNullOrEmpty(controllerName)) { - throw new HttpResponseException(request.CreateErrorResponse( + throw new HttpResponseException(request.CreateErrorResponse( HttpStatusCode.NotFound, "Unable to locate a controller for " + request.RequestUri)); diff --git a/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs index 4d89fb32c5f..59705d9c4e5 100644 --- a/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/DnnModuleAuthorizeAttribute.cs @@ -19,7 +19,7 @@ public DnnModuleAuthorizeAttribute() } public string PermissionKey { get; set; } - + public SecurityAccessLevel AccessLevel { get; set; } public override bool IsAuthorized(AuthFilterContext context) diff --git a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs index c6e558b6c2c..c1a279af4ca 100644 --- a/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/Api/HttpRequestMessageExtensions.cs @@ -13,7 +13,7 @@ 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); diff --git a/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs index 5e901ab8c67..e0e2da91161 100644 --- a/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/IPortalAliasRouteManager.cs @@ -13,15 +13,15 @@ namespace DotNetNuke.Web.Api internal interface IPortalAliasRouteManager { IEnumerable GetRoutePrefixCounts(); - + string GetRouteName(string moduleFolderName, string routeName, int count); - + string GetRouteName(string moduleFolderName, string routeName, PortalAliasInfo portalAlias); - + HttpRouteValueDictionary GetAllRouteValues(PortalAliasInfo portalAliasInfo, object routeValues); - + string GetRouteUrl(string moduleFolderName, string url, int count); - + void ClearCachedData(); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs index 6d1cbf993e7..f061ddd0a7b 100644 --- a/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/ITabAndModuleInfoProvider.cs @@ -11,9 +11,9 @@ namespace DotNetNuke.Web.Api public interface ITabAndModuleInfoProvider { bool TryFindTabId(HttpRequestMessage request, out int tabId); - + bool TryFindModuleId(HttpRequestMessage request, out int moduleId); - + bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleInfo); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs index e63b954e8c6..fca926303b5 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/AntiForgeryImpl.cs @@ -6,11 +6,11 @@ namespace DotNetNuke.Web.Api.Internal { internal class AntiForgeryImpl : IAntiForgery { - public string CookieName - { - get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } - } - + public string CookieName + { + get { return System.Web.Helpers.AntiForgeryConfig.CookieName; } + } + public void Validate(string cookieToken, string headerToken) { System.Web.Helpers.AntiForgery.Validate(cookieToken, headerToken); diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs index 38e05f87b8b..e865e35876c 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthentication.cs @@ -16,10 +16,10 @@ internal class DigestAuthentication { internal const string AuthenticationScheme = "Digest"; private static readonly MD5 Md5 = new MD5CryptoServiceProvider(); - private DigestAuthenticationRequest _request; - private string _password; private readonly int _portalId; private readonly string _ipAddress; + private DigestAuthenticationRequest _request; + private string _password; public DigestAuthentication(DigestAuthenticationRequest request, int portalId, string ipAddress) { @@ -56,7 +56,7 @@ private static string CreateMd5HashBinHex(string val) { ha1 += string.Format("{0:x02}", bha1[i]); } - + return ha1; } @@ -70,7 +70,7 @@ private static bool IsNonceValid(string nonce) { numPadChars = 4 - numPadChars; } - + string newNonce = nonce.PadRight(nonce.Length + numPadChars, '='); try @@ -93,7 +93,7 @@ private void AuthenticateRequest() if (this._password != null) { 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()) { @@ -110,12 +110,12 @@ private string GetPassword(DigestAuthenticationRequest request) { user = UserController.GetUserByName(this._portalId, request.RawUsername); } - + if (user == null) { return null; } - + var password = UserController.GetPassword(ref user, string.Empty); // Try to validate user @@ -143,7 +143,7 @@ private string GenerateUnhashedDigest() { unhashedDigest = string.Format("{0}:{1}:{2}", ha1, this._request.RequestParams["nonce"], ha2); } - + // Services.Logging.LoggingController.SimpleLog(A1, HA1, A2, HA2, unhashedDigest) return unhashedDigest; } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs index cd85037e860..240ae63fafb 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/Auth/DigestAuthenticationRequest.cs @@ -31,7 +31,7 @@ public DigestAuthenticationRequest(string authorizationHeader, string httpMethod { this.RequestParams.Add(m.Groups["name"].Value, m.Groups["value"].Value); } - + this.HttpMethod = httpMethod; this.RawUsername = this.RequestParams["username"].Replace("\\\\", "\\"); this.CleanUsername = this.RawUsername; diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs index 836bfb04daf..5971dffc1d6 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnDependencyResolver.cs @@ -18,9 +18,9 @@ namespace DotNetNuke.Web.Api.Internal /// internal class DnnDependencyResolver : IDependencyResolver { - private readonly IServiceProvider _serviceProvider; - - /// + private readonly IServiceProvider _serviceProvider; + + /// /// Initializes a new instance of the class. /// Instantiate a new instance of the . /// diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs index a1a7b2cf4fc..27082be52d0 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPageEditorAttribute.cs @@ -36,7 +36,7 @@ private bool IsModuleAdmin(PortalSettings portalSettings) } } } - + return portalSettings.ControlPanelSecurity == PortalSettings.ControlPanelPermission.ModuleEditor && isModuleAdmin; } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs index 209f1860604..f3f59ac9b0c 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/DnnPagePermissionAttribute.cs @@ -16,13 +16,13 @@ public string PermissionKey { return this.permissionKey; } - + set { this.permissionKey = value; } } - + public override bool IsAuthorized(AuthFilterContext context) { Requires.NotNull("context", context); diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs index b1ff41c55fc..534da3db695 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/IAntiForgery.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.Api.Internal public interface IAntiForgery { string CookieName { get; } - + void Validate(string cookieToken, string headerToken); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs index ca1401c9b54..1186c7419dc 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/IFrameSupportedValidateAntiForgeryTokenAttribute.cs @@ -13,11 +13,11 @@ public class IFrameSupportedValidateAntiForgeryTokenAttribute : ValidateAntiForg protected override Tuple IsAuthorized(HttpActionContext actionContext) { var result = base.IsAuthorized(actionContext); - if (result.Item1) - { - return SuccessResult; - } - + if (result.Item1) + { + return SuccessResult; + } + try { var queryString = actionContext.Request.GetQueryNameValuePairs(); @@ -30,7 +30,7 @@ protected override Tuple IsAuthorized(HttpActionContext actionCont break; } } - + var cookieValue = GetAntiForgeryCookieValue(actionContext); AntiForgery.Instance.Validate(cookieValue, token); diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs index 7ec1cc9a4bb..b050e870d28 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/PagePermissionsAttributesHelper.cs @@ -23,11 +23,11 @@ public static bool HasTabPermission(string permissionKey) var currentPortal = PortalController.Instance.GetCurrentPortalSettings(); bool isAdminUser = currentPortal.UserInfo.IsSuperUser || PortalSecurity.IsInRole(currentPortal.AdministratorRoleName); - if (isAdminUser) - { - return true; - } - + if (isAdminUser) + { + return true; + } + return TabPermissionController.HasTabPermission(permissionKey); } } diff --git a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs index a9b9ec69f9e..0b5c7fe9295 100644 --- a/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/Internal/ServicesRoutingManager.cs @@ -30,7 +30,7 @@ public sealed class ServicesRoutingManager : IMapRoute private readonly RouteCollection _routes; private readonly PortalAliasRouteManager _portalAliasRouteManager; - public ServicesRoutingManager() + public ServicesRoutingManager() : this(RouteTable.Routes) { } @@ -42,13 +42,13 @@ internal ServicesRoutingManager(RouteCollection routes) this.TypeLocator = new TypeLocator(); } - internal ITypeLocator TypeLocator { get; set; } - + internal ITypeLocator TypeLocator { get; set; } + public IList MapHttpRoute(string moduleFolderName, string routeName, string url, object defaults, object constraints, string[] namespaces) { if (namespaces == null || namespaces.Length == 0 || string.IsNullOrEmpty(namespaces[0])) { - throw new ArgumentException(Localization.GetExceptionMessage( + throw new ArgumentException(Localization.GetExceptionMessage( "ArgumentCannotBeNullOrEmpty", "The argument '{0}' cannot be null or empty.", "namespaces")); @@ -67,20 +67,20 @@ public IList MapHttpRoute(string moduleFolderName, string routeName, stri string routeUrl = this._portalAliasRouteManager.GetRouteUrl(moduleFolderName, url, count); Route route = this.MapHttpRouteWithNamespace(fullRouteName, routeUrl, defaults, constraints, namespaces); routes.Add(route); - if (Logger.IsTraceEnabled) - { - Logger.Trace("Mapping route: " + fullRouteName + " @ " + routeUrl); - } - - // compatible with old service path: DesktopModules/{namespace}/API/{controller}/{action}. + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mapping route: " + fullRouteName + " @ " + routeUrl); + } + + // compatible with old service path: DesktopModules/{namespace}/API/{controller}/{action}. var oldRouteName = $"{fullRouteName}-old"; var oldRouteUrl = PortalAliasRouteManager.GetOldRouteUrl(moduleFolderName, url, count); var oldRoute = this.MapHttpRouteWithNamespace(oldRouteName, oldRouteUrl, defaults, constraints, namespaces); routes.Add(oldRoute); - if (Logger.IsTraceEnabled) - { - Logger.Trace("Mapping route: " + oldRouteName + " @ " + oldRouteUrl); - } + if (Logger.IsTraceEnabled) + { + Logger.Trace("Mapping route: " + oldRouteName + " @ " + oldRouteUrl); + } } return routes; @@ -94,8 +94,8 @@ public IList MapHttpRoute(string moduleFolderName, string routeName, stri public IList MapHttpRoute(string moduleFolderName, string routeName, string url, string[] namespaces) { return this.MapHttpRoute(moduleFolderName, routeName, url, null, null, namespaces); - } - + } + public void RegisterRoutes() { // register routes is ONLY called from within DNN application initialization @@ -110,12 +110,12 @@ public void RegisterRoutes() GlobalConfiguration.Configuration.MessageHandlers.Add(new DnnContextMessageHandler()); RegisterAuthenticationHandlers(); - + // this must run after all other auth message handlers var handler = new WebFormsAuthMessageHandler(); GlobalConfiguration.Configuration.MessageHandlers.Add(handler); DnnAuthorizeAttribute.AppendToDefaultAuthTypes(handler.AuthScheme); - + // Add Windows Authentication type to make API request works when windows authentication enabled. DnnAuthorizeAttribute.AppendToDefaultAuthTypes("Negotiate"); @@ -143,7 +143,7 @@ public void RegisterRoutes() this._routes.Clear(); this.LocateServicesAndMapRoutes(); } - + Logger.TraceFormat("Registered a total of {0} routes", this._routes.Count); } @@ -156,11 +156,11 @@ private static void RegisterAuthenticationHandlers() { // authentication message handlers from web.config file var authSvcCfg = AuthServicesConfiguration.GetConfig(); - if (authSvcCfg?.MessageHandlers == null || authSvcCfg.MessageHandlers.Count <= 0) - { - return; - } - + if (authSvcCfg?.MessageHandlers == null || authSvcCfg.MessageHandlers.Count <= 0) + { + return; + } + var registeredSchemes = new List(); foreach (var handlerEntry in authSvcCfg.MessageHandlers.Cast()) { @@ -194,7 +194,7 @@ private static void RegisterAuthenticationHandlers() { DnnAuthorizeAttribute.AppendToDefaultAuthTypes(handler.AuthScheme); } - + if (handler.BypassAntiForgeryToken) { ValidateAntiForgeryTokenAttribute.AppendToBypassAuthTypes(handler.AuthScheme); diff --git a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs index 85135b250c2..625e6875207 100644 --- a/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.cs +++ b/DNN Platform/DotNetNuke.Web/Api/PortalAliasRouteManager.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 DotNetNuke.Web.Api { using System; @@ -49,7 +48,7 @@ public string GetRouteName(string moduleFolderName, string routeName, PortalAlia alias = alias.Remove(i, appPath.Length); } } - + return this.GetRouteName(moduleFolderName, routeName, CalcAliasPrefixCount(alias)); } @@ -60,12 +59,12 @@ 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); } } @@ -80,23 +79,6 @@ public string GetRouteUrl(string moduleFolderName, string url, int count) return string.Format("{0}API/{1}/{2}", this.GeneratePrefixString(count), moduleFolderName, url); } - 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 void ClearCachedData() { this._prefixCounts = null; @@ -109,7 +91,7 @@ public IEnumerable GetRoutePrefixCounts() // prefixCounts are required for each route that is mapped but they only change // when a new portal is added so cache them until that time var portals = PortalController.Instance.GetPortals(); - + var segmentCounts1 = new List(); foreach (PortalInfo portal in portals) @@ -128,7 +110,7 @@ public IEnumerable GetRoutePrefixCounts() } } } - + IEnumerable segmentCounts = segmentCounts1; this._prefixCounts = segmentCounts.OrderByDescending(x => x).ToList(); } @@ -169,5 +151,22 @@ private IEnumerable StripApplicationPath(IEnumerable aliases) return StripApplicationPathIterable(aliases, appPath); } + + 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; + } } } diff --git a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs index 8425baf70a0..dc48b267d99 100644 --- a/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Api/StandardTabAndModuleInfoProvider.cs @@ -18,12 +18,12 @@ public sealed class StandardTabAndModuleInfoProvider : ITabAndModuleInfoProvider { 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"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardTabAndModuleInfoProvider)); + public bool TryFindTabId(HttpRequestMessage request, out int tabId) { return TryFindTabId(request, out tabId, true); @@ -40,11 +40,11 @@ public bool TryFindModuleInfo(HttpRequestMessage request, out ModuleInfo moduleI 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; - } - + if (moduleInfo != null && moduleInfo.IsDeleted) + { + moduleInfo = null; + } + return moduleInfo != null; } @@ -121,11 +121,11 @@ private static bool TryFindByMoniker(HttpRequestMessage requestMessage, out Modu } moduleInfo = id > Null.NullInteger ? ModuleController.Instance.GetTabModule(id) : null; - if (moduleInfo != null && moduleInfo.IsDeleted) - { - moduleInfo = null; - } - + if (moduleInfo != null && moduleInfo.IsDeleted) + { + moduleInfo = null; + } + return moduleInfo != null; } diff --git a/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs b/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs index bcba5c5e20f..f0e84f47d51 100644 --- a/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs +++ b/DNN Platform/DotNetNuke.Web/Api/StringPassThroughMediaTypeFormatter.cs @@ -16,17 +16,17 @@ namespace DotNetNuke.Web.Api /// A MediaTypeFormatter that simply allows strings to pass through WebAPI and be associated with the specified MIME type. /// public class StringPassThroughMediaTypeFormatter : MediaTypeFormatter - { - /// + { + /// /// Initializes a new instance of the class. /// Initialize a formatter that can handle text/plain and text/html. /// - public StringPassThroughMediaTypeFormatter() - : this(new[] { "text/plain", "text/html" }) - { - } - - /// + public StringPassThroughMediaTypeFormatter() + : this(new[] { "text/plain", "text/html" }) + { + } + + /// /// Initializes a new instance of the class. /// Initialize a formatter that can handle the specified media types. /// diff --git a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs index 2888c0df2eb..799d309b425 100644 --- a/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs +++ b/DNN Platform/DotNetNuke.Web/Api/ValidateAntiForgeryTokenAttribute.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Web.Api public class ValidateAntiForgeryTokenAttribute : ActionFilterAttribute { protected static Tuple SuccessResult = new Tuple(true, null); - + private static readonly List BypassedAuthTypes = new List(); public override bool AllowMultiple => false; @@ -76,11 +76,11 @@ protected virtual Tuple IsAuthorized(HttpActionContext actionConte token = values.FirstOrDefault(); } - if (string.IsNullOrEmpty(token)) - { - return new Tuple(false, "RequestVerificationToken not present"); - } - + if (string.IsNullOrEmpty(token)) + { + return new Tuple(false, "RequestVerificationToken not present"); + } + var cookieValue = GetAntiForgeryCookieValue(actionContext); AntiForgery.Instance.Validate(cookieValue, token); } diff --git a/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs b/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs index 9a9d559ccce..5acc4e0abd0 100644 --- a/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs +++ b/DNN Platform/DotNetNuke.Web/Api/WebApiException.cs @@ -14,8 +14,8 @@ namespace DotNetNuke.Web.Api /// Represents a non successful response while executing a WebApi call. /// public class WebApiException : Exception - { - /// + { + /// /// Initializes a new instance of the class, with the specified inner exception and response. /// message that caused the exception. /// @@ -34,14 +34,14 @@ public WebApiException(Exception innerException, HttpResponseMessage result, str } /// - /// Gets the result of the request. Can be used to retrieve additional info like HTTP status code. + /// Gets body from the Get Response. Available when exception is thrown as well. /// - public HttpResponseMessage Result { get; private set; } + public string Body { get; } /// - /// Gets body from the Get Response. Available when exception is thrown as well. + /// Gets the result of the request. Can be used to retrieve additional info like HTTP status code. /// - public string Body { get; } + public HttpResponseMessage Result { get; private set; } public dynamic BodyAsJson() { diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs index 54c2525279c..fe5ef2745e7 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeHttpApplication.cs @@ -49,8 +49,8 @@ public class DotNetNukeHttpApplication : HttpApplication ".css", ".gif", ".jpeg", ".jpg", ".js", ".png", "scriptresource.axd", "webresource.axd", }; - private static void RegisterIfNotAlreadyRegistered() - where TConcrete : class, new() + private static void RegisterIfNotAlreadyRegistered() + where TConcrete : class, new() { RegisterIfNotAlreadyRegistered(string.Empty); } @@ -73,6 +73,18 @@ private static void RegisterIfNotAlreadyRegistered(string } } + 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"); + } + private void Application_Error(object sender, EventArgs eventArgs) { // Code that runs when an unhandled error occurs @@ -80,11 +92,11 @@ private void Application_Error(object sender, EventArgs eventArgs) { // Get the exception object. Logger.Trace("Dumping all Application Errors"); - foreach (Exception exc in HttpContext.Current.AllErrors) - { - Logger.Fatal(exc); - } - + foreach (Exception exc in HttpContext.Current.AllErrors) + { + Logger.Fatal(exc); + } + Logger.Trace("End Dumping all Application Errors"); } } @@ -108,9 +120,9 @@ 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))); + ComponentFactory.InstallComponents(new ProviderInstaller("searchIndex", typeof(IndexingProvider), typeof(ModuleIndexer))); #pragma warning disable 0618 - ComponentFactory.InstallComponents(new ProviderInstaller("searchDataStore", typeof(SearchDataStoreProvider), typeof(SearchDataStore))); + 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))); @@ -136,20 +148,8 @@ private void Application_Start(object sender, EventArgs eventArgs) // register the assembly-lookup to correct the breaking rename in DNN 9.2 DotNetNuke.Services.Zip.SharpZipLibRedirect.RegisterSharpZipLibRedirect(); - - // DotNetNukeSecurity.Initialize(); - } - - 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"); + // DotNetNukeSecurity.Initialize(); } private void Application_End(object sender, EventArgs eventArgs) @@ -179,24 +179,24 @@ private void Application_End(object sender, EventArgs eventArgs) { Logger.Trace("Disposing Lucene"); var lucene = LuceneController.Instance as IDisposable; - if (lucene != null) - { - lucene.Dispose(); - } + if (lucene != null) + { + lucene.Dispose(); + } } - + Logger.Trace("Dumping all Application Errors"); if (HttpContext.Current != null) { if (HttpContext.Current.AllErrors != null) { - foreach (Exception exc in HttpContext.Current.AllErrors) - { - Logger.Fatal(exc); - } + foreach (Exception exc in HttpContext.Current.AllErrors) + { + Logger.Fatal(exc); + } } } - + Logger.Trace("End Dumping all Application Errors"); Logger.Info("Application Ended"); } diff --git a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs index 2b40ce524c1..f3b9ca4f8ea 100644 --- a/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs +++ b/DNN Platform/DotNetNuke.Web/Common/DotNetNukeShutdownOverload.cs @@ -36,7 +36,7 @@ internal static void InitializeFcnSettings() if (fileChangesMonitor == null) { Logger.Info("fileChangesMonitor is null"); - + // AddSiteFilesMonitoring(true); } else @@ -49,12 +49,12 @@ internal static void InitializeFcnSettings() Logger.Info("FCNMode = " + fcnVal + " (Modes: NotSet/Default=0, Disabled=1, Single=2)"); var dirMonCompletion = typeof(HttpRuntime).Assembly.GetType("System.Web.DirMonCompletion"); - var dirMonCount = (int)dirMonCompletion.InvokeMember( + var dirMonCount = (int)dirMonCompletion.InvokeMember( "_activeDirMonCompletions", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null); Logger.Trace("DirMonCompletion count: " + dirMonCount); - + // enable our monitor only when fcnMode="Disabled" // AddSiteFilesMonitoring(fcnVal.ToString() == "1"); } @@ -79,11 +79,11 @@ private static void AddSiteFilesMonitoring(bool handleShutdowns) try { _handleShutdowns = handleShutdowns; - if (_handleShutdowns) - { - _shutDownDelayTimer = new Timer(InitiateShutdown); - } - + if (_handleShutdowns) + { + _shutDownDelayTimer = new Timer(InitiateShutdown); + } + _binFolder = Path.Combine(Globals.ApplicationMapPath, "bin").ToLowerInvariant(); _binOrRootWatcher = new FileSystemWatcher { @@ -114,11 +114,11 @@ private static void AddSiteFilesMonitoring(bool handleShutdowns) private static void InitiateShutdown(object state) { - if (!_handleShutdowns) - { - return; - } - + if (!_handleShutdowns) + { + return; + } + try { HttpRuntime.UnloadAppDomain(); @@ -136,7 +136,7 @@ private static void ShceduleShutdown() if (_handleShutdowns && !_shutdownInprogress) { _shutdownInprogress = true; - + // delay for a very short period _shutDownDelayTimer.Change(1500, Timeout.Infinite); } @@ -144,11 +144,11 @@ private static void ShceduleShutdown() private static void WatcherOnChanged(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - { - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - } - + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) { ShceduleShutdown(); @@ -157,49 +157,49 @@ private static void WatcherOnChanged(object sender, FileSystemEventArgs e) private static void WatcherOnCreated(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - { - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - } - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - { - ShceduleShutdown(); - } + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnRenamed(object sender, RenamedEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - { - Logger.Info($"Watcher Activity: {e.ChangeType}. New Path: {e.FullPath}. Old Path: {e.OldFullPath}"); - } - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - { - ShceduleShutdown(); - } + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. New Path: {e.FullPath}. Old Path: {e.OldFullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnDeleted(object sender, FileSystemEventArgs e) { - if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) - { - Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); - } - - if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) - { - ShceduleShutdown(); - } + if (Logger.IsInfoEnabled && !e.FullPath.EndsWith(".log.resources")) + { + Logger.Info($"Watcher Activity: {e.ChangeType}. Path: {e.FullPath}"); + } + + if (_handleShutdowns && !_shutdownInprogress && (e.FullPath ?? string.Empty).StartsWith(_binFolder, StringComparison.InvariantCultureIgnoreCase)) + { + ShceduleShutdown(); + } } private static void WatcherOnError(object sender, ErrorEventArgs e) { - if (Logger.IsInfoEnabled) - { - Logger.Info("Watcher Activity: N/A. Error: " + e.GetException()); - } + if (Logger.IsInfoEnabled) + { + Logger.Info("Watcher Activity: N/A. Error: " + e.GetException()); + } } } } diff --git a/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs b/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs index 32182b59d0c..9c65cea9926 100644 --- a/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs +++ b/DNN Platform/DotNetNuke.Web/Common/LazyServiceProvider.cs @@ -16,11 +16,11 @@ public class LazyServiceProvider : IServiceProvider public object GetService(Type serviceType) { - if (this._serviceProvider is null) - { - throw new Exception("Cannot resolve services until the service provider is built."); - } - + if (this._serviceProvider is null) + { + throw new Exception("Cannot resolve services until the service provider is built."); + } + return this._serviceProvider.GetService(serviceType); } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs index 68954da3bb1..d56ea8683f4 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/ControlBarController.cs @@ -28,7 +28,7 @@ public ControlBarController() { this._mef = new ExtensionPointManager(); } - + public IEnumerable> GetCategoryDesktopModules(int portalId, string category, string searchTerm = "") { var formattedSearchTerm = string.IsNullOrEmpty(searchTerm) ? string.Empty : searchTerm.ToLower(CultureInfo.InvariantCulture); @@ -74,7 +74,7 @@ public string GetBookmarkCategory(int portalId) PortalController.UpdatePortalSetting(portalId, BookmarkCategoryProperty, "Common"); return "Common"; } - + return bookmarkCategory; } @@ -144,7 +144,7 @@ private IEnumerable> GetBookmarked { return new List>(); } - + var bookmarkItemsKeys = bookmarkItems.ToString().Split(',').ToList(); var bookmarkedModules = DesktopModuleController.GetPortalDesktopModules(PortalSettings.Current.PortalId) .Where(dm => bookmarkItemsKeys.Contains(dm.Value.DesktopModuleID.ToString(CultureInfo.InvariantCulture))); diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs index 02bb3d69ac3..03a784b26c6 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/IControlBarController.cs @@ -19,7 +19,7 @@ public interface IControlBarController /// Catenory name. /// Search term to filter modules. /// A list with all matched desktop modules. - IEnumerable> GetCategoryDesktopModules( + IEnumerable> GetCategoryDesktopModules( int portalId, string category, string searchTerm = ""); diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs index 9078a4b5665..29f822954d8 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/MenuItemViewModel.cs @@ -12,11 +12,11 @@ namespace DotNetNuke.Web.Components.Controllers.Models public class MenuItemViewModel { public string ID { get; set; } - + public string Text { get; set; } - + public string Source { get; set; } - + public int Order { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs index 18f9ec94d55..6594081cd75 100644 --- a/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs +++ b/DNN Platform/DotNetNuke.Web/Components/Controllers/Models/UpgradeIndicatorViewModel.cs @@ -7,15 +7,15 @@ namespace DotNetNuke.Web.Components.Controllers.Models public class UpgradeIndicatorViewModel { public string ID { get; set; } - + public string ImageUrl { get; set; } - + public string WebAction { get; set; } - + public string AltText { get; set; } - + public string ToolTip { get; set; } - + public string CssClass { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs index 7b91872deb4..f3452f63c67 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/AuthServicesConfiguration.cs @@ -10,7 +10,7 @@ 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; diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs index 5d51590ac9a..8f88fe61c97 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlerEntry.cs @@ -17,7 +17,7 @@ public class MessageHandlerEntry : ConfigurationElement private const string ForceSslTag = "forceSSL"; [ConfigurationProperty(NameTag, DefaultValue = "", IsRequired = true)] - + // [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public string Name { @@ -25,7 +25,7 @@ public string Name { return (string)this[NameTag]; } - + set { this[NameTag] = value; @@ -33,7 +33,7 @@ public string Name } [ConfigurationProperty(ClassNameTag, DefaultValue = "", IsRequired = true)] - + // [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 300)] public string ClassName { @@ -41,7 +41,7 @@ public string ClassName { return (string)this[ClassNameTag]; } - + set { this[ClassNameTag] = value; @@ -56,7 +56,7 @@ public bool Enabled var b = (bool?)this[EnabledNameTag]; return b.Value; } - + set { this[EnabledNameTag] = value; @@ -74,7 +74,7 @@ public bool DefaultInclude var b = (bool?)this[DefaultIncludeTag]; return b.Value; } - + set { this[DefaultIncludeTag] = value; @@ -89,7 +89,7 @@ public bool ForceSsl var b = (bool?)this[ForceSslTag]; return b.Value; } - + set { this[ForceSslTag] = value; diff --git a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs index 11b22ed02b7..1844b17f2fd 100644 --- a/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs +++ b/DNN Platform/DotNetNuke.Web/ConfigSection/MessageHandlersCollection.cs @@ -14,14 +14,14 @@ public MessageHandlerEntry this[int index] { return this.BaseGet(index) as MessageHandlerEntry; } - + set { if (this.BaseGet(index) != null) { this.BaseRemoveAt(index); } - + this.BaseAdd(index, value); } } diff --git a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj index 71b441306e6..6b185aaf91d 100644 --- a/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj +++ b/DNN Platform/DotNetNuke.Web/DotNetNuke.Web.csproj @@ -260,9 +260,11 @@ + + diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs index 683e1283cb7..3d67aec328e 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ContentWorkflowServiceController.cs @@ -19,14 +19,14 @@ namespace DotNetNuke.Web.InternalServices [DnnAuthorize] public class ContentWorkflowServiceController : DnnApiController - { - private readonly IWorkflowEngine _workflowEngine; - + { + private readonly IWorkflowEngine _workflowEngine; + public ContentWorkflowServiceController() { this._workflowEngine = WorkflowEngine.Instance; - } - + } + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage Reject(NotificationDTO postData) @@ -43,12 +43,12 @@ 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); @@ -79,12 +79,12 @@ 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); @@ -146,6 +146,6 @@ public HttpResponseMessage Review(NotificationDTO postData) } return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs index 507a242c161..799e50a0562 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ControlBarController.cs @@ -46,7 +46,7 @@ public ControlBarController() { this.Controller = Components.Controllers.ControlBarController.Instance; } - + [HttpGet] [DnnPageEditor] public HttpResponseMessage GetPortalDesktopModules(string category, int loadingStartIndex, int loadingPageSize, string searchTerm, string excludeCategories = "", bool sortBookmarks = false, string topModule = "") @@ -55,7 +55,7 @@ public HttpResponseMessage GetPortalDesktopModules(string category, int loadingS { category = "All"; } - + var bookmarCategory = this.Controller.GetBookmarkCategory(PortalSettings.Current.PortalId); var bookmarkedModules = this.Controller.GetBookmarkedDesktopModules(PortalSettings.Current.PortalId, UserController.Instance.GetCurrentUserInfo().UserID, searchTerm); var bookmarkCategoryModules = this.Controller.GetCategoryDesktopModules(this.PortalSettings.PortalId, bookmarCategory, searchTerm); @@ -70,12 +70,12 @@ public HttpResponseMessage GetPortalDesktopModules(string category, int loadingS filteredList.Where(kvp => !excludeList.Contains(kvp.Value.DesktopModule.Category.ToLowerInvariant())); } - + if (sortBookmarks) { // sort bookmarked modules filteredList = bookmarkedModules.OrderBy(m => m.Key).Concat(filteredList.Except(bookmarkedModules)); - + // move Html on top filteredList = filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant()). Concat(filteredList.Except(filteredList.Where(m => m.Key.ToLowerInvariant() == topModule.ToLowerInvariant()))); @@ -158,74 +158,20 @@ public HttpResponseMessage GetTabModules(string tab) let imageUrl = this.GetTabModuleImage(tabID, kvp.Key) select new ModuleDefDTO { ModuleID = kvp.Key, ModuleName = kvp.Value, ModuleImage = imageUrl }); } - + return this.Request.CreateResponse(HttpStatusCode.OK, result); } return this.Request.CreateResponse(HttpStatusCode.InternalServerError); } - 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; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnPageEditor] public HttpResponseMessage CopyPermissionsToChildren() { if (TabPermissionController.CanManagePage() && UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators") - && this.ActiveTabHasChildren() && !this.PortalSettings.ActiveTab.IsSuperTab) + && this.ActiveTabHasChildren() && !this.PortalSettings.ActiveTab.IsSuperTab) { TabController.CopyPermissionsToChildren(this.PortalSettings.ActiveTab, this.PortalSettings.ActiveTab.TabPermissions); return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); @@ -259,10 +205,10 @@ public HttpResponseMessage AddModule(AddModuleDTO dto) try { sortID = int.Parse(dto.Sort); - if (sortID >= 0) - { - positionID = this.GetPaneModuleOrder(dto.Pane, sortID); - } + if (sortID >= 0) + { + positionID = this.GetPaneModuleOrder(dto.Pane, sortID); + } } catch (Exception exc) { @@ -336,18 +282,6 @@ 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] @@ -449,11 +383,11 @@ public HttpResponseMessage SwitchLanguage(SwitchLanguageDTO dto) [DnnPageEditor] public HttpResponseMessage ToggleUserMode(UserModeDTO userMode) { - if (userMode == null) - { - userMode = new UserModeDTO { UserMode = "VIEW" }; - } - + if (userMode == null) + { + userMode = new UserModeDTO { UserMode = "VIEW" }; + } + this.ToggleUserMode(userMode.UserMode); var response = this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); @@ -477,11 +411,11 @@ public HttpResponseMessage ToggleUserMode(UserModeDTO userMode) [DnnPageEditor] public HttpResponseMessage SaveBookmark(BookmarkDTO bookmark) { - if (string.IsNullOrEmpty(bookmark.Bookmark)) - { - bookmark.Bookmark = string.Empty; - } - + if (string.IsNullOrEmpty(bookmark.Bookmark)) + { + bookmark.Bookmark = string.Empty; + } + this.Controller.SaveBookMark(this.PortalSettings.PortalId, this.UserInfo.UserID, bookmark.Title, bookmark.Bookmark); return this.Request.CreateResponse(HttpStatusCode.OK, new { Success = true }); @@ -508,18 +442,30 @@ public HttpResponseMessage LockSite(LockingDTO lockingRequest) 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.SetData( Thread.GetNamedDataSlot("CloneModuleContext"), cloneModuleContext ? bool.TrueString : bool.FalseString); } + 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; + } + private void ToggleUserMode(string mode) { var personalizationController = new DotNetNuke.Services.Personalization.PersonalizationController(); @@ -529,18 +475,6 @@ 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; @@ -582,10 +516,10 @@ private string GetDeskTopModuleImage(int moduleId) var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); string imageUrl = - (from pkgs in packages - join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID - where portMods.Value.DesktopModuleID == moduleId - select pkgs.IconFile).FirstOrDefault(); + (from pkgs in packages + join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID + where portMods.Value.DesktopModuleID == moduleId + select pkgs.IconFile).FirstOrDefault(); imageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; return System.Web.VirtualPathUtility.ToAbsolute(imageUrl); @@ -599,11 +533,11 @@ private string GetTabModuleImage(int tabId, int moduleId) var packages = PackageController.Instance.GetExtensionPackages(PortalSettings.Current.PortalId); string imageUrl = (from pkgs in packages - join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID - join modDefs in moduleDefnitions on portMods.Value.DesktopModuleID equals modDefs.Value.DesktopModuleID - join tabMods in tabModules on modDefs.Value.DesktopModuleID equals tabMods.Value.DesktopModuleID - where tabMods.Value.ModuleID == moduleId - select pkgs.IconFile).FirstOrDefault(); + join portMods in portalDesktopModules on pkgs.PackageID equals portMods.Value.PackageID + join modDefs in moduleDefnitions on portMods.Value.DesktopModuleID equals modDefs.Value.DesktopModuleID + join tabMods in tabModules on modDefs.Value.DesktopModuleID equals tabMods.Value.DesktopModuleID + where tabMods.Value.ModuleID == moduleId + select pkgs.IconFile).FirstOrDefault(); imageUrl = string.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; return System.Web.VirtualPathUtility.ToAbsolute(imageUrl); @@ -632,7 +566,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po { userID = user.UserID; } - + if (moduleInfo != null) { // Is this from a site other than our own? (i.e., is the user requesting "module sharing"?) @@ -643,7 +577,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po { case ModuleSharing.Unsupported: // Should never happen since the module should not be listed in the first place. - throw new ApplicationException(string.Format( + throw new ApplicationException(string.Format( "Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", moduleInfo.DesktopModule.FriendlyName)); case ModuleSharing.Supported: @@ -725,7 +659,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po && originalTab.TabSettings.ContainsKey("CustomStylesheet") && !string.IsNullOrEmpty(originalTab.TabSettings["CustomStylesheet"].ToString()) && (!targetTab.TabSettings.ContainsKey("CustomStylesheet") || - string.IsNullOrEmpty(targetTab.TabSettings["CustomStylesheet"].ToString()))) + string.IsNullOrEmpty(targetTab.TabSettings["CustomStylesheet"].ToString()))) { TabController.Instance.UpdateTabSetting(targetTab.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); } @@ -735,7 +669,7 @@ private int DoAddExistingModule(int moduleId, int tabId, string paneName, int po // Ensure the Portal Admin has View rights var permissionController = new PermissionController(); ArrayList arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - this.AddModulePermission( + this.AddModulePermission( newModule, (PermissionInfo)arrSystemModuleViewPermissions[0], PortalSettings.Current.AdministratorRoleId, @@ -866,7 +800,7 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i if (PortalSettings.Current.ContentLocalizationEnabled) { Locale defaultLocale = LocaleController.Instance.GetDefaultLocale(PortalSettings.Current.PortalId); - + // set the culture of the module to that of the tab var tabInfo = TabController.Instance.GetTab(objModule.TabID, PortalSettings.Current.PortalId, false); objModule.CultureCode = tabInfo != null ? tabInfo.CultureCode : defaultLocale.Code; @@ -875,7 +809,7 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i { objModule.CultureCode = Null.NullString; } - + objModule.AllTabs = false; objModule.Alignment = align; @@ -885,7 +819,7 @@ private int DoAddNewModule(string title, int desktopModuleId, string paneName, i { tabModuleId = objModule.ModuleID; } - + // update the position to let later modules with add after previous one. position = ModuleController.Instance.GetTabModule(objModule.TabModuleID).ModuleOrder + 1; } @@ -897,15 +831,81 @@ private string GetModuleName(string moduleName) { if (this._nameDics == null) { - this._nameDics = new Dictionary - { + this._nameDics = new Dictionary + { { "SearchCrawlerAdmin", "SearchCrawler Admin" }, - { "SearchCrawlerInput", "SearchCrawler Input" }, - { "SearchCrawlerResults", "SearchCrawler Results" }, + { "SearchCrawlerInput", "SearchCrawler Input" }, + { "SearchCrawlerResults", "SearchCrawler Results" }, }; } return this._nameDics.ContainsKey(moduleName) ? this._nameDics[moduleName] : moduleName; } + + 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; } + } + + public class BookmarkDTO + { + public string Title { get; set; } + + public string Bookmark { get; set; } + } + + public class LockingDTO + { + public bool Lock { get; set; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs index 6ef33ae2874..1d824195df8 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/CountryRegionController.cs @@ -41,7 +41,7 @@ public HttpResponseMessage Regions(int country) Value = r.EntryID.ToString(), }); } - + return this.Request.CreateResponse(HttpStatusCode.OK, res.OrderBy(r => r.Text)); } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs index 26a28743727..0805dbe6806 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/EventLogServiceController.cs @@ -40,10 +40,10 @@ 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) @@ -71,7 +71,7 @@ private string GetPropertiesText(LogInfo logInfo) str.Append("

" + ldi.PropertyName + ":" + HttpUtility.HtmlEncode(ldi.PropertyValue) + "

"); } } - + str.Append("

Server Name: " + HttpUtility.HtmlEncode(logInfo.LogServerName) + "

"); return str.ToString(); } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs index 061ab8632dd..153a82eef58 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/FileUploadController.cs @@ -210,22 +210,6 @@ 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] @@ -354,18 +338,103 @@ public Task UploadFromLocal(int portalId) return task; } + [HttpPost] + [ValidateAntiForgeryToken] + [AllowAnonymous] + public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) + { + FileUploadDto result; + WebResponse response = null; + Stream responseStream = null; + var mediaTypeFormatter = new JsonMediaTypeFormatter(); + mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); + + if (this.VerifySafeUrl(dto.Url) == false) + { + return this.Request.CreateResponse(HttpStatusCode.BadRequest); + } + + try + { + var request = (HttpWebRequest)WebRequest.Create(dto.Url); + request.Credentials = CredentialCache.DefaultCredentials; + response = request.GetResponse(); + responseStream = response.GetResponseStream(); + if (responseStream == null) + { + throw new Exception("No server response"); + } + + var fileName = this.GetFileName(response); + if (string.IsNullOrEmpty(fileName)) + { + fileName = HttpUtility.UrlDecode(new Uri(dto.Url).Segments.Last()); + } + + var portalId = dto.PortalId; + if (portalId > -1) + { + if (!this.IsPortalIdValid(portalId)) + { + throw new HttpResponseException(HttpStatusCode.Unauthorized); + } + } + else + { + portalId = this.PortalSettings.PortalId; + } + + result = UploadFile(responseStream, portalId, this.UserInfo, dto.Folder.ValueOrEmpty(), dto.Filter.ValueOrEmpty(), + fileName, dto.Overwrite, dto.IsHostMenu, dto.Unzip, dto.ValidationCode); + + /* 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"); + } + catch (Exception ex) + { + result = new FileUploadDto + { + Message = ex.Message, + }; + return this.Request.CreateResponse( + HttpStatusCode.OK, + result, + mediaTypeFormatter, + "text/plain"); + } + finally + { + if (response != null) + { + response.Close(); + } + + if (responseStream != null) + { + responseStream.Close(); + } + } + } + private static SavedFileDTO SaveFile( - Stream stream, - PortalSettings portalSettings, - UserInfo userInfo, - string folder, - string filter, - string fileName, - bool overwrite, - bool isHostMenu, - bool extract, - out bool alreadyExists, - out string errorMessage) + Stream stream, + PortalSettings portalSettings, + UserInfo userInfo, + string folder, + string filter, + string fileName, + bool overwrite, + bool isHostMenu, + bool extract, + out bool alreadyExists, + out string errorMessage) { alreadyExists = false; var savedFileDto = new SavedFileDTO(); @@ -473,16 +542,16 @@ private static bool IsImage(string fileName) } private static FileUploadDto UploadFile( - Stream stream, - int portalId, - UserInfo userInfo, - string folder, - string filter, - string fileName, - bool overwrite, - bool isHostPortal, - bool extract, - string validationCode) + Stream stream, + int portalId, + UserInfo userInfo, + string folder, + string filter, + string fileName, + bool overwrite, + bool isHostPortal, + bool extract, + string validationCode) { var result = new FileUploadDto(); BinaryReader reader = null; @@ -549,8 +618,8 @@ private static FileUploadDto UploadFile( else { file = FileManager.Instance.AddFile(folderInfo, fileName, stream, true, false, - FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)), - userInfo.UserID); + FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)), + userInfo.UserID); if (extract && extension.ToLowerInvariant() == "zip") { var destinationFolder = FolderManager.Instance.GetFolder(file.FolderId); @@ -629,146 +698,14 @@ private static FileUploadDto UploadFile( } } - 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; } - } - - [HttpPost] - [ValidateAntiForgeryToken] - [AllowAnonymous] - public HttpResponseMessage UploadFromUrl(UploadByUrlDto dto) - { - FileUploadDto result; - WebResponse response = null; - Stream responseStream = null; - var mediaTypeFormatter = new JsonMediaTypeFormatter(); - mediaTypeFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain")); - - if (this.VerifySafeUrl(dto.Url) == false) - { - return this.Request.CreateResponse(HttpStatusCode.BadRequest); - } - - try - { - var request = (HttpWebRequest)WebRequest.Create(dto.Url); - request.Credentials = CredentialCache.DefaultCredentials; - response = request.GetResponse(); - responseStream = response.GetResponseStream(); - if (responseStream == null) - { - throw new Exception("No server response"); - } - - var fileName = this.GetFileName(response); - if (string.IsNullOrEmpty(fileName)) - { - fileName = HttpUtility.UrlDecode(new Uri(dto.Url).Segments.Last()); - } - - var portalId = dto.PortalId; - if (portalId > -1) - { - if (!this.IsPortalIdValid(portalId)) - { - throw new HttpResponseException(HttpStatusCode.Unauthorized); - } - } - else - { - portalId = this.PortalSettings.PortalId; - } - - result = UploadFile(responseStream, portalId, this.UserInfo, dto.Folder.ValueOrEmpty(), dto.Filter.ValueOrEmpty(), - fileName, dto.Overwrite, dto.IsHostMenu, dto.Unzip, dto.ValidationCode); - - /* 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"); - } - catch (Exception ex) - { - result = new FileUploadDto - { - Message = ex.Message, - }; - return this.Request.CreateResponse( - HttpStatusCode.OK, - result, - mediaTypeFormatter, - "text/plain"); - } - finally - { - if (response != null) - { - response.Close(); - } - - if (responseStream != null) - { - responseStream.Close(); - } - } - } - 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(); + select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + select portals.ToArray()).FirstOrDefault(); return mygroup; } @@ -841,5 +778,68 @@ private bool IsPortalIdValid(int portalId) var mygroup = GetMyPortalGroup(); return mygroup != null && mygroup.Any(p => p.PortalID == portalId); } + + 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; } + } + + 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; } + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs index ebcaafc66bc..2263d867e6a 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ImageHeader.cs @@ -28,7 +28,7 @@ public static class ImageHeader { new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, DecodePng }, { new byte[] { 0xff, 0xd8 }, DecodeJfif }, }; - + /// /// Gets the dimensions of an image. /// @@ -61,7 +61,7 @@ public static Size GetDimensions(string path) size = b.Size; } } - + return size; } @@ -86,7 +86,7 @@ public static Size GetDimensions(BinaryReader binaryReader) } } } - + throw new ArgumentException(ErrorMessage, "binaryReader"); } @@ -99,7 +99,7 @@ private static bool StartsWith(IList thisBytes, IList thatBytes) return false; } } - + return true; } @@ -110,7 +110,7 @@ private static short ReadLittleEndianInt16(BinaryReader binaryReader) { bytes[sizeof(short) - 1 - i] = binaryReader.ReadByte(); } - + return BitConverter.ToInt16(bytes, 0); } @@ -121,7 +121,7 @@ private static ushort ReadLittleEndianUInt16(BinaryReader binaryReader) { bytes[sizeof(ushort) - 1 - i] = binaryReader.ReadByte(); } - + return BitConverter.ToUInt16(bytes, 0); } @@ -132,7 +132,7 @@ private static int ReadLittleEndianInt32(BinaryReader binaryReader) { bytes[sizeof(int) - 1 - i] = binaryReader.ReadByte(); } - + return BitConverter.ToInt32(bytes, 0); } @@ -172,7 +172,7 @@ private static Size DecodeJfif(BinaryReader binaryReader) int width = ReadLittleEndianInt16(binaryReader); return new Size(width, height); } - + if (chunkLength < 0) { var uchunkLength = (ushort)chunkLength; @@ -183,7 +183,7 @@ private static Size DecodeJfif(BinaryReader binaryReader) binaryReader.ReadBytes(chunkLength - 2); } } - + throw new ArgumentException(ErrorMessage); } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs index 4a64f05bb8e..2006d30c816 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ItemListServiceController.cs @@ -32,10 +32,10 @@ namespace DotNetNuke.Web.InternalServices public class ItemListServiceController : DnnApiController { private const string PortalPrefix = "P-"; - private const string RootKey = "Root"; - + private const string RootKey = "Root"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ItemListServiceController)); - + [HttpGet] public HttpResponseMessage GetPageDescendants(string parentId = null, int sortOrder = 0, string searchText = "", int portalId = -1, bool includeDisabled = false, @@ -80,29 +80,6 @@ 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, @@ -113,7 +90,7 @@ public HttpResponseMessage SortPagesInPortalGroup(string treeAsJson, int sortOrd { Success = true, Tree = string.IsNullOrEmpty(searchText) ? this.SortPagesInPortalGroupInternal(treeAsJson, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles) - : this.SearchPagesInPortalGroupInternal(treeAsJson, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + : this.SearchPagesInPortalGroupInternal(treeAsJson, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), IgnoreRoot = true, }; return this.Request.CreateResponse(HttpStatusCode.OK, response); @@ -154,7 +131,7 @@ public HttpResponseMessage SearchPages(string searchText, int sortOrder = 0, int { Success = true, Tree = string.IsNullOrEmpty(searchText) ? this.GetPagesInternal(portalId, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles, false) - : this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + : this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), IgnoreRoot = true, }; return this.Request.CreateResponse(HttpStatusCode.OK, response); @@ -196,12 +173,12 @@ public HttpResponseMessage SearchPagesInPortalGroup(string searchText, int sortO { Success = true, Tree = string.IsNullOrEmpty(searchText) ? GetPagesInPortalGroupInternal(sortOrder) - : this.SearchPagesInPortalGroupInternal(searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), + : this.SearchPagesInPortalGroupInternal(searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles), IgnoreRoot = true, }; return this.Request.CreateResponse(HttpStatusCode.OK, response); - } - + } + [HttpGet] public HttpResponseMessage GetFolderDescendants(string parentId = null, int sortOrder = 0, string searchText = "", string permission = null, int portalId = -1) { @@ -259,8 +236,8 @@ public HttpResponseMessage SearchFolders(string searchText, int sortOrder = 0, s IgnoreRoot = true, }; return this.Request.CreateResponse(HttpStatusCode.OK, response); - } - + } + [HttpGet] public HttpResponseMessage GetFiles(int parentId, string filter, int sortOrder = 0, string permission = null, int portalId = -1) { @@ -295,7 +272,7 @@ public HttpResponseMessage SearchFiles(int parentId, string filter, string searc IgnoreRoot = true, }; return this.Request.CreateResponse(HttpStatusCode.OK, response); - } + } [HttpGet] public HttpResponseMessage SearchUser(string q) @@ -307,11 +284,11 @@ public HttpResponseMessage SearchUser(string q) // 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); - } - + 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 { @@ -327,8 +304,8 @@ public HttpResponseMessage SearchUser(string q) Logger.Error(exc); return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - } - + } + [HttpGet] public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTags) { @@ -339,24 +316,24 @@ public HttpResponseMessage GetTerms(string q, bool includeSystem, bool includeTa 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; + 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[] - { + 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 }, + 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) { @@ -383,7 +360,68 @@ private static IEnumerable GetChildrenOf(IEnumerable tabs, str id = int.TryParse(parentId, out id) ? id : Null.NullInteger; return GetChildrenOf(tabs, id); } - + + 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 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 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(); + return mygroup; + } + private NTree GetPagesInternal(int portalId, int sortOrder, bool includeDisabled = false, bool includeAllTypes = false, bool includeActive = false, bool includeHostPages = false, string roles = "", bool disabledNotSelectable = false) @@ -392,7 +430,7 @@ private NTree GetPagesInternal(int portalId, int sortOrder, bool includ { portalId = this.GetActivePortalId(); } - + var tabs = this.GetPortalPages(portalId, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); var sortedTree = new NTree { Data = new ItemDto { Key = RootKey } }; if (tabs == null) @@ -414,7 +452,7 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare { return null; } - + int portalId; int parentIdAsInt; if (parentId.StartsWith(PortalPrefix)) @@ -424,7 +462,7 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare { portalId = -1; } - + if (!string.IsNullOrEmpty(searchText)) { return this.SearchPagesInternal(portalId, searchText, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles).Children.Select(node => node.Data); @@ -438,7 +476,7 @@ private IEnumerable GetPageDescendantsInPortalGroupInternal(string pare parentIdAsInt = -1; } } - + return this.GetPageDescendantsInternal(portalId, parentIdAsInt, sortOrder, searchText, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } @@ -463,10 +501,10 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent } else { - if (!this.IsPortalIdValid(portalId)) - { - return new List(); - } + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } Func searchFunc; @@ -482,13 +520,13 @@ private IEnumerable GetPageDescendantsInternal(int portalId, int parent if (portalId > -1) { tabs = TabController.GetPortalTabs(portalId, includeActive ? Null.NullInteger : this.PortalSettings.ActiveTab.TabID, false, null, true, false, includeAllTypes, true, false) - .Where(tab => searchFunc(tab) - && tab.ParentId == parentId - && (includeDisabled || !tab.DisableLink) - && (includeAllTypes || tab.TabType == TabType.Normal) - && !tab.IsSystem) - .OrderBy(tab => tab.TabOrder) - .ToList(); + .Where(tab => searchFunc(tab) + && tab.ParentId == parentId + && (includeDisabled || !tab.DisableLink) + && (includeAllTypes || tab.TabType == TabType.Normal) + && !tab.IsSystem) + .OrderBy(tab => tab.TabOrder) + .ToList(); if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { @@ -558,11 +596,11 @@ private NTree SearchPagesInternal(int portalId, string searchText, int if (portalId > -1) { tabs = TabController.Instance.GetTabsByPortal(portalId).Where(tab => - (includeActive || tab.Value.TabID != this.PortalSettings.ActiveTab.TabID) - && (includeDisabled || !tab.Value.DisableLink) - && (includeAllTypes || tab.Value.TabType == TabType.Normal) - && searchFunc(tab.Value) - && !tab.Value.IsSystem) + (includeActive || tab.Value.TabID != this.PortalSettings.ActiveTab.TabID) + && (includeDisabled || !tab.Value.DisableLink) + && (includeAllTypes || tab.Value.TabType == TabType.Normal) + && searchFunc(tab.Value) + && !tab.Value.IsSystem) .OrderBy(tab => tab.Value.TabOrder) .Select(tab => tab.Value) .ToList(); @@ -570,9 +608,9 @@ private NTree SearchPagesInternal(int portalId, string searchText, int if (this.PortalSettings.UserInfo.IsSuperUser && includeHostPages) { tabs.AddRange(TabController.Instance.GetTabsByPortal(-1).Where(tab => !tab.Value.DisableLink && searchFunc(tab.Value) && !tab.Value.IsSystem) - .OrderBy(tab => tab.Value.TabOrder) - .Select(tab => tab.Value) - .ToList()); + .OrderBy(tab => tab.Value.TabOrder) + .Select(tab => tab.Value) + .ToList()); } } else @@ -580,9 +618,9 @@ private NTree SearchPagesInternal(int portalId, string searchText, int if (this.PortalSettings.UserInfo.IsSuperUser) { tabs = TabController.Instance.GetTabsByPortal(-1).Where(tab => !tab.Value.DisableLink && searchFunc(tab.Value) && !tab.Value.IsSystem) - .OrderBy(tab => tab.Value.TabOrder) - .Select(tab => tab.Value) - .ToList(); + .OrderBy(tab => tab.Value.TabOrder) + .Select(tab => tab.Value) + .ToList(); } else { @@ -622,11 +660,11 @@ 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(); - + { + 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()); @@ -643,56 +681,6 @@ private List GetPortalPages(int portalId, bool includeDisabled = false, return tabs; } - 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 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 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, bool includeHostPages = false, string roles = "") @@ -711,7 +699,7 @@ private NTree SortPagesInternal(int portalId, NTree openedNo { return sortedTree; } - + SortPagesRecursevely(pages, sortedTree, openedNodesTree, sortOrder); return sortedTree; } @@ -732,7 +720,7 @@ private NTree SearchPagesInPortalGroupInternal(string searchText, int s child.Children = pageTree.Children; } } - + return treeNode; } @@ -754,7 +742,7 @@ private NTree SearchPagesInPortalGroupInternal(string treeAsJson, strin { return treeNode; } - + foreach (var openedNodeChild in openedNode.Children) { var portalIdString = openedNodeChild.Data.Id; @@ -763,7 +751,7 @@ private NTree SearchPagesInPortalGroupInternal(string treeAsJson, strin { continue; } - + int portalId; if (int.TryParse(treeNodeChild.Data.Key.Replace(PortalPrefix, string.Empty), out portalId)) { @@ -771,7 +759,7 @@ private NTree SearchPagesInPortalGroupInternal(string treeAsJson, strin treeNodeChild.Children = pageTree.Children; } } - + return treeNode; } @@ -792,7 +780,7 @@ private NTree SortPagesInPortalGroupInternal(NTree openedNod { return treeNode; } - + var portals = GetPortalGroup(sortOrder); treeNode.Children = portals.Select(dto => new NTree { Data = dto }).ToList(); if (openedNode.HasChildren()) @@ -805,18 +793,18 @@ private NTree SortPagesInPortalGroupInternal(NTree openedNod { continue; } - + int portalId; if (!int.TryParse(portalIdString.Replace(PortalPrefix, string.Empty), out portalId)) { portalId = -1; } - + var treeOfPages = this.SortPagesInternal(portalId, openedNodeChild, sortOrder, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); treeNodeChild.Children = treeOfPages.Children; } } - + return treeNode; } @@ -829,7 +817,7 @@ private NTree GetTreePathForPageInternal(int portalId, string itemId, i { itemIdAsInt = Null.NullInteger; } - + return this.GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } @@ -843,7 +831,7 @@ private NTree GetTreePathForPageInternal(string itemId, int sortOrder, { return tree; } - + var portals = PortalController.GetPortalDictionary(); int portalId; if (portals.ContainsKey(itemIdAsInt)) @@ -854,7 +842,7 @@ private NTree GetTreePathForPageInternal(string itemId, int sortOrder, { return tree; } - + return this.GetTreePathForPageInternal(portalId, itemIdAsInt, sortOrder, includePortalTree, includeDisabled, includeAllTypes, includeActive, includeHostPages, roles); } @@ -971,10 +959,10 @@ private NTree GetTreePathForPageInternal(int portalId, int selectedItem break; } } - + rootTree = portalTree; } - + tree.Children = rootTree; return tree; @@ -989,9 +977,9 @@ private List FilterTabsByRole(IList tabs, string roles, bool disab filterTabs.AddRange( tabs.Where( - t => - t.TabPermissions.Cast() - .Any(p => roleList.Contains(p.RoleID) && p.UserID == Null.NullInteger && p.PermissionKey == "VIEW" && p.AllowAccess)).ToList() + t => + t.TabPermissions.Cast() + .Any(p => roleList.Contains(p.RoleID) && p.UserID == Null.NullInteger && p.PermissionKey == "VIEW" && p.AllowAccess)).ToList() .Where(t => !disabledNotSelectable || !t.DisableLink) .Select(t => t.TabID)); } @@ -1001,8 +989,8 @@ private List FilterTabsByRole(IList tabs, string roles, bool disab } return filterTabs; - } - + } + private NTree GetFoldersInternal(int portalId, int sortOrder, string permissions) { var tree = new NTree { Data = new ItemDto { Key = RootKey } }; @@ -1013,7 +1001,7 @@ private NTree GetFoldersInternal(int portalId, int sortOrder, string pe children = ApplySort(this.GetFolderDescendantsInternal(portalId, child.Data.Key, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); child.Children = children; } - + return tree; } @@ -1036,7 +1024,7 @@ private void SortFoldersRecursevely(int portalId, NTree treeNode, NTree { return; } - + var children = ApplySort(this.GetFolderDescendantsInternal(portalId, openedNode.Data.Id, sortOrder, string.Empty, permissions), sortOrder).Select(dto => new NTree { Data = dto }).ToList(); treeNode.Children = children; if (openedNode.HasChildren()) @@ -1048,7 +1036,7 @@ private void SortFoldersRecursevely(int portalId, NTree treeNode, NTree { continue; } - + this.SortFoldersRecursevely(portalId, treeNodeChild, openedNodeChild, sortOrder, permissions); } } @@ -1065,16 +1053,16 @@ private IEnumerable GetFolderDescendantsInternal(int portalId, int pare { if (portalId > -1) { - if (!this.IsPortalIdValid(portalId)) - { - return new List(); - } + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } else { portalId = this.GetActivePortalId(); } - + var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, string.Empty); if (parentFolder == null) @@ -1085,25 +1073,25 @@ private IEnumerable GetFolderDescendantsInternal(int portalId, int pare var hasPermission = string.IsNullOrEmpty(permission) ? (this.HasPermission(parentFolder, "BROWSE") || this.HasPermission(parentFolder, "READ")) : this.HasPermission(parentFolder, permission.ToUpper()); - if (!hasPermission) - { - return new List(); - } - - if (parentId < 1) - { - return new List - { - new ItemDto + if (!hasPermission) + { + return new List(); + } + + if (parentId < 1) + { + return new List { - Key = parentFolder.FolderID.ToString(CultureInfo.InvariantCulture), - Value = portalId == -1 ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder, - HasChildren = this.HasChildren(parentFolder, permission), - Selectable = true - }, - }; - } - + new ItemDto + { + Key = parentFolder.FolderID.ToString(CultureInfo.InvariantCulture), + Value = portalId == -1 ? DynamicSharedConstants.HostRootFolder : DynamicSharedConstants.RootFolder, + HasChildren = this.HasChildren(parentFolder, permission), + Selectable = true + }, + }; + } + var childrenFolders = this.GetFolderDescendants(parentFolder, searchText, permission); var folders = childrenFolders.Select(folder => new ItemDto @@ -1169,11 +1157,11 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s var hasPermission = string.IsNullOrEmpty(permission) ? (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : this.HasPermission(folder, permission.ToUpper()); - if (!hasPermission) - { - return new NTree(); - } - + if (!hasPermission) + { + return new NTree(); + } + var selfTree = new NTree { Data = new ItemDto @@ -1230,7 +1218,7 @@ private NTree GetTreePathForFolderInternal(string selectedItemId, int s parentId = parentFolder.ParentID; parentFolder = parentId > 0 ? FolderManager.Instance.GetFolder(parentId) : null; } - + selfTree.Data.Value = DynamicSharedConstants.RootFolder; tree.Children.Add(selfTree); @@ -1260,7 +1248,7 @@ private IEnumerable GetFolderDescendants(IFolderInfo parentFolder, { searchFunc = folder => folder.FolderName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1; } - + permission = string.IsNullOrEmpty(permission) ? null : permission.ToUpper(); return FolderManager.Instance.GetFolders(parentFolder).Where(folder => (string.IsNullOrEmpty(permission) ? @@ -1274,7 +1262,7 @@ private IEnumerable GetPortalFolders(int portalId, string searchTex { portalId = this.GetActivePortalId(); } - + Func searchFunc; if (string.IsNullOrEmpty(searchText)) { @@ -1284,7 +1272,7 @@ private IEnumerable GetPortalFolders(int portalId, string searchTex { searchFunc = folder => folder.FolderName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1; } - + permission = string.IsNullOrEmpty(permission) ? null : permission.ToUpper(); return FolderManager.Instance.GetFolders(portalId).Where(folder => (string.IsNullOrEmpty(permission) ? @@ -1299,8 +1287,8 @@ private bool HasChildren(IFolderInfo parentFolder, string permission) (string.IsNullOrEmpty(permission) ? (this.HasPermission(folder, "BROWSE") || this.HasPermission(folder, "READ")) : this.HasPermission(folder, permission))); - } - + } + private NTree GetFilesInternal(int portalId, int parentId, string filter, string searchText, int sortOrder, string permissions) { var tree = new NTree { Data = new ItemDto { Key = RootKey } }; @@ -1321,16 +1309,16 @@ private IEnumerable GetFileItemsDto(int portalId, int parentId, string { if (portalId > -1) { - if (!this.IsPortalIdValid(portalId)) - { - return new List(); - } + if (!this.IsPortalIdValid(portalId)) + { + return new List(); + } } else { portalId = this.GetActivePortalId(); } - + var parentFolder = parentId > -1 ? FolderManager.Instance.GetFolder(parentId) : FolderManager.Instance.GetFolder(portalId, string.Empty); if (parentFolder == null) @@ -1341,11 +1329,11 @@ private IEnumerable GetFileItemsDto(int portalId, int parentId, string var hasPermission = string.IsNullOrEmpty(permission) ? (this.HasPermission(parentFolder, "BROWSE") || this.HasPermission(parentFolder, "READ")) : this.HasPermission(parentFolder, permission.ToUpper()); - if (!hasPermission) - { - return new List(); - } - + if (!hasPermission) + { + return new List(); + } + if (parentId < 1) { return new List(); @@ -1377,56 +1365,30 @@ private IEnumerable GetFiles(IFolderInfo parentFolder, string filter, else { searchFunc = f => f.FileName.IndexOf(searchText, StringComparison.InvariantCultureIgnoreCase) > -1 - && (filterList == null || filterList.Contains(f.Extension.ToLowerInvariant())); + && (filterList == null || filterList.Contains(f.Extension.ToLowerInvariant())); } return FolderManager.Instance.GetFiles(parentFolder).Where(f => searchFunc(f)); - } - - /// - /// This class stores a single search result needed by jQuery Tokeninput. - /// - private class SearchResult - { - // ReSharper disable InconsistentNaming - // ReSharper disable NotAccessedField.Local - public int id; - public string name; - public string iconfile; - - // ReSharper restore NotAccessedField.Local - // ReSharper restore InconsistentNaming - } - - 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) - { - return true; - } - - if (this.PortalSettings.PortalId == portalId) - { - return true; - } - + if (this.UserInfo.IsSuperUser) + { + return true; + } + + if (this.PortalSettings.PortalId == portalId) + { + return true; + } + var isAdminUser = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); - if (!isAdminUser) - { - return false; - } - + if (!isAdminUser) + { + return false; + } + var mygroup = GetMyPortalGroup(); return mygroup != null && mygroup.Any(p => p.PortalID == portalId); } @@ -1440,19 +1402,57 @@ private int GetActivePortalId(int pageId) { portalId = this.GetActivePortalId(); } - + return portalId; } private int GetActivePortalId() { var portalId = -1; - if (!TabController.CurrentPage.IsSuperTab) - { - portalId = this.PortalSettings.PortalId; - } - + if (!TabController.CurrentPage.IsSuperTab) + { + portalId = this.PortalSettings.PortalId; + } + return portalId; - } + } + + [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; } + } + + /// + /// This class stores a single search result needed by jQuery Tokeninput. + /// + private class SearchResult + { + // ReSharper disable InconsistentNaming + // ReSharper disable NotAccessedField.Local + public int id; + public string name; + public string iconfile; + + // ReSharper restore NotAccessedField.Local + // ReSharper restore InconsistentNaming + } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs index c23114caca7..e33da42fe35 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/LanguageServiceController.cs @@ -25,7 +25,7 @@ public LanguageServiceController(INavigationManager navigationManager) { this.NavigationManager = navigationManager; } - + protected INavigationManager NavigationManager { get; } [HttpGet] @@ -49,10 +49,10 @@ public HttpResponseMessage GetNonTranslatedPages(string languageCode) }); } } - + return this.Request.CreateResponse(HttpStatusCode.OK, pages); } - + private bool IsDefaultLanguage(string code) { return code == this.PortalSettings.DefaultLanguage; @@ -61,9 +61,9 @@ private bool IsDefaultLanguage(string code) 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 97fd3384e13..790d6f6216e 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/MessagingServiceController.cs @@ -28,7 +28,7 @@ namespace DotNetNuke.Web.InternalServices public class MessagingServiceController : DnnApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MessagingServiceController)); - + [HttpGet] public HttpResponseMessage WaitTimeForNextMessage() { @@ -86,11 +86,11 @@ public HttpResponseMessage Search(string q) // 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); - } - + 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 { @@ -101,17 +101,17 @@ 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)); @@ -142,7 +142,7 @@ private class SearchResult public string id; public string name; public string iconfile; - + // ReSharper restore NotAccessedField.Local // ReSharper restore InconsistentNaming } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs index c94be293c03..9920c8b506c 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ModuleServiceController.cs @@ -81,7 +81,7 @@ public HttpResponseMessage MoveModule(MoveModuleDTO postData) } } } - + ModuleController.Instance.UpdateModuleOrder(postData.TabId, postData.ModuleId, moduleOrder, postData.Pane); ModuleController.Instance.UpdateTabModuleOrder(postData.TabId); @@ -103,33 +103,33 @@ public HttpResponseMessage DeleteModule(DeleteModuleDto deleteModuleDto) return this.Request.CreateResponse(HttpStatusCode.OK); } - + + private int FixPortalId(int portalId) + { + return this.UserInfo.IsSuperUser && this.PortalSettings.PortalId != portalId && PortalController.Instance.GetPortals() + .OfType().Any(x => x.PortalID == portalId) + ? portalId + : this.PortalSettings.PortalId; + } + 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) - { - return this.UserInfo.IsSuperUser && this.PortalSettings.PortalId != portalId && PortalController.Instance.GetPortals() - .OfType().Any(x => x.PortalID == portalId) - ? portalId - : this.PortalSettings.PortalId; + public bool SoftDelete { get; set; } } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs index f73640c61be..3d30a63fcc0 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/NotificationsServiceController.cs @@ -42,7 +42,7 @@ public HttpResponseMessage Dismiss(NotificationDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } - + [HttpGet] public HttpResponseMessage GetToasts() { diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs index a827d8c7582..0dcd10d28b9 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/PageServiceController.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Web.InternalServices public class PageServiceController : DnnApiController { private int? _portalId; - + protected int PortalId { get @@ -31,11 +31,11 @@ protected int PortalId { this._portalId = this.PortalSettings.ActiveTab.IsSuperTab ? -1 : this.PortalSettings.PortalId; } - + return this._portalId.Value; } } - + [HttpPost] [ValidateAntiForgeryToken] [DnnPagePermission] @@ -54,7 +54,7 @@ public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) { var urlPath = dto.Path.ValueOrEmpty().TrimStart('/'); bool modified; - + // Clean Url var options = UrlRewriterUtils.ExtendOptionsForCustomURLs(UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(this.PortalSettings.PortalId))); @@ -62,7 +62,7 @@ public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); if (modified) { - return this.Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, new { @@ -76,7 +76,7 @@ public HttpResponseMessage UpdateCustomUrl(SaveUrlDto dto) urlPath = FriendlyUrlController.ValidateUrl(urlPath, -1, this.PortalSettings, out modified); if (modified) { - return this.Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, new { @@ -100,17 +100,17 @@ 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); } @@ -131,21 +131,21 @@ 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); } - + var response = new { Success = true, diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs index 18a6b9463eb..d1eecdba565 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ProfileServiceController.cs @@ -27,7 +27,7 @@ public class ProfileServiceController : DnnApiController public HttpResponseMessage Search(string q) { var results = RegistrationProfileController.Instance.Search(PortalController.GetEffectivePortalId(this.PortalSettings.PortalId), q); - return this.Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, results.OrderBy(sr => sr) .Select(field => new { id = field, name = field })); @@ -42,33 +42,33 @@ public HttpResponseMessage UpdateVanityUrl(VanityUrlDTO vanityUrl) // Clean Url var options = UrlRewriterUtils.GetOptionsFromSettings(new FriendlyUrlSettings(this.PortalSettings.PortalId)); var cleanUrl = FriendlyUrlController.CleanNameForUrl(vanityUrl.Url, options, out modified); - + if (modified) { - return this.Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, - new - { - Result = "warning", - Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), - Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), - SuggestedUrl = cleanUrl, + new + { + Result = "warning", + Title = Localization.GetString("CleanWarningTitle", Localization.SharedResourceFile), + Message = Localization.GetString("ProfileUrlCleaned", Localization.SharedResourceFile), + SuggestedUrl = cleanUrl, }); } // Validate for uniqueness var uniqueUrl = FriendlyUrlController.ValidateUrl(cleanUrl, -1, this.PortalSettings, out modified); - + if (modified) { - return this.Request.CreateResponse( + 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, }); } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs index b7b779ae4f4..eadb45594c2 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/RelationshipServiceController.cs @@ -59,7 +59,7 @@ public HttpResponseMessage AcceptFriend(NotificationDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"); } - + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage FollowBack(NotificationDTO postData) @@ -81,7 +81,7 @@ public HttpResponseMessage FollowBack(NotificationDTO postData) { var response = new { - Message = Localization.GetExceptionMessage( + Message = Localization.GetExceptionMessage( "UserDoesNotExist", "The user you are trying to follow no longer exists."), }; @@ -100,7 +100,7 @@ public HttpResponseMessage FollowBack(NotificationDTO postData) Logger.Error(exc); var response = new { - Message = Localization.GetExceptionMessage( + Message = Localization.GetExceptionMessage( "AlreadyFollowingUser", "You are already following this user."), }; diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs index 0cd24fb0512..4809d233dde 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/SearchServiceController.cs @@ -34,9 +34,12 @@ public class SearchServiceController : DnnApiController private const string ModuleInfosCacheKey = "ModuleInfos{0}"; private const CacheItemPriority ModuleInfosCachePriority = CacheItemPriority.AboveNormal; private const int ModuleInfosCacheTimeOut = 20; - + private const string ModuleTitleCacheKey = "SearchModuleTabTitle_{0}"; + private const CacheItemPriority ModuleTitleCachePriority = CacheItemPriority.Normal; + private const int ModuleTitleCacheTimeOut = 20; + private static readonly Regex GroupedBasicViewRegex = new Regex("userid(/|\\|=)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); - + private int HtmlModuleDefitionId; public SearchServiceController() @@ -49,49 +52,173 @@ public SearchServiceController() internal SearchServiceController(int htmlModuleDefitionId) // , TabController newtabController, ModuleController newmoduleController) { this.HtmlModuleDefitionId = htmlModuleDefitionId; - + // _tabController = newtabController; // _moduleController = newmoduleController; - } + } - private bool IsWildCardEnabledForModule() + [HttpGet] + [AllowAnonymous] + public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1) { - var searchModuleSettings = this.GetSearchModuleSettings(); - var enableWildSearch = true; - if (!string.IsNullOrEmpty(Convert.ToString(searchModuleSettings["EnableWildSearch"]))) + string cleanedKeywords; + keywords = (keywords ?? string.Empty).Trim(); + var tags = SearchQueryStringParser.Instance.GetTags(keywords, out cleanedKeywords); + var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); + var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out cleanedKeywords); + + var contentSources = this.GetSearchContentSources(searchTypes); + var settings = this.GetSearchModuleSettings(); + var searchTypeIds = GetSearchTypeIds(settings, contentSources); + var moduleDefids = GetSearchModuleDefIds(settings, contentSources); + var portalIds = this.GetSearchPortalIds(settings, portal); + + var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; + var userSearchSource = contentSources.FirstOrDefault(s => s.SearchTypeId == userSearchTypeId); + + var results = new List(); + if (portalIds.Any() && searchTypeIds.Any() && + (!string.IsNullOrEmpty(cleanedKeywords) || tags.Any())) { - enableWildSearch = Convert.ToBoolean(searchModuleSettings["EnableWildSearch"]); + var query = new SearchQuery + { + KeyWords = cleanedKeywords, + Tags = tags, + PortalIds = portalIds, + SearchTypeIds = searchTypeIds, + ModuleDefIds = moduleDefids, + BeginModifiedTimeUtc = beginModifiedTimeUtc, + PageIndex = 1, + PageSize = 5, + TitleSnippetLength = 40, + BodySnippetLength = 100, + CultureCode = culture, + WildCardSearch = forceWild > 0, + }; + + try + { + results = this.GetGroupedBasicViews(query, userSearchSource, this.PortalSettings.PortalId); + } + catch (Exception ex) + { + DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); + } } - return enableWildSearch; - } + return this.Request.CreateResponse(HttpStatusCode.OK, results); + } - public class SynonymsGroupDto + [HttpGet] + [AllowAnonymous] + public HttpResponseMessage Search(string search, string culture, int pageIndex, int pageSize, int sortOption) { - public int Id { get; set; } - - public string Tags { get; set; } - - public int PortalId { get; set; } - - public string Culture { get; set; } + string cleanedKeywords; + search = (search ?? string.Empty).Trim(); + var tags = SearchQueryStringParser.Instance.GetTags(search, out cleanedKeywords); + var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); + var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(cleanedKeywords, out cleanedKeywords); + + var contentSources = this.GetSearchContentSources(searchTypes); + var settings = this.GetSearchModuleSettings(); + var searchTypeIds = GetSearchTypeIds(settings, contentSources); + var moduleDefids = GetSearchModuleDefIds(settings, contentSources); + var portalIds = this.GetSearchPortalIds(settings, -1); + var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; + + var more = false; + var totalHits = 0; + var results = new List(); + 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(), + }; + + try + { + results = this.GetGroupedDetailViews(query, userSearchTypeId, out totalHits, out more).ToList(); + } + catch (Exception ex) + { + DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); + } + } + + return this.Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more }); } - public class StopWordsDto + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage AddSynonymsGroup(SynonymsGroupDto synonymsGroup) { - public int Id { get; set; } - - public string Words { get; set; } - - public int PortalId { get; set; } - - public string Culture { get; set; } + string duplicateWord; + var synonymsGroupId = SearchHelper.Instance.AddSynonymsGroup(synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); + } + + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage UpdateSynonymsGroup(SynonymsGroupDto synonymsGroup) + { + string duplicateWord; + var synonymsGroupId = SearchHelper.Instance.UpdateSynonymsGroup(synonymsGroup.Id, synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); + } + + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage DeleteSynonymsGroup(SynonymsGroupDto synonymsGroup) + { + SearchHelper.Instance.DeleteSynonymsGroup(synonymsGroup.Id, synonymsGroup.PortalId, synonymsGroup.Culture); + return this.Request.CreateResponse(HttpStatusCode.OK); + } + + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage AddStopWords(StopWordsDto stopWords) + { + var stopWordsId = SearchHelper.Instance.AddSearchStopWords(stopWords.Words, stopWords.PortalId, stopWords.Culture); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); + } + + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage UpdateStopWords(StopWordsDto stopWords) + { + var stopWordsId = SearchHelper.Instance.UpdateSearchStopWords(stopWords.Id, stopWords.Words, stopWords.PortalId, stopWords.Culture); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); + } + + [HttpPost] + [ValidateAntiForgeryToken] + [SupportedModules("SearchAdmin")] + public HttpResponseMessage DeleteStopWords(StopWordsDto stopWords) + { + SearchHelper.Instance.DeleteSearchStopWords(stopWords.Id, stopWords.PortalId, stopWords.Culture); + return this.Request.CreateResponse(HttpStatusCode.OK); } - 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) { var searchResults = SearchController.Instance.SiteSearch(searchQuery); @@ -134,8 +261,8 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search // first entry var first = results[0]; - group.Title = showFriendlyTitle ? this.GetFriendlyTitle(first) : first.Title; - group.DocumentUrl = first.Url; + @group.Title = showFriendlyTitle ? this.GetFriendlyTitle(first) : first.Title; + @group.DocumentUrl = first.Url; // Find a different title for multiple entries with same url if (results.Count > 1) @@ -143,17 +270,17 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search if (first.TabId > 0) { var tab = TabController.Instance.GetTab(first.TabId, first.PortalId, false); - if (tab != null) - { - group.Title = showFriendlyTitle && !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; - } + if (tab != null) + { + @group.Title = showFriendlyTitle && !string.IsNullOrEmpty(tab.Title) ? tab.Title : tab.TabName; + } } else if (first.ModuleId > 0) { var tabTitle = this.GetTabTitleFromModuleId(first.ModuleId); if (!string.IsNullOrEmpty(tabTitle)) { - group.Title = tabTitle; + @group.Title = tabTitle; } } } @@ -162,13 +289,13 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search var tabTitle = this.GetTabTitleFromModuleId(first.ModuleId); if (!string.IsNullOrEmpty(tabTitle)) { - group.Title = tabTitle; - if (first.Title != "Enter Title" && first.Title != "Text/HTML") - { - group.Title += " > " + first.Title; - } - - first.Title = group.Title; + @group.Title = tabTitle; + if (first.Title != "Enter Title" && first.Title != "Text/HTML") + { + @group.Title += " > " + first.Title; + } + + first.Title = @group.Title; } } @@ -187,10 +314,10 @@ internal IEnumerable GetGroupedDetailViews(SearchQuery search AuthorProfileUrl = result.AuthorUserId > 0 ? Globals.UserProfileURL(result.AuthorUserId) : string.Empty, AuthorName = result.AuthorName, }; - group.Results.Add(detail); + @group.Results.Add(detail); } - groups.Add(group); + groups.Add(@group); } return groups; @@ -222,8 +349,8 @@ internal List GetGroupedBasicViews(SearchQuery query, SearchCo var groupedResult = results.SingleOrDefault(g => g.DocumentTypeName == preview.DocumentTypeName); if (groupedResult != null) { - if (!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl))) - { + if (!groupedResult.Results.Any(r => string.Equals(r.DocumentUrl, preview.DocumentUrl))) + { groupedResult.Results.Add(new BasicView { Title = preview.Title.Contains("<") ? HttpUtility.HtmlEncode(preview.Title) : preview.Title, @@ -231,8 +358,8 @@ internal List GetGroupedBasicViews(SearchQuery query, SearchCo Description = preview.Description, DocumentUrl = preview.DocumentUrl, Attributes = preview.Attributes, - }); - } + }); + } } else { @@ -291,17 +418,17 @@ private static List GetSearchTypeIds(IDictionary settings, IEnumerable 0) { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list - { - list.Add(contentSource.SearchTypeId); - } + if (configuredList.Any(l => l.Contains(contentSource.LocalizedName))) // in configured list + { + list.Add(contentSource.SearchTypeId); + } } else { @@ -324,30 +451,42 @@ private static IEnumerable GetSearchModuleDefIds(IDictionary settings, IEnu // check content source in configured list or not foreach (var contentSource in searchContentSources) { - if (contentSource.IsPrivate) - { - continue; - } - + if (contentSource.IsPrivate) + { + continue; + } + if (configuredList.Count > 0) { - if (configuredList.Any(l => l.Contains(contentSource.LocalizedName)) && contentSource.ModuleDefinitionId > 0) // in configured list - { - list.Add(contentSource.ModuleDefinitionId); - } + 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); - } + if (contentSource.ModuleDefinitionId > 0) + { + list.Add(contentSource.ModuleDefinitionId); + } } } return list; } + private bool IsWildCardEnabledForModule() + { + var searchModuleSettings = this.GetSearchModuleSettings(); + var enableWildSearch = true; + if (!string.IsNullOrEmpty(Convert.ToString(searchModuleSettings["EnableWildSearch"]))) + { + enableWildSearch = Convert.ToBoolean(searchModuleSettings["EnableWildSearch"]); + } + + return enableWildSearch; + } + private ModuleInfo GetSearchModule() { var arrModules = GetModulesByDefinition(this.PortalSettings.PortalId, "Search Results"); @@ -417,23 +556,23 @@ private List GetSearchPortalIds(IDictionary settings, int portalId) 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 + 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); - } - + if (userInfo.IsSuperUser) + { + list.Add(-1); + } + return list; } @@ -456,7 +595,7 @@ private IList GetSearchContentSources(IList typesLi } return sources; - } + } private string GetFriendlyTitle(SearchResult result) { @@ -475,123 +614,17 @@ private string GetTitle(SearchResult result, bool showFriendlyTitle = false) var tabTitle = this.GetTabTitleFromModuleId(result.ModuleId); if (!string.IsNullOrEmpty(tabTitle)) { - if (result.Title != "Enter Title" && result.Title != "Text/HTML") - { - return tabTitle + " > " + result.Title; - } - + if (result.Title != "Enter Title" && result.Title != "Text/HTML") + { + return tabTitle + " > " + result.Title; + } + return tabTitle; } } return showFriendlyTitle ? this.GetFriendlyTitle(result) : result.Title; } - - [HttpGet] - [AllowAnonymous] - public HttpResponseMessage Preview(string keywords, string culture, int forceWild = 1, int portal = -1) - { - string cleanedKeywords; - keywords = (keywords ?? string.Empty).Trim(); - var tags = SearchQueryStringParser.Instance.GetTags(keywords, out cleanedKeywords); - var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); - var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(keywords, out cleanedKeywords); - - var contentSources = this.GetSearchContentSources(searchTypes); - var settings = this.GetSearchModuleSettings(); - var searchTypeIds = GetSearchTypeIds(settings, contentSources); - var moduleDefids = GetSearchModuleDefIds(settings, contentSources); - var portalIds = this.GetSearchPortalIds(settings, portal); - - var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; - var userSearchSource = contentSources.FirstOrDefault(s => s.SearchTypeId == userSearchTypeId); - - var results = new List(); - 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, - PageIndex = 1, - PageSize = 5, - TitleSnippetLength = 40, - BodySnippetLength = 100, - CultureCode = culture, - WildCardSearch = forceWild > 0, - }; - - try - { - results = this.GetGroupedBasicViews(query, userSearchSource, this.PortalSettings.PortalId); - } - catch (Exception ex) - { - DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); - } - } - - return this.Request.CreateResponse(HttpStatusCode.OK, results); - } - - [HttpGet] - [AllowAnonymous] - public HttpResponseMessage Search(string search, string culture, int pageIndex, int pageSize, int sortOption) - { - string cleanedKeywords; - search = (search ?? string.Empty).Trim(); - var tags = SearchQueryStringParser.Instance.GetTags(search, out cleanedKeywords); - var beginModifiedTimeUtc = SearchQueryStringParser.Instance.GetLastModifiedDate(cleanedKeywords, out cleanedKeywords); - var searchTypes = SearchQueryStringParser.Instance.GetSearchTypeList(cleanedKeywords, out cleanedKeywords); - - var contentSources = this.GetSearchContentSources(searchTypes); - var settings = this.GetSearchModuleSettings(); - var searchTypeIds = GetSearchTypeIds(settings, contentSources); - var moduleDefids = GetSearchModuleDefIds(settings, contentSources); - var portalIds = this.GetSearchPortalIds(settings, -1); - var userSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; - - var more = false; - var totalHits = 0; - var results = new List(); - 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(), - }; - - try - { - results = this.GetGroupedDetailViews(query, userSearchTypeId, out totalHits, out more).ToList(); - } - catch (Exception ex) - { - DotNetNuke.Services.Exceptions.Exceptions.LogException(ex); - } - } - - return this.Request.CreateResponse(HttpStatusCode.OK, new { results, totalHits, more }); - } private string GetTabTitleFromModuleId(int moduleId) { @@ -613,62 +646,28 @@ private object GetTabTitleCallBack(CacheItemArgs cacheItemArgs) } return string.Empty; - } - - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage AddSynonymsGroup(SynonymsGroupDto synonymsGroup) - { - string duplicateWord; - var synonymsGroupId = SearchHelper.Instance.AddSynonymsGroup(synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); } - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage UpdateSynonymsGroup(SynonymsGroupDto synonymsGroup) + public class SynonymsGroupDto { - string duplicateWord; - var synonymsGroupId = SearchHelper.Instance.UpdateSynonymsGroup(synonymsGroup.Id, synonymsGroup.Tags, synonymsGroup.PortalId, synonymsGroup.Culture, out duplicateWord); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = synonymsGroupId, DuplicateWord = duplicateWord }); - } + public int Id { get; set; } - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage DeleteSynonymsGroup(SynonymsGroupDto synonymsGroup) - { - SearchHelper.Instance.DeleteSynonymsGroup(synonymsGroup.Id, synonymsGroup.PortalId, synonymsGroup.Culture); - return this.Request.CreateResponse(HttpStatusCode.OK); - } - - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage AddStopWords(StopWordsDto stopWords) - { - var stopWordsId = SearchHelper.Instance.AddSearchStopWords(stopWords.Words, stopWords.PortalId, stopWords.Culture); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); - } + public string Tags { get; set; } - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage UpdateStopWords(StopWordsDto stopWords) - { - var stopWordsId = SearchHelper.Instance.UpdateSearchStopWords(stopWords.Id, stopWords.Words, stopWords.PortalId, stopWords.Culture); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Id = stopWordsId }); + public int PortalId { get; set; } + + public string Culture { get; set; } } - [HttpPost] - [ValidateAntiForgeryToken] - [SupportedModules("SearchAdmin")] - public HttpResponseMessage DeleteStopWords(StopWordsDto stopWords) + public class StopWordsDto { - SearchHelper.Instance.DeleteSearchStopWords(stopWords.Id, stopWords.PortalId, stopWords.Culture); - return this.Request.CreateResponse(HttpStatusCode.OK); + public int Id { get; set; } + + public string Words { get; set; } + + public int PortalId { get; set; } + + public string Culture { get; set; } } } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs b/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs index f1817aca1a3..f0a61c292b3 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/ServiceRouteMapper.cs @@ -10,7 +10,7 @@ public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute mapRouteManager) { - mapRouteManager.MapHttpRoute( + mapRouteManager.MapHttpRoute( "InternalServices", "default", "{controller}/{action}", diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs index 845eba8919a..1345385e6de 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/UserFileController.cs @@ -83,7 +83,34 @@ private static bool IsImageFile(string relativePath) return acceptedExtensions.Contains(extension); } - // ReSharper disable LoopCanBeConvertedToQuery + private static string GetFileSize(int sizeInBytes) + { + var size = sizeInBytes / 1024; + var biggerThanAMegabyte = size > 1024; + if (biggerThanAMegabyte) + { + size = size / 1024; + } + + return size.ToString(CultureInfo.InvariantCulture) + (biggerThanAMegabyte ? "Mb" : "k"); + } + + private string GetThumbUrl(IFileInfo file) + { + if (IsImageFile(file.RelativePath)) + { + return FileManager.Instance.GetUrl(file); + } + + var fileIcon = IconController.IconURL("Ext" + file.Extension, "32x32"); + if (!System.IO.File.Exists(this.Request.GetHttpContext().Server.MapPath(fileIcon))) + { + fileIcon = IconController.IconURL("File", "32x32"); + } + + return fileIcon; + } + private List GetChildren(IFolderInfo folder, ICollection extensions) { var everything = new List(); @@ -126,59 +153,34 @@ private List GetChildren(IFolderInfo folder, ICollection extension return everything; } - // ReSharper restore LoopCanBeConvertedToQuery - private string GetThumbUrl(IFileInfo file) - { - if (IsImageFile(file.RelativePath)) - { - return FileManager.Instance.GetUrl(file); - } - - var fileIcon = IconController.IconURL("Ext" + file.Extension, "32x32"); - if (!System.IO.File.Exists(this.Request.GetHttpContext().Server.MapPath(fileIcon))) - { - fileIcon = IconController.IconURL("File", "32x32"); - } - - return fileIcon; - } - - private static string GetFileSize(int sizeInBytes) - { - var size = sizeInBytes / 1024; - var biggerThanAMegabyte = size > 1024; - if (biggerThanAMegabyte) - { - size = size / 1024; - } - - return size.ToString(CultureInfo.InvariantCulture) + (biggerThanAMegabyte ? "Mb" : "k"); - } - private class Item { // ReSharper disable InconsistentNaming // ReSharper disable UnusedAutoPropertyAccessor.Local public int id { get; set; } - + public string name { get; set; } - + public bool folder { get; set; } - + public int parentId { get; set; } - + public string thumb_url { get; set; } - + public string type { get; set; } - + public string size { get; set; } - + public string modified { get; set; } - + public List children { get; set; } - + // ReSharper restore UnusedAutoPropertyAccessor.Local // ReSharper restore InconsistentNaming } + + // ReSharper disable LoopCanBeConvertedToQuery + + // ReSharper restore LoopCanBeConvertedToQuery } } diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs index 1be0a054e43..c95f974ae53 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/BasicView.cs @@ -17,7 +17,7 @@ public BasicView() { this.Attributes = new Dictionary(); } - + /// /// Gets or sets document's Title. /// diff --git a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs index 05090e315ca..7bdcea0e61b 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedBasicView.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Web.InternalServices.Views.Search public class GroupedBasicView { public GroupedBasicView() - { - } + { + } public GroupedBasicView(BasicView basic) { @@ -29,8 +29,8 @@ public GroupedBasicView(BasicView basic) Attributes = basic.Attributes }, }; - } - + } + /// /// Gets or sets type of Search Document. /// @@ -39,6 +39,6 @@ public GroupedBasicView(BasicView basic) /// /// Gets or sets results of the Search. /// - public List Results { get; set; } + 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 9c9fda33ab4..4e36b2e6f97 100644 --- a/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs +++ b/DNN Platform/DotNetNuke.Web/InternalServices/Views/Search/GroupedDetailView.cs @@ -14,8 +14,8 @@ public class GroupedDetailView public GroupedDetailView() { this.Results = new List(); - } - + } + /// /// Gets or sets document's Url. /// @@ -29,6 +29,6 @@ public GroupedDetailView() /// /// Gets or sets results of the Search. /// - public List Results { get; set; } + public List Results { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs index 4b859cdaafe..71dc6a9e89e 100644 --- a/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/ModuleDetail.cs @@ -14,7 +14,7 @@ public ModuleDetail() { this.ModuleInstances = new List(); } - + [DataMember] public string ModuleVersion { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs index 60d7a671f40..3258b7d8676 100644 --- a/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs +++ b/DNN Platform/DotNetNuke.Web/Models/SiteDetail.cs @@ -14,7 +14,7 @@ public SiteDetail() { this.Modules = new List(); } - + [DataMember] public string DnnVersion { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs index 8dfd3d2ff1c..f48550b4d4a 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerPresenter.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Web.Mvp public abstract class HttpHandlerPresenter : Presenter where TView : class, IHttpHandlerView { - protected HttpHandlerPresenter(TView view) + protected HttpHandlerPresenter(TView view) : base(view) { } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs index 0caf7546cc4..acca4bcacce 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/HttpHandlerView.cs @@ -10,6 +10,5 @@ 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 abstract class HttpHandlerView : MvpHttpHandler, IHttpHandlerView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs index 5e217c94314..f1bede214de 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IHttpHandlerView.cs @@ -10,6 +10,5 @@ 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 IHttpHandlerView : IView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs index cd3c22032b5..649d526acfe 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleView.cs @@ -7,6 +7,5 @@ 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 IModuleView : IModuleViewBase - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs index 5e9dd07be43..949e41d2c60 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewBase.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Web.Mvp public interface IModuleViewBase : IView { event EventHandler Initialize; - + bool AutoDataBind { get; set; } void ProcessModuleLoadException(Exception ex); diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs index 02cfced008f..cdb98ab33c4 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IModuleViewOfT.cs @@ -10,6 +10,5 @@ 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 IModuleView : IModuleViewBase, IView where TModel : class, new() - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs index c943d579308..6f8e8034bd8 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceView.cs @@ -8,6 +8,5 @@ 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 IWebServiceView : IWebServiceViewBase - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs index f3d971261e8..a60437b333a 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewBase.cs @@ -10,6 +10,5 @@ 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 IWebServiceViewBase : IView - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs index 40398dec299..48021139cb3 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/IWebServiceViewOfT.cs @@ -11,6 +11,5 @@ 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 IWebServiceView : IWebServiceViewBase, IView where TModel : class, new() - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs index 548a4d7fbf7..61c50127724 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenter.cs @@ -11,8 +11,8 @@ public abstract class ModulePresenter : ModulePresenterBase where TView : class, IModuleView { protected ModulePresenter(TView view) - : base(view) - { + : base(view) + { } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs index 4a06e9105b4..12dde780df0 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterBase.cs @@ -19,8 +19,8 @@ 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 abstract class ModulePresenterBase : Presenter where TView : class, IModuleViewBase - { - protected ModulePresenterBase(TView view) + { + protected ModulePresenterBase(TView view) : base(view) { // Try and cast view to Control to get common control properties @@ -37,32 +37,16 @@ protected ModulePresenterBase(TView view) this.LocalResourceFile = moduleControl.LocalResourceFile; this.ModuleContext = moduleControl.ModuleContext; } - + this.Validator = new Validator(new DataAnnotationsObjectValidator()); view.Initialize += this.InitializeInternal; view.Load += this.LoadInternal; - } - + } + public bool AutoDataBind { get; set; } public ModuleInfo ModuleInfo { get; set; } - - protected internal virtual bool AllowAnonymousAccess - { - get - { - return true; - } - } - - protected internal virtual bool IsUserAuthorized - { - get - { - return true; - } - } public bool IsEditable { get; set; } @@ -84,8 +68,24 @@ protected internal virtual bool IsUserAuthorized public Dictionary Settings { get; set; } - public Validator Validator { get; set; } - + public Validator Validator { get; set; } + + protected internal virtual bool AllowAnonymousAccess + { + get + { + return true; + } + } + + protected internal virtual bool IsUserAuthorized + { + get + { + return true; + } + } + public virtual void RestoreState(StateBag stateBag) { AttributeBasedViewStateSerializer.DeSerialize(this, stateBag); @@ -94,8 +94,8 @@ public virtual void RestoreState(StateBag stateBag) public virtual void SaveState(StateBag stateBag) { AttributeBasedViewStateSerializer.Serialize(this, stateBag); - } - + } + protected internal virtual bool CheckAuthPolicy() { if (this.UserId == Null.NullInteger && !this.AllowAnonymousAccess) @@ -127,25 +127,11 @@ protected virtual void LoadFromContext() { this.Settings[key.ToString()] = (string)this.ModuleContext.Settings[key]; } - + this.TabId = this.ModuleContext.TabId; 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) { @@ -158,7 +144,7 @@ protected virtual string LocalizeString(string key) { localizedString = Null.NullString; } - + return localizedString; } @@ -224,9 +210,23 @@ protected void ShowMessage(string messageHeader, string message, ModuleMessage.M messageHeader = this.LocalizeString(messageHeader); message = this.LocalizeString(message); } - + this.View.ShowMessage(messageHeader, message, messageType); } - } + } + + private void InitializeInternal(object sender, EventArgs e) + { + this.LoadFromContext(); + this.OnInit(); + } + + private void LoadInternal(object sender, EventArgs e) + { + if (this.CheckAuthPolicy()) + { + this.OnLoad(); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs index 2d81cd64e0c..655f050e79d 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModulePresenterOfT.cs @@ -11,7 +11,7 @@ public abstract class ModulePresenter : ModulePresenterBase where TModel : class, new() { - protected ModulePresenter(TView view) + protected ModulePresenter(TView view) : base(view) { } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs index 3ef2ae0a213..4e17165b2a8 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenter.cs @@ -10,8 +10,8 @@ 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 ModuleSettingsPresenterBase : ModulePresenterBase where TView : class, ISettingsView - { - public ModuleSettingsPresenterBase(TView view) + { + public ModuleSettingsPresenterBase(TView view) : base(view) { view.OnLoadSettings += this.OnLoadSettingsInternal; @@ -19,12 +19,12 @@ public ModuleSettingsPresenterBase(TView view) this.ModuleSettings = new Dictionary(); this.TabModuleSettings = new Dictionary(); - } - + } + public Dictionary ModuleSettings { get; set; } - public Dictionary TabModuleSettings { get; set; } - + public Dictionary TabModuleSettings { get; set; } + protected override void LoadFromContext() { base.LoadFromContext(); @@ -43,7 +43,11 @@ protected override void LoadFromContext() protected virtual void LoadSettings() { } - + + protected virtual void SaveSettings() + { + } + private void OnLoadSettingsInternal(object sender, EventArgs e) { this.LoadSettings(); @@ -52,10 +56,6 @@ private void OnLoadSettingsInternal(object sender, EventArgs e) 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 2e268351498..ccad74752ae 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleSettingsPresenterOfT.cs @@ -16,13 +16,13 @@ public abstract class ModuleSettingsPresenter : ModulePresenterBa where TView : class, ISettingsView where TModel : SettingsModel, new() { - protected ModuleSettingsPresenter(TView view) + protected ModuleSettingsPresenter(TView view) : base(view) { view.OnLoadSettings += this.OnLoadSettingsInternal; view.OnSaveSettings += this.OnSaveSettingsInternal; - } - + } + protected override void OnLoad() { base.OnLoad(); @@ -47,16 +47,6 @@ 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() { @@ -71,6 +61,16 @@ protected virtual void SaveSettings() { ModuleController.Instance.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, setting.Key, setting.Value); } - } + } + + private void OnLoadSettingsInternal(object sender, EventArgs e) + { + this.LoadSettings(); + } + + private void OnSaveSettingsInternal(object sender, EventArgs e) + { + this.SaveSettings(); + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs index 43b8f8809c1..771203749d5 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleView.cs @@ -8,6 +8,5 @@ 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 abstract class ModuleView : ModuleViewBase - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs index 07a903f7962..b77a4a7db4b 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewBase.cs @@ -13,22 +13,22 @@ 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 abstract class ModuleViewBase : ModuleUserControlBase, IModuleViewBase - { + { 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 bool AutoDataBind { get; set; } public void ProcessModuleLoadException(Exception ex) { @@ -38,10 +38,10 @@ public void ProcessModuleLoadException(Exception 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() + } + + protected T DataItem() + where T : class, new() { var _T = this.Page.GetDataItem() as T ?? new T(); return _T; @@ -66,8 +66,8 @@ protected override void OnInit(EventArgs e) this.Page.InitComplete += this.PageInitComplete; this.Page.PreRenderComplete += this.PagePreRenderComplete; this.Page.Load += this.PageLoad; - } - + } + private void PageInitComplete(object sender, EventArgs e) { if (this.Initialize != null) @@ -92,6 +92,6 @@ private void PagePreRenderComplete(object sender, EventArgs e) { this.DataBind(); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs index be44cad0b92..fd07b1194c9 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ModuleViewOfT.cs @@ -11,8 +11,8 @@ namespace DotNetNuke.Web.Mvp public abstract class ModuleView : ModuleViewBase, IView where TModel : class, new() { - private TModel _model; - + private TModel _model; + public TModel Model { get @@ -22,13 +22,13 @@ public TModel Model throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - + return this._model; } - + set { this._model = value; } - } - + } + protected override void LoadViewState(object savedState) { // Call the base class to load any View State @@ -39,7 +39,7 @@ protected override void LoadViewState(object savedState) protected override object SaveViewState() { AttributeBasedViewStateSerializer.Serialize(this.Model, this.ViewState); - + // Call the base class to save the View State return base.SaveViewState(); } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs index b7436d124d6..2c3ab7df1b2 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/ProfileModuleViewBase.cs @@ -23,8 +23,8 @@ public abstract class ProfileModuleViewBase : ModuleView, IProfi public ProfileModuleViewBase() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - + } + public abstract bool DisplayModule { get; } public int ProfileUserId @@ -36,13 +36,13 @@ public int ProfileUserId { UserId = int.Parse(this.Request.Params["UserId"]); } - + return UserId; } - } - + } + protected INavigationManager NavigationManager { get; } - + protected bool IsUser { get @@ -54,8 +54,8 @@ protected bool IsUser protected UserInfo ProfileUser { get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } - } - + } + protected override void OnInit(EventArgs e) { if (this.ProfileUserId == Null.NullInteger && @@ -63,15 +63,15 @@ protected override void OnInit(EventArgs e) || this.ModuleContext.PortalSettings.ActiveTab.ParentId == this.ModuleContext.PortalSettings.UserTabId)) { // Clicked on breadcrumb - don't know which user - this.Response.Redirect( + 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. @@ -88,6 +88,6 @@ private string GetRedirectUrl() } return redirectUrl; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs index 86585f36cb7..4de8c4afc53 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsView.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.Web.Mvp public abstract class SettingsView : SettingsViewBase, ISettingsView where TModel : SettingsModel, new() { - private TModel _model; - + private TModel _model; + public TModel Model { get @@ -21,13 +21,13 @@ public TModel Model throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - + return this._model; } - + set { this._model = value; } - } - + } + protected string GetModuleSetting(string key, string defaultValue) { var value = defaultValue; diff --git a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs index 183effd02a6..76574c3dbc9 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/SettingsViewBase.cs @@ -9,11 +9,11 @@ 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 event EventHandler OnSaveSettings; + public void LoadSettings() { if (this.OnLoadSettings != null) @@ -32,8 +32,8 @@ public void UpdateSettings() { this.OnSaveSettings(this, EventArgs.Empty); } - } - + } + /// /// The OnSettingsLoaded method is called when the Settings have been Loaded. /// diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs index 7783a06be77..c1c7d3b9d9e 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServicePresenter.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Web.Mvp public abstract class WebServicePresenter : Presenter where TView : class, IWebServiceView { - protected WebServicePresenter(TView view) + protected WebServicePresenter(TView view) : base(view) { } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs index 0b71438e459..49e90251b23 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceView.cs @@ -8,6 +8,5 @@ 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 abstract class WebServiceView : WebServiceViewBase - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs index 59c4ab18c13..8cf44124370 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewBase.cs @@ -10,6 +10,5 @@ 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 abstract class WebServiceViewBase : MvpWebService, IWebServiceViewBase - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs index 8d40d8f92b6..6938dc407aa 100644 --- a/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs +++ b/DNN Platform/DotNetNuke.Web/Mvp/WebServiceViewOfT.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Web.Mvp public abstract class WebServiceViewOfT : ModuleViewBase, IView where TModel : class, new() { - private TModel _model; - + private TModel _model; + public TModel Model { get @@ -23,11 +23,11 @@ public TModel Model throw new InvalidOperationException( "The Model property is currently null, however it should have been automatically initialized by the presenter. This most likely indicates that no presenter was bound to the control. Check your presenter bindings."); } - + return this._model; } - + set { this._model = value; } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs index fc9d449eb3e..2cf44634901 100644 --- a/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs +++ b/DNN Platform/DotNetNuke.Web/Services/MobileHelperController.cs @@ -28,7 +28,7 @@ public class MobileHelperController : DnnApiController /// /// Gets the various defined monikers for the various tab modules in the system. - /// + ///
/// [HttpGet] public IHttpActionResult Monikers(string moduleList) @@ -42,8 +42,8 @@ public HttpResponseMessage ModuleDetails(string moduleList) { var siteDetails = this.GetSiteDetails(moduleList); return this.Request.CreateResponse(HttpStatusCode.OK, siteDetails); - } - + } + private static IEnumerable> GetMonikersForList(string moduleList) { var portalId = PortalSettings.Current.PortalId; @@ -128,6 +128,22 @@ private static object GetTabModulesCallback(CacheItemArgs cacheItemArgs) return tabModules; } + private static void AddChildTabsToList(TabInfo currentTab, TabCollection allPortalTabs, + IDictionary tabsWithModule, IDictionary tabsInOrder) + { + if (tabsWithModule.ContainsKey(currentTab.TabID) && !tabsInOrder.ContainsKey(currentTab.TabID)) + { + // add current tab + tabsInOrder.Add(currentTab.TabID, currentTab); + + // add children of current tab + foreach (var tab in allPortalTabs.WithParentId(currentTab.TabID)) + { + AddChildTabsToList(tab, allPortalTabs, tabsWithModule, tabsInOrder); + } + } + } + private SiteDetail GetSiteDetails(string moduleList) { var siteDetails = new SiteDetail @@ -164,21 +180,5 @@ private SiteDetail GetSiteDetails(string moduleList) return siteDetails; } - - private static void AddChildTabsToList(TabInfo currentTab, TabCollection allPortalTabs, - IDictionary tabsWithModule, IDictionary tabsInOrder) - { - if (tabsWithModule.ContainsKey(currentTab.TabID) && !tabsInOrder.ContainsKey(currentTab.TabID)) - { - // add current tab - tabsInOrder.Add(currentTab.TabID, currentTab); - - // add children of current tab - foreach (var tab in allPortalTabs.WithParentId(currentTab.TabID)) - { - AddChildTabsToList(tab, allPortalTabs, tabsWithModule, tabsInOrder); - } - } - } } } diff --git a/DNN Platform/DotNetNuke.Web/Startup.cs b/DNN Platform/DotNetNuke.Web/Startup.cs index c05fd6887f1..59d5c298188 100644 --- a/DNN Platform/DotNetNuke.Web/Startup.cs +++ b/DNN Platform/DotNetNuke.Web/Startup.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Web public class Startup : IDnnStartup { private static readonly ILog _logger = LoggerSource.Instance.GetLogger(typeof(Startup)); - + public Startup() { this.Configure(); diff --git a/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs b/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs index 7a1428a505b..b6b4dbc5ae6 100644 --- a/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs +++ b/DNN Platform/DotNetNuke.Web/UI/ILocalizable.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Web.UI public interface ILocalizable { string LocalResourceFile { get; set; } - + bool Localize { get; set; } void LocalizeStrings(); diff --git a/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs b/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs index 5695703ae90..7b29135ea79 100644 --- a/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs +++ b/DNN Platform/DotNetNuke.Web/UI/MessageWindowParameters.cs @@ -37,7 +37,7 @@ public string Message { return this._Message; } - + set { // todo: javascript encode for onclick events @@ -53,7 +53,7 @@ public string Title { return this._Title; } - + set { // todo: javascript encode for onclick events @@ -69,7 +69,7 @@ public Unit WindowWidth { return this._WindowWidth; } - + set { this._WindowWidth = value; @@ -82,7 +82,7 @@ public Unit WindowHeight { return this._WindowHeight; } - + set { this._WindowHeight = value; diff --git a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs index 242e52b752d..ec44ba6c193 100644 --- a/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs +++ b/DNN Platform/DotNetNuke.Web/UI/RibbonBarManager.cs @@ -50,7 +50,7 @@ public enum TabRelativeLocation public class RibbonBarManager { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RibbonBarManager)); - + public static TabInfo InitTabInfoObject() { return InitTabInfoObject(null, TabRelativeLocation.AFTER); @@ -93,7 +93,7 @@ public static TabInfo InitTabInfoObject(TabInfo relativeToTab, TabRelativeLocati if (PortalSettings.Current.SSLEnabled) { newTab.IsSecure = parentTab.IsSecure; - + // Inherit from parent } } @@ -261,7 +261,7 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat { var defaultLanguageTabs = TabController.Instance.GetTabsByPortal(tab.PortalID).WithCulture(PortalSettings.Current.DefaultLanguage, true).AsList(); defaultLanguageSelectedTab = defaultLanguageTabs[defaultLanguageTabs.Count]; - + // get the last tab } } @@ -269,7 +269,7 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat relativeToTab = defaultLanguageSelectedTab; } } - + if (location != TabRelativeLocation.NOTSET) { // Check Host tab - don't allow adding before or after @@ -280,13 +280,13 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat TabInfo parentTab = GetParentTab(relativeToTab, location); string permissionList = "ADD,COPY,EDIT,MANAGE"; - + // Check permissions for Page Editors when moving or inserting if (!PortalSecurity.IsInRole("Administrators")) { if ((parentTab == null) || !TabPermissionController.HasTabPermission(parentTab.TabPermissions, permissionList)) { - throw new DotNetNukeException( + throw new DotNetNukeException( "You do not have permissions to add or move pages to this location. You can only add or move pages as children of pages you can edit.", DotNetNukeErrorCode.PageEditorPermissionError); } @@ -310,7 +310,7 @@ public static int SaveTabInfoObject(TabInfo tab, TabInfo relativeToTab, TabRelat } tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - + // check whether have conflict between tab path and portal alias. if (TabController.IsDuplicateWithPortalAlias(PortalSettings.Current.PortalId, tab.TabPath)) { @@ -432,20 +432,20 @@ public static bool Validate_IsCircularReference(int portalID, int tabID) { return false; } - + if (objtab.Level == 0) { return false; } - + if (tabID == objtab.ParentId) { return true; } - + return Validate_IsCircularReference(portalID, objtab.ParentId); } - + return false; } @@ -477,10 +477,10 @@ public static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, Tab { roleId = role.RoleID; } - + break; } - + if (roleId != int.MinValue && !tab.TabPermissions.Cast().Any(p => p.RoleID == roleId @@ -510,29 +510,29 @@ public DotNetNukeException() { } - public DotNetNukeException(string message) + public DotNetNukeException(string message) : base(message) { } - public DotNetNukeException(string message, Exception innerException) + public DotNetNukeException(string message, Exception innerException) : base(message, innerException) { } - public DotNetNukeException(string message, DotNetNukeErrorCode errorCode) + public DotNetNukeException(string message, DotNetNukeErrorCode errorCode) : base(message) { this._ErrorCode = errorCode; } - public DotNetNukeException(string message, Exception innerException, DotNetNukeErrorCode errorCode) + public DotNetNukeException(string message, Exception innerException, DotNetNukeErrorCode errorCode) : base(message, innerException) { this._ErrorCode = errorCode; } - public DotNetNukeException(SerializationInfo info, StreamingContext context) + public DotNetNukeException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs index 42de159479a..74f936ca721 100644 --- a/DNN Platform/DotNetNuke.Web/UI/Utilities.cs +++ b/DNN Platform/DotNetNuke.Web/UI/Utilities.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.Web.UI using FileInfo = DotNetNuke.Services.FileSystem.FileInfo; public class Utilities - { + { public static void ApplySkin(Control telerikControl) { ApplySkin(telerikControl, string.Empty, string.Empty, string.Empty); @@ -33,11 +33,6 @@ 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) { @@ -66,38 +61,38 @@ public static void ApplySkin(Control telerikControl, string fallBackEmbeddedSkin controlName = controlName.Substring(3); } } - + string skinVirtualFolder = string.Empty; - if (PortalSettings.Current != null) - { - skinVirtualFolder = PortalSettings.Current.ActiveTab.SkinPath.Replace('\\', '/').Replace("//", "/"); - } - else - { - skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/skins/_default/Aphelia"); // developer skin Aphelia - } - + if (PortalSettings.Current != null) + { + skinVirtualFolder = PortalSettings.Current.ActiveTab.SkinPath.Replace('\\', '/').Replace("//", "/"); + } + else + { + skinVirtualFolder = telerikControl.ResolveUrl("~/Portals/_default/skins/_default/Aphelia"); // developer skin Aphelia + } + string skinName = string.Empty; string webControlSkinName = string.Empty; if (skinProperty != null) { var v = skinProperty.GetValue(telerikControl, null); - if (v != null) - { - webControlSkinName = v.ToString(); + if (v != null) + { + webControlSkinName = v.ToString(); } } - - if (string.IsNullOrEmpty(webControlSkinName)) - { - webControlSkinName = "default"; - } - + + if (string.IsNullOrEmpty(webControlSkinName)) + { + webControlSkinName = "default"; + } + if (skinVirtualFolder.EndsWith("/")) { skinVirtualFolder = skinVirtualFolder.Substring(0, skinVirtualFolder.Length - 1); } - + int lastIndex = skinVirtualFolder.LastIndexOf("/"); if (lastIndex > -1 && skinVirtualFolder.Length > lastIndex) { @@ -259,7 +254,7 @@ public static string GetOnClientClickConfirm(Control ctrl, string message) public static string GetOnClientClickConfirm(Control ctrl, MessageWindowParameters message) { AddMessageWindow(ctrl); - + // function(text, mozEvent, oWidth, oHeight, callerObj, oTitle) return string.Format("return postBackConfirm('{0}', event, '{1}', '{2}', '', '{3}');", message.Message, message.WindowWidth, message.WindowHeight, message.Title); } @@ -271,7 +266,7 @@ public static string GetViewStateAsString(object value, string defaultValue) { _Value = Convert.ToString(value); } - + return _Value; } @@ -283,6 +278,11 @@ public static void RegisterAlertOnPageLoad(Control ctrl, string message) public static void RegisterAlertOnPageLoad(Control ctrl, MessageWindowParameters message) { ctrl.Page.ClientScript.RegisterClientScriptBlock(ctrl.GetType(), ctrl.ID + "_AlertOnPageLoad", GetClientAlert(ctrl, message), true); - } + } + + private static void AddMessageWindow(Control ctrl) + { + ClientResourceManager.RegisterScript(ctrl.Page, ctrl.ResolveUrl("~/js/dnn.postbackconfirm.js")); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs index dd5da6e7575..d009e6a184b 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnButton.cs @@ -10,14 +10,14 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnButton : Button, ILocalizable { - private bool _Localize = true; - + private bool _Localize = true; + public DnnButton() { this.CssClass = "CommandButton"; this.DisabledCssClass = "CommandButtonDisabled"; - } - + } + [Bindable(true)] [Category("Appearance")] [DefaultValue("")] @@ -28,7 +28,7 @@ public string ConfirmMessage { return this.ViewState["ConfirmMessage"] == null ? string.Empty : this.ViewState["ConfirmMessage"].ToString(); } - + set { this.ViewState["ConfirmMessage"] = value; @@ -45,13 +45,13 @@ public string ConfirmMessage { return this.ViewState["DisabledCssClass"] == null ? string.Empty : this.ViewState["DisabledCssClass"].ToString(); } - + set { this.ViewState["DisabledCssClass"] = value; } - } - + } + public bool Localize { get @@ -60,10 +60,10 @@ public bool Localize { return false; } - + return this._Localize; } - + set { this._Localize = value; @@ -100,8 +100,8 @@ public virtual void LocalizeStrings() } } } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -118,7 +118,7 @@ protected override void OnPreRender(EventArgs e) { msg = Utilities.GetLocalizedStringFromParent(this.ConfirmMessage, this); } - + // must be done before render this.OnClientClick = Utilities.GetOnClientClickConfirm(this, msg); } @@ -128,6 +128,6 @@ protected override void Render(HtmlTextWriter writer) { this.LocalizeStrings(); base.Render(writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs index 468f45e39f4..de48d96a46e 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnCheckBox.cs @@ -14,7 +14,7 @@ public string CommandArgument { return Convert.ToString(this.ViewState["CommandArgument"]); } - + set { this.ViewState["CommandArgument"] = value; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs index 42f5e46ae27..f29cc6890cb 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownList.cs @@ -1,17 +1,15 @@ -// 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 DotNetNuke.Web.UI.WebControls { using System; using System.Collections.Generic; using System.ComponentModel; - using System.Runtime.Serialization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; - + using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Framework; @@ -20,25 +18,18 @@ namespace DotNetNuke.Web.UI.WebControls using DotNetNuke.Web.Client; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Web.UI.WebControls.Extensions; - - [DataContract] - public class DnnDropDownListState - { - [DataMember(Name = "selectedItem")] - public SerializableKeyValuePair SelectedItem; - } [ToolboxData("<{0}:DnnDropDownList runat='server'>")] public class DnnDropDownList : Panel, INamingContainer - { + { private static readonly object EventSelectionChanged = new object(); private readonly Lazy _options = new Lazy(() => new DnnDropDownListOptions()); private DnnGenericHiddenField _stateControl; - private HtmlAnchor _selectedValue; - + private HtmlAnchor _selectedValue; + /// /// Occurs when the selection from the list control changes between posts to the server. /// @@ -48,13 +39,13 @@ public event EventHandler SelectionChanged { this.Events.AddHandler(EventSelectionChanged, value); } - + remove { this.Events.RemoveHandler(EventSelectionChanged, value); } - } - + } + public override ControlCollection Controls { get @@ -65,83 +56,63 @@ public override ControlCollection Controls } /// - /// Gets or sets the selected item in the control, or selects the item in the control. + /// Gets when this method returns, contains the 32-bit signed integer value equivalent to the number contained in + /// SelectedItem.Value, if the conversion succeeded, or Null.NullInteger if the conversion failed. /// - public ListItem SelectedItem + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int SelectedItemValueAsInt { get { - if (this.StateControl.TypedValue != null && this.StateControl.TypedValue.SelectedItem != null) + if (this.SelectedItem != null && !string.IsNullOrEmpty(this.SelectedItem.Value)) { - return new ListItem { Text = this.StateControl.TypedValue.SelectedItem.Value, Value = this.StateControl.TypedValue.SelectedItem.Key }; + int valueAsInt; + var parsed = int.TryParse(this.SelectedItem.Value, out valueAsInt); + return parsed ? valueAsInt : Null.NullInteger; } - - return null; - } - - set - { - 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; + return Null.NullInteger; } } - private HtmlAnchor SelectedValue + public ItemListServicesOptions Services { get { - this.EnsureChildControls(); - return this._selectedValue; + return this.Options.Services; } } - private bool UseUndefinedItem + /// + /// Gets register a list of JavaScript methods that are executed when the selection from the list control changes on the client. + /// + public List OnClientSelectionChanged { get { - return this.ViewState.GetValue("UseUndefinedItem", false); - } - - set - { - this.ViewState.SetValue("UseUndefinedItem", value, false); + return this.Options.OnClientSelectionChanged; } - } + } /// - /// Gets when this method returns, contains the 32-bit signed integer value equivalent to the number contained in - /// SelectedItem.Value, if the conversion succeeded, or Null.NullInteger if the conversion failed. + /// Gets or sets the selected item in the control, or selects the item in the control. /// - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public int SelectedItemValueAsInt + public ListItem SelectedItem { get { - if (this.SelectedItem != null && !string.IsNullOrEmpty(this.SelectedItem.Value)) + if (this.StateControl.TypedValue != null && this.StateControl.TypedValue.SelectedItem != null) { - int valueAsInt; - var parsed = int.TryParse(this.SelectedItem.Value, out valueAsInt); - return parsed ? valueAsInt : Null.NullInteger; + return new ListItem { Text = this.StateControl.TypedValue.SelectedItem.Value, Value = this.StateControl.TypedValue.SelectedItem.Key }; } - - return Null.NullInteger; + + return null; + } + + set + { + this.StateControl.TypedValueOrDefault.SelectedItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); } } @@ -155,7 +126,7 @@ public ListItem UndefinedItem { return this.FirstItem; } - + set { this.FirstItem = value; @@ -172,7 +143,7 @@ public ListItem FirstItem { return (this.Options.ItemList.FirstItem == null) ? null : new ListItem(this.Options.ItemList.FirstItem.Value, this.Options.ItemList.FirstItem.Key); } - + set { this.Options.ItemList.FirstItem = (value == null) ? null : new SerializableKeyValuePair(value.Value, value.Text); @@ -180,14 +151,6 @@ public ListItem FirstItem } } - public ItemListServicesOptions Services - { - get - { - return this.Options.Services; - } - } - /// /// Sets dropDownList Caption when no Item is selected. /// @@ -217,7 +180,7 @@ public bool AutoPostBack { return this.ViewState.GetValue("AutoPostBack", false); } - + set { this.ViewState.SetValue("AutoPostBack", value, false); @@ -233,7 +196,7 @@ public virtual bool CausesValidation { return this.ViewState.GetValue("CausesValidation", false); } - + set { this.ViewState.SetValue("CausesValidation", value, false); @@ -249,7 +212,7 @@ public virtual string ValidationGroup { return this.ViewState.GetValue("ValidationGroup", string.Empty); } - + set { this.ViewState.SetValue("ValidationGroup", value, string.Empty); @@ -257,32 +220,60 @@ public virtual string ValidationGroup } /// - /// Gets register a list of JavaScript methods that are executed when the selection from the list control changes on the client. + /// Gets or sets when the tree view in drop down has multiple level nodes, and the initial selected item is a child node. + /// we need expand its parent nodes to make it selected. /// - public List OnClientSelectionChanged + public string ExpandPath { get { - return this.Options.OnClientSelectionChanged; + return ClientAPI.GetClientVariable(this.Page, this.ClientID + "_expandPath"); + } + + set + { + ClientAPI.RegisterClientVariable(this.Page, this.ClientID + "_expandPath", value, true); } } - /// - /// Gets or sets when the tree view in drop down has multiple level nodes, and the initial selected item is a child node. - /// we need expand its parent nodes to make it selected. - /// - public string ExpandPath + internal DnnDropDownListOptions Options { get { - return ClientAPI.GetClientVariable(this.Page, this.ClientID + "_expandPath"); + 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 { - ClientAPI.RegisterClientVariable(this.Page, this.ClientID + "_expandPath", value, true); + this.ViewState.SetValue("UseUndefinedItem", value, false); } - } + } internal static void RegisterClientScript(Page page, string skin) { @@ -291,7 +282,7 @@ internal static void RegisterClientScript(Page page, string 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"); @@ -303,7 +294,7 @@ internal static void RegisterClientScript(Page page, string skin) ClientResourceManager.RegisterScript(page, "~/Resources/Shared/scripts/TreeView/dnn.DynamicTreeView.js"); ClientResourceManager.RegisterScript(page, "~/Resources/Shared/Components/DropDownList/dnn.DropDownList.js"); } - + protected override void CreateChildControls() { this.Controls.Clear(); @@ -346,10 +337,10 @@ protected virtual void OnSelectionChanged(EventArgs e) { return; } - + eventHandler(this, e); - } - + } + private static string LocalizeString(string key) { return Localization.GetString(key, Localization.SharedResourceFile); @@ -366,20 +357,20 @@ private string GetPostBackScript() this.Attributes.Remove("onchange"); } } - + var options = new PostBackOptions(this, string.Empty); if (this.CausesValidation) { options.PerformValidation = true; options.ValidationGroup = this.ValidationGroup; } - + if (this.Page.Form != null) { options.AutoPostBack = true; options.TrackFocus = true; } - + return script.Append(this.Page.ClientScript.GetPostBackEventReference(options), "; "); } @@ -422,6 +413,6 @@ private void RegisterStartupScript() { this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "DnnDropDownList", script, true); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListState.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListState.cs new file mode 100644 index 00000000000..3193b4cd5f7 --- /dev/null +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnDropDownListState.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Web.UI.WebControls +{ + using System.Runtime.Serialization; + using DotNetNuke.Common; + + [DataContract] + public class DnnDropDownListState + { + [DataMember(Name = "selectedItem")] + public SerializableKeyValuePair SelectedItem; + } +} diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs index 03742168353..39fc41dc2c3 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileDropDownList.cs @@ -23,7 +23,7 @@ public class DnnFileDropDownList : DnnDropDownList /// /// Gets or sets the selected Folder in the control, or selects the Folder in the control. /// - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IFileInfo SelectedFile { @@ -32,7 +32,7 @@ public IFileInfo SelectedFile var fileId = this.SelectedItemValueAsInt; return (fileId == Null.NullInteger) ? null : FileManager.Instance.GetFile(fileId); } - + set { this.SelectedItem = (value != null) ? new ListItem() { Text = value.FileName, Value = value.FileId.ToString(CultureInfo.InvariantCulture) } : null; @@ -45,7 +45,7 @@ public int FolderId { return this.Services.Parameters.ContainsKey("parentId") ? Convert.ToInt32(this.Services.Parameters["parentId"]) : Null.NullInteger; } - + set { this.Services.Parameters["parentId"] = value.ToString(); @@ -57,7 +57,9 @@ public string Filter get { return this.Services.Parameters.ContainsKey("filter") ? this.Services.Parameters["filter"] : string.Empty; } set { this.Services.Parameters["filter"] = value; } } - + + public bool IncludeNoneSpecificItem { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -83,7 +85,5 @@ protected override void OnPreRender(EventArgs e) 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 30c525347e9..b6fc350e2e0 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileEditControl.cs @@ -10,11 +10,11 @@ namespace DotNetNuke.Web.UI.WebControls using DotNetNuke.UI.WebControls; public class DnnFileEditControl : IntegerEditControl - { - private DnnFilePickerUploader _fileControl; - - // private DnnFilePicker _fileControl; - + { + private DnnFilePickerUploader _fileControl; + + // private DnnFilePicker _fileControl; + /// ----------------------------------------------------------------------------- /// /// Gets or sets the current file extension filter. @@ -27,8 +27,8 @@ public class DnnFileEditControl : IntegerEditControl /// Gets or sets the current file path. /// /// ----------------------------------------------------------------------------- - public string FilePath { get; set; } - + public string FilePath { get; set; } + /// ----------------------------------------------------------------------------- /// /// Loads the Post Back Data and determines whether the value has change. @@ -39,14 +39,14 @@ public class DnnFileEditControl : IntegerEditControl /// this method as the Framework calls it for us. /// /// A key to the PostBack Data to load. - /// A name value collection of postback data. + /// 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)) @@ -54,10 +54,10 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.Value = postedValue; dataChanged = true; } - + return dataChanged; - } - + } + /// ----------------------------------------------------------------------------- /// /// Creates the control contained within this control. @@ -120,6 +120,6 @@ protected override void OnPreRender(EventArgs e) protected override void RenderEditMode(HtmlTextWriter writer) { this.RenderChildren(writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs index 1a5be592cb7..bf250daff66 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePicker.cs @@ -26,12 +26,31 @@ namespace DotNetNuke.Web.UI.WebControls /// public class DnnFilePicker : CompositeControl, ILocalizable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DnnFilePicker)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DnnFilePicker)); + private Panel _pnlContainer; private Panel _pnlLeftDiv; private Panel _pnlFolder; - + + private Label _lblFolder; + private DropDownList _cboFolders; + private Panel _pnlFile; + private Label _lblFile; + private DropDownList _cboFiles; + private Panel _pnlUpload; + private HtmlInputFile _txtFile; + private Panel _pnlButtons; + private LinkButton _cmdCancel; + private LinkButton _cmdSave; + private LinkButton _cmdUpload; + private Panel _pnlMessage; + private Label _lblMessage; + private Panel _pnlRightDiv; + private Image _imgPreview; + private bool _localize = true; + private int _maxHeight = 100; + private int _maxWidth = 135; + /// /// Represents a possible mode for the File Control. /// @@ -51,25 +70,7 @@ protected enum FileControlMode /// The File Control is in the Preview mode /// Preview, - } - private Label _lblFolder; - private DropDownList _cboFolders; - private Panel _pnlFile; - private Label _lblFile; - private DropDownList _cboFiles; - private Panel _pnlUpload; - private HtmlInputFile _txtFile; - private Panel _pnlButtons; - private LinkButton _cmdCancel; - private LinkButton _cmdSave; - private LinkButton _cmdUpload; - private Panel _pnlMessage; - private Label _lblMessage; - private Panel _pnlRightDiv; - private Image _imgPreview; - private bool _localize = true; - private int _maxHeight = 100; - private int _maxWidth = 135; + } public int MaxHeight { @@ -77,7 +78,7 @@ public int MaxHeight { return this._maxHeight; } - + set { this._maxHeight = value; @@ -90,33 +91,13 @@ public int MaxWidth { return this._maxWidth; } - + set { this._maxWidth = value; } } - - /// - /// Gets a value indicating whether gets whether the control is on a Host or Portal Tab. - /// - /// A Boolean. - protected bool IsHost - { - get - { - var isHost = Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); - - // if not host tab but current edit user is a host user, then return true - if (!isHost && this.User != null && this.User.IsSuperUser) - { - isHost = true; - } - return isHost; - } - } - /// /// Gets or sets the class to be used for the Labels. /// @@ -131,7 +112,7 @@ public string CommandCssClass var cssClass = Convert.ToString(this.ViewState["CommandCssClass"]); return string.IsNullOrEmpty(cssClass) ? "dnnSecondaryAction" : cssClass; } - + set { this.ViewState["CommandCssClass"] = value; @@ -151,81 +132,13 @@ public string FileFilter { return this.ViewState["FileFilter"] != null ? (string)this.ViewState["FileFilter"] : string.Empty; } - - set - { - this.ViewState["FileFilter"] = value; - } - } - /// - /// Gets or sets the current mode of the control. - /// - /// - /// Defaults to FileControlMode.Normal. - /// - /// A FileControlMode enum. - protected FileControlMode Mode - { - get - { - return this.ViewState["Mode"] == null ? FileControlMode.Normal : (FileControlMode)this.ViewState["Mode"]; - } - set { - this.ViewState["Mode"] = value; - } - } - - /// - /// Gets the root folder for the control. - /// - /// A String. - protected string ParentFolder - { - get - { - return this.IsHost ? Globals.HostMapPath : this.PortalSettings.HomeDirectoryMapPath; - } - } - - /// - /// Gets the file PortalId to use. - /// - /// - /// Defaults to PortalSettings.PortalId. - /// - /// An Integer. - protected int PortalId - { - get - { - if ((this.Page.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) - { - return int.Parse(this.Page.Request.QueryString["pid"]); - } - - if (!this.IsHost) - { - return this.PortalSettings.PortalId; - } - - return Null.NullInteger; + this.ViewState["FileFilter"] = value; } } - /// - /// Gets the current Portal Settings. - /// - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - /// /// Gets or sets the FileID for the control. /// @@ -243,13 +156,13 @@ public int FileID { fileId = int.Parse(this._cboFiles.SelectedItem.Value); } - + this.ViewState["FileID"] = fileId; } - + return Convert.ToInt32(this.ViewState["FileID"]); } - + set { this.EnsureChildControls(); @@ -275,7 +188,7 @@ public string FilePath { return Convert.ToString(this.ViewState["FilePath"]); } - + set { this.ViewState["FilePath"] = value; @@ -295,7 +208,7 @@ public bool UsePersonalFolder { return this.ViewState["UsePersonalFolder"] != null && Convert.ToBoolean(this.ViewState["UsePersonalFolder"]); } - + set { this.ViewState["UsePersonalFolder"] = value; @@ -313,7 +226,7 @@ public string LabelCssClass var cssClass = Convert.ToString(this.ViewState["LabelCssClass"]); return string.IsNullOrEmpty(cssClass) ? string.Empty : cssClass; } - + set { this.ViewState["LabelCssClass"] = value; @@ -327,7 +240,7 @@ public string Permissions var permissions = Convert.ToString(this.ViewState["Permissions"]); return string.IsNullOrEmpty(permissions) ? "BROWSE,ADD" : permissions; } - + set { this.ViewState["Permissions"] = value; @@ -347,7 +260,7 @@ public bool Required { return this.ViewState["Required"] != null && Convert.ToBoolean(this.ViewState["Required"]); } - + set { this.ViewState["Required"] = value; @@ -360,7 +273,7 @@ public bool ShowFolders { return this.ViewState["ShowFolders"] == null || Convert.ToBoolean(this.ViewState["ShowFolders"]); } - + set { this.ViewState["ShowFolders"] = value; @@ -380,22 +293,22 @@ public bool ShowUpLoad { return this.ViewState["ShowUpLoad"] == null || Convert.ToBoolean(this.ViewState["ShowUpLoad"]); } - + set { this.ViewState["ShowUpLoad"] = value; } } - public UserInfo User { get; set; } - + public UserInfo User { get; set; } + public bool Localize { get { return this._localize; } - + set { this._localize = value; @@ -404,10 +317,98 @@ public bool Localize public string LocalResourceFile { get; set; } + /// + /// Gets a value indicating whether gets whether the control is on a Host or Portal Tab. + /// + /// A Boolean. + protected bool IsHost + { + get + { + var isHost = Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID); + + // if not host tab but current edit user is a host user, then return true + if (!isHost && this.User != null && this.User.IsSuperUser) + { + isHost = true; + } + + return isHost; + } + } + + /// + /// Gets the root folder for the control. + /// + /// A String. + protected string ParentFolder + { + get + { + return this.IsHost ? Globals.HostMapPath : this.PortalSettings.HomeDirectoryMapPath; + } + } + + /// + /// Gets the file PortalId to use. + /// + /// + /// Defaults to PortalSettings.PortalId. + /// + /// An Integer. + protected int PortalId + { + get + { + if ((this.Page.Request.QueryString["pid"] != null) && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) + { + return int.Parse(this.Page.Request.QueryString["pid"]); + } + + if (!this.IsHost) + { + return this.PortalSettings.PortalId; + } + + return Null.NullInteger; + } + } + + /// + /// Gets the current Portal Settings. + /// + protected PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + /// + /// Gets or sets the current mode of the control. + /// + /// + /// Defaults to FileControlMode.Normal. + /// + /// A FileControlMode enum. + protected FileControlMode Mode + { + get + { + return this.ViewState["Mode"] == null ? FileControlMode.Normal : (FileControlMode)this.ViewState["Mode"]; + } + + set + { + this.ViewState["Mode"] = value; + } + } + public virtual void LocalizeStrings() { - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -445,7 +446,101 @@ protected override void CreateChildControls() base.CreateChildControls(); } - + + /// + /// OnPreRender runs just before the control is rendered. + /// + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (this._cboFolders.Items.Count > 0) + { + // Configure Labels + this._lblFolder.Text = Utilities.GetLocalizedString("Folder"); + this._lblFolder.CssClass = this.LabelCssClass; + this._lblFile.Text = Utilities.GetLocalizedString("File"); + this._lblFile.CssClass = this.LabelCssClass; + + // select folder + string fileName; + string folderPath; + if (!string.IsNullOrEmpty(this.FilePath)) + { + fileName = this.FilePath.Substring(this.FilePath.LastIndexOf("/") + 1); + folderPath = string.IsNullOrEmpty(fileName) ? this.FilePath : this.FilePath.Replace(fileName, string.Empty); + } + else + { + fileName = this.FilePath; + folderPath = string.Empty; + } + + if (this._cboFolders.Items.FindByValue(folderPath) != null) + { + this._cboFolders.SelectedIndex = -1; + this._cboFolders.Items.FindByValue(folderPath).Selected = true; + } + + // Get Files + this.LoadFiles(); + if (this._cboFiles.Items.FindByText(fileName) != null) + { + this._cboFiles.Items.FindByText(fileName).Selected = true; + } + + if (this._cboFiles.SelectedItem == null || string.IsNullOrEmpty(this._cboFiles.SelectedItem.Value)) + { + this.FileID = -1; + } + else + { + this.FileID = int.Parse(this._cboFiles.SelectedItem.Value); + } + + if (this._cboFolders.Items.Count > 1 && this.ShowFolders) + { + this._pnlFolder.Visible = true; + } + else + { + this._pnlFolder.Visible = false; + } + + // Configure Mode + switch (this.Mode) + { + case FileControlMode.Normal: + this._pnlFile.Visible = true; + this._pnlUpload.Visible = false; + this._pnlRightDiv.Visible = true; + this.ShowImage(); + + if ((FolderPermissionController.HasFolderPermission(this.PortalId, this._cboFolders.SelectedItem.Value, "ADD") || this.IsUserFolder(this._cboFolders.SelectedItem.Value)) && this.ShowUpLoad) + { + this.ShowButton(this._cmdUpload, "Upload"); + } + + break; + + case FileControlMode.UpLoadFile: + this._pnlFile.Visible = false; + this._pnlUpload.Visible = true; + this._pnlRightDiv.Visible = false; + this.ShowButton(this._cmdSave, "Save"); + this.ShowButton(this._cmdCancel, "Cancel"); + break; + } + } + else + { + this._lblMessage.Text = Utilities.GetLocalizedString("NoPermission"); + } + + // Show message Row + this._pnlMessage.Visible = !string.IsNullOrEmpty(this._lblMessage.Text); + } + /// /// AddButton adds a button to the Command Row. /// @@ -568,7 +663,7 @@ private void LoadFiles() { effectivePortalId = PortalController.GetEffectivePortalId(this.PortalId); } - + this._cboFiles.DataSource = Globals.GetFileList(effectivePortalId, this.FileFilter, !this.Required, this._cboFolders.SelectedItem.Value); this._cboFiles.DataBind(); } @@ -601,13 +696,13 @@ private void LoadFolders() var folders = FolderManager.Instance.GetFolders(this.PortalId, "READ,ADD", user.UserID); foreach (FolderInfo folder in folders) { - var folderItem = new ListItem - { + 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); } @@ -656,7 +751,7 @@ private void ShowButton(LinkButton button, string command) { button.Text = Utilities.GetLocalizedString(command); } - + AJAX.RegisterPostBackControl(button); this._pnlButtons.Visible = true; } @@ -689,102 +784,8 @@ private void ShowImage() this._pnlRightDiv.Controls.Add(imageHolderPanel); this._pnlRightDiv.Visible = true; } - } - - /// - /// OnPreRender runs just before the control is rendered. - /// - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (this._cboFolders.Items.Count > 0) - { - // Configure Labels - this._lblFolder.Text = Utilities.GetLocalizedString("Folder"); - this._lblFolder.CssClass = this.LabelCssClass; - this._lblFile.Text = Utilities.GetLocalizedString("File"); - this._lblFile.CssClass = this.LabelCssClass; - - // select folder - string fileName; - string folderPath; - if (!string.IsNullOrEmpty(this.FilePath)) - { - fileName = this.FilePath.Substring(this.FilePath.LastIndexOf("/") + 1); - folderPath = string.IsNullOrEmpty(fileName) ? this.FilePath : this.FilePath.Replace(fileName, string.Empty); - } - else - { - fileName = this.FilePath; - folderPath = string.Empty; - } - - if (this._cboFolders.Items.FindByValue(folderPath) != null) - { - this._cboFolders.SelectedIndex = -1; - this._cboFolders.Items.FindByValue(folderPath).Selected = true; - } - - // Get Files - this.LoadFiles(); - if (this._cboFiles.Items.FindByText(fileName) != null) - { - this._cboFiles.Items.FindByText(fileName).Selected = true; - } - - if (this._cboFiles.SelectedItem == null || string.IsNullOrEmpty(this._cboFiles.SelectedItem.Value)) - { - this.FileID = -1; - } - else - { - this.FileID = int.Parse(this._cboFiles.SelectedItem.Value); - } - - if (this._cboFolders.Items.Count > 1 && this.ShowFolders) - { - this._pnlFolder.Visible = true; - } - else - { - this._pnlFolder.Visible = false; - } - - // Configure Mode - switch (this.Mode) - { - case FileControlMode.Normal: - this._pnlFile.Visible = true; - this._pnlUpload.Visible = false; - this._pnlRightDiv.Visible = true; - this.ShowImage(); - - if ((FolderPermissionController.HasFolderPermission(this.PortalId, this._cboFolders.SelectedItem.Value, "ADD") || this.IsUserFolder(this._cboFolders.SelectedItem.Value)) && this.ShowUpLoad) - { - this.ShowButton(this._cmdUpload, "Upload"); - } - - break; - - case FileControlMode.UpLoadFile: - this._pnlFile.Visible = false; - this._pnlUpload.Visible = true; - this._pnlRightDiv.Visible = false; - this.ShowButton(this._cmdSave, "Save"); - this.ShowButton(this._cmdCancel, "Cancel"); - break; - } - } - else - { - this._lblMessage.Text = Utilities.GetLocalizedString("NoPermission"); - } + } - // Show message Row - this._pnlMessage.Visible = !string.IsNullOrEmpty(this._lblMessage.Text); - } - private void CancelUpload(object sender, EventArgs e) { this.Mode = FileControlMode.Normal; @@ -835,7 +836,7 @@ private void SaveFile(object sender, EventArgs e) { // Add User folder var user = this.User ?? UserController.Instance.GetCurrentUserInfo(); - + // fix user's portal id user.PortalID = this.PortalId; folder = ((FolderManager)folderManager).AddUserFolder(user); @@ -878,13 +879,13 @@ private void SaveFile(object sender, EventArgs e) this.SetFilePath(fileName); } } - + this.Mode = FileControlMode.Normal; } private void UploadFile(object sender, EventArgs e) { this.Mode = FileControlMode.UpLoadFile; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs index b3d12e336df..0f39d9634ce 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFilePickerUploader.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 DotNetNuke.Web.UI.WebControls { using System; @@ -25,18 +24,17 @@ namespace DotNetNuke.Web.UI.WebControls using DotNetNuke.Web.Common; public class DnnFilePickerUploader : UserControl, IFilePickerUploader - { + { protected DnnFileDropDownList FilesComboBox; protected DnnFolderDropDownList FoldersComboBox; + protected Label FoldersLabel; + protected DnnFileUpload FileUploadControl; private const string MyFileName = "filepickeruploader.ascx"; private int? _portalId = null; - private string _fileFilter; private string _folderPath = string.Empty; - private bool _folderPathSet = false; - protected Label FoldersLabel; - protected DnnFileUpload FileUploadControl; - + private bool _folderPathSet = false; + public bool UsePersonalFolder { get; set; } public string FilePath @@ -76,38 +74,6 @@ 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 @@ -139,7 +105,7 @@ public string FolderPath ? this.FoldersComboBox.SelectedFolder.FolderPath : string.Empty; } - + set { this._folderPath = value; @@ -153,7 +119,7 @@ public string FileFilter { return this._fileFilter; } - + set { this._fileFilter = value; @@ -178,7 +144,7 @@ public int PortalId { return !this._portalId.HasValue ? PortalSettings.Current.PortalId : this._portalId.Value; } - + set { this._portalId = value; @@ -189,8 +155,40 @@ public bool SupportHost { get { return this.FileUploadControl.SupportHost; } set { this.FileUploadControl.SupportHost = value; } - } - + } + + 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)); + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -223,18 +221,18 @@ 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,16 +247,16 @@ 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; } base.OnPreRender(e); - } - + } + private void LoadFolders() { if (this.UsePersonalFolder) @@ -293,6 +291,6 @@ private void LoadFolders() this.FoldersComboBox.Enabled = !this.UsePersonalFolder; this.FoldersLabel.Visible = this.UsePersonalFolder; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs index 8c5fe687494..2d76abf100f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUpload.cs @@ -139,7 +139,7 @@ private void RegisterStartupScript() { this.Options.FolderPicker.Services.Parameters["portalId"] = portalSettings.PortalId.ToString(); } - + this.Options.FolderPicker.Services.GetTreeMethod = "ItemListService/GetFolders"; this.Options.FolderPicker.Services.GetNodeDescendantsMethod = "ItemListService/GetFolderDescendants"; this.Options.FolderPicker.Services.SearchTreeMethod = "ItemListService/SearchFolders"; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs index bbb92fb3fc8..f619ed65e82 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadOptions.cs @@ -1,105 +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 - namespace DotNetNuke.Web.UI.WebControls { using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; - + using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; - - [DataContract] - public class DnnFileUploadResources - { - [DataMember(Name = "title")] - public string Title; - - [DataMember(Name = "decompressLabel")] - public string DecompressLabel; - - [DataMember(Name = "uploadToFolderLabel")] - public string UploadToFolderLabel; - - [DataMember(Name = "dragAndDropAreaTitle")] - public string DragAndDropAreaTitle; - - [DataMember(Name = "uploadFileMethod")] - public string UploadFileMethod; - - [DataMember(Name = "uploadFromWebMethod")] - public string UploadFromWebMethod; - - [DataMember(Name = "closeButtonText")] - public string CloseButtonText; - - [DataMember(Name = "uploadFromWebButtonText")] - public string UploadFromWebButtonText; - - [DataMember(Name = "decompressingFile")] - public string DecompressingFile; - - [DataMember(Name = "fileIsTooLarge")] - public string FileIsTooLarge; - - [DataMember(Name = "fileUploadCancelled")] - public string FileUploadCancelled; - - [DataMember(Name = "fileUploadFailed")] - public string FileUploadFailed; - - [DataMember(Name = "fileUploaded")] - public string FileUploaded; - - [DataMember(Name = "emptyFileUpload")] - public string EmptyFileUpload; - - [DataMember(Name = "fileAlreadyExists")] - public string FileAlreadyExists; - - [DataMember(Name = "uploadStopped")] - public string UploadStopped; - - [DataMember(Name = "urlTooltip")] - public string UrlTooltip; - - [DataMember(Name = "keepButtonText")] - public string KeepButtonText; - - [DataMember(Name = "replaceButtonText")] - public string ReplaceButtonText; - - [DataMember(Name = "tooManyFiles")] - public string TooManyFiles; - - [DataMember(Name = "invalidFileExtensions")] - public string InvalidFileExtensions; - - [DataMember(Name = "unzipFilePromptTitle")] - public string UnzipFilePromptTitle; - - [DataMember(Name = "unzipFileFailedPromptBody")] - public string UnzipFileFailedPromptBody; - - [DataMember(Name = "unzipFileSuccessPromptBody")] - public string UnzipFileSuccessPromptBody; - - [DataMember(Name = "errorDialogTitle")] - public string ErrorDialogTitle; - } [DataContract] public class DnnFileUploadOptions { [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; @@ -131,6 +49,9 @@ public class DnnFileUploadOptions [DataMember(Name = "folderPath")] public string FolderPath; + private const int DefaultWidth = 780; + private const int DefaultHeight = 630; + private Dictionary _parameters; public DnnFileUploadOptions() @@ -189,8 +110,8 @@ public string ValidationCode if (portalSettings != null) { parameters.Add(portalSettings.UserInfo.UserID); - if (!portalSettings.UserInfo.IsSuperUser) - { + if (!portalSettings.UserInfo.IsSuperUser) + { parameters.Add(portalSettings.PortalId); } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadResources.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadResources.cs new file mode 100644 index 00000000000..6093f506fb2 --- /dev/null +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFileUploadResources.cs @@ -0,0 +1,86 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Web.UI.WebControls +{ + using System.Runtime.Serialization; + + [DataContract] + public class DnnFileUploadResources + { + [DataMember(Name = "title")] + public string Title; + + [DataMember(Name = "decompressLabel")] + public string DecompressLabel; + + [DataMember(Name = "uploadToFolderLabel")] + public string UploadToFolderLabel; + + [DataMember(Name = "dragAndDropAreaTitle")] + public string DragAndDropAreaTitle; + + [DataMember(Name = "uploadFileMethod")] + public string UploadFileMethod; + + [DataMember(Name = "uploadFromWebMethod")] + public string UploadFromWebMethod; + + [DataMember(Name = "closeButtonText")] + public string CloseButtonText; + + [DataMember(Name = "uploadFromWebButtonText")] + public string UploadFromWebButtonText; + + [DataMember(Name = "decompressingFile")] + public string DecompressingFile; + + [DataMember(Name = "fileIsTooLarge")] + public string FileIsTooLarge; + + [DataMember(Name = "fileUploadCancelled")] + public string FileUploadCancelled; + + [DataMember(Name = "fileUploadFailed")] + public string FileUploadFailed; + + [DataMember(Name = "fileUploaded")] + public string FileUploaded; + + [DataMember(Name = "emptyFileUpload")] + public string EmptyFileUpload; + + [DataMember(Name = "fileAlreadyExists")] + public string FileAlreadyExists; + + [DataMember(Name = "uploadStopped")] + public string UploadStopped; + + [DataMember(Name = "urlTooltip")] + public string UrlTooltip; + + [DataMember(Name = "keepButtonText")] + public string KeepButtonText; + + [DataMember(Name = "replaceButtonText")] + public string ReplaceButtonText; + + [DataMember(Name = "tooManyFiles")] + public string TooManyFiles; + + [DataMember(Name = "invalidFileExtensions")] + public string InvalidFileExtensions; + + [DataMember(Name = "unzipFilePromptTitle")] + public string UnzipFilePromptTitle; + + [DataMember(Name = "unzipFileFailedPromptBody")] + public string UnzipFileFailedPromptBody; + + [DataMember(Name = "unzipFileSuccessPromptBody")] + public string UnzipFileSuccessPromptBody; + + [DataMember(Name = "errorDialogTitle")] + public string ErrorDialogTitle; + } +} diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs index 6754d299db8..f44ea9ec81a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFolderDropDownList.cs @@ -25,7 +25,7 @@ public class DnnFolderDropDownList : DnnDropDownList /// /// Gets or sets the selected Folder in the control, or selects the Folder in the control. /// - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IFolderInfo SelectedFolder { @@ -34,7 +34,7 @@ public IFolderInfo SelectedFolder var folderId = this.SelectedItemValueAsInt; return (folderId == Null.NullInteger) ? null : FolderManager.Instance.GetFolder(folderId); } - + set { var folderName = value != null ? value.FolderName : null; @@ -46,7 +46,7 @@ public IFolderInfo SelectedFolder this.SelectedItem = (value != null) ? new ListItem() { Text = folderName, Value = value.FolderID.ToString(CultureInfo.InvariantCulture) } : null; } } - + protected override void OnInit(EventArgs e) { base.OnInit(e); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs index 750ccf2ae3b..8f045920812 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormEditor.cs @@ -33,13 +33,32 @@ public DnnFormEditor() this.ViewStateMode = ViewStateMode.Disabled; } + public bool IsValid + { + get + { + bool isValid = true; + foreach (var item in this.GetAllItems()) + { + item.CheckIsValid(); + if (!item.IsValid) + { + isValid = false; + break; + } + } + + return isValid; + } + } + public object DataSource { get { return this._dataSource; } - + set { if (this._dataSource != value) @@ -55,6 +74,23 @@ public object DataSource public DnnFormMode FormMode { get; set; } + public bool EncryptIds { get; set; } + + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List Items { get; private set; } + + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List Sections { get; private set; } + + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + public List Tabs { get; private set; } + protected string LocalResourceFile { get @@ -71,42 +107,6 @@ protected override HtmlTextWriterTag TagKey } } - public bool EncryptIds { get; set; } - - public bool IsValid - { - get - { - bool isValid = true; - foreach (var item in this.GetAllItems()) - { - item.CheckIsValid(); - if (!item.IsValid) - { - isValid = false; - break; - } - } - - return isValid; - } - } - - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public List Items { get; private set; } - - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public List Sections { get; private set; } - - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public List Tabs { get; private set; } - public override void DataBind() { this.OnDataBinding(EventArgs.Empty); @@ -115,8 +115,8 @@ public override void DataBind() 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) { @@ -136,33 +136,6 @@ internal static void SetUpItems(IEnumerable items, WebControl p } } - private List GetAllItems() - { - var items = new List(); - - // iterate over pages - foreach (DnnFormTab page in this.Tabs) - { - foreach (DnnFormSection section in page.Sections) - { - items.AddRange(section.Items); - } - - items.AddRange(page.Items); - } - - // iterate over section - foreach (DnnFormSection section in this.Sections) - { - items.AddRange(section.Items); - } - - // Add base items - items.AddRange(this.Items); - - return items; - } - protected override void CreateChildControls() { // CreateChildControls re-creates the children (the items) @@ -190,7 +163,7 @@ protected virtual void CreateControlHierarchy(bool useDataSource) this.DataBindItems(useDataSource); } - + protected override void LoadControlState(object state) { if (state != null) @@ -199,6 +172,87 @@ protected override void LoadControlState(object state) } } + protected override void OnInit(EventArgs e) + { + this.Page.RegisterRequiresControlState(this); + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + base.OnInit(e); + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (this.Tabs.Count > 0) + { + const string scriptName = "FormEditorjQuery"; + ClientScriptManager cs = this.Page.ClientScript; + + if (!cs.IsClientScriptBlockRegistered(this.GetType(), scriptName)) + { + // Render Script + var scriptBuilder = new StringBuilder(); + scriptBuilder.Append("\r\n"); + cs.RegisterClientScriptBlock(this.GetType(), scriptName, scriptBuilder.ToString()); + } + } + } + + protected override object SaveControlState() + { + return this._itemCount > 0 ? (object)this._itemCount : null; + } + + private List GetAllItems() + { + var items = new List(); + + // iterate over pages + foreach (DnnFormTab page in this.Tabs) + { + foreach (DnnFormSection section in page.Sections) + { + items.AddRange(section.Items); + } + + items.AddRange(page.Items); + } + + // iterate over section + foreach (DnnFormSection section in this.Sections) + { + items.AddRange(section.Items); + } + + // Add base items + items.AddRange(this.Items); + + return items; + } + private void SetUpSections(List sections, WebControl parentControl) { if (sections.Count > 0) @@ -213,7 +267,7 @@ private void SetUpSections(List sections, WebControl parentContr { resourceKey = section.ID; } - + panel.Text = Localization.GetString(resourceKey, this.LocalResourceFile); panel.Expanded = section.Expanded; @@ -268,7 +322,7 @@ private void SetUpTabs() SetUpItems(formTab.Items, tab, this.LocalResourceFile, this.EncryptIds); } } - } + } private void DataBindItems(bool useDataSource) { @@ -280,7 +334,7 @@ private void DataBindItems(bool useDataSource) { item.LocalResourceFile = this.LocalResourceFile; } - + if (item.FormMode == DnnFormMode.Inherit) { item.FormMode = this.FormMode; @@ -292,62 +346,8 @@ private void DataBindItems(bool useDataSource) item.DataBindItem(useDataSource); } } - - this._itemCount = this.GetAllItems().Count; - } - - protected override void OnInit(EventArgs e) - { - this.Page.RegisterRequiresControlState(this); - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - base.OnInit(e); - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (this.Tabs.Count > 0) - { - const string scriptName = "FormEditorjQuery"; - ClientScriptManager cs = this.Page.ClientScript; - - if (!cs.IsClientScriptBlockRegistered(this.GetType(), scriptName)) - { - // Render Script - var scriptBuilder = new StringBuilder(); - scriptBuilder.Append("\r\n"); - cs.RegisterClientScriptBlock(this.GetType(), scriptName, scriptBuilder.ToString()); - } - } + this._itemCount = this.GetAllItems().Count; } - - protected override object SaveControlState() - { - return this._itemCount > 0 ? (object)this._itemCount : null; - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs index 57e0dc06552..c078b148d4d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormItemBase.cs @@ -29,50 +29,15 @@ protected DnnFormItemBase() this.IsValid = true; this.Validators = new List(); - } + } public object Value { get { return this._value; } set { this._value = value; } - } - - public string DataField { get; set; } - - protected PropertyInfo ChildProperty - { - get - { - Type type = this.Property.PropertyType; - IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); - return props.SingleOrDefault(p => p.Name == this.DataField); - } - } - - protected PortalSettings PortalSettings - { - get { return PortalController.Instance.GetCurrentPortalSettings(); } - } - - protected PropertyInfo Property - { - get - { - Type type = this.DataSource.GetType(); - IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); - return !string.IsNullOrEmpty(this.DataMember) - ? props.SingleOrDefault(p => p.Name == this.DataMember) - : props.SingleOrDefault(p => p.Name == this.DataField); - } } - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } + public string DataField { get; set; } public string DataMember { get; set; } @@ -80,8 +45,6 @@ protected override HtmlTextWriterTag TagKey public bool IsValid { get; private set; } - internal object DataSource { get; set; } - public string OnClientClicked { get; set; } public string LocalResourceFile { get; set; } @@ -96,7 +59,7 @@ public string RequiredMessageSuffix { return this._requiredMessageSuffix; } - + set { this._requiredMessageSuffix = value; @@ -109,19 +72,56 @@ public string ValidationMessageSuffix { return this._validationMessageSuffix; } - + set { this._validationMessageSuffix = value; } } - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Validators { get; private set; } - public string ValidationExpression { get; set; } + public string ValidationExpression { get; set; } + + internal object DataSource { get; set; } + + protected PropertyInfo ChildProperty + { + get + { + Type type = this.Property.PropertyType; + IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); + return props.SingleOrDefault(p => p.Name == this.DataField); + } + } + + protected PortalSettings PortalSettings + { + get { return PortalController.Instance.GetCurrentPortalSettings(); } + } + + protected PropertyInfo Property + { + get + { + Type type = this.DataSource.GetType(); + IList props = new List(type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)); + return !string.IsNullOrEmpty(this.DataMember) + ? props.SingleOrDefault(p => p.Name == this.DataMember) + : props.SingleOrDefault(p => p.Name == this.DataField); + } + } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } public void CheckIsValid() { @@ -172,15 +172,15 @@ 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) + if (this.Required) { label.RequiredField = true; } @@ -191,52 +191,6 @@ 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. @@ -278,7 +232,7 @@ protected void DataBindInternal(string dataField, ref object value) { // ReSharper disable PossibleNullReferenceException value = this.Property.GetValue(this.DataSource, null); - + // ReSharper restore PossibleNullReferenceException } } @@ -292,7 +246,7 @@ protected void DataBindInternal(string dataField, ref object value) { value = this.ChildProperty.GetValue(parentValue, null); } - + // ReSharper restore PossibleNullReferenceException } } @@ -312,13 +266,75 @@ protected void UpdateDataSource(object oldValue, object newValue, string dataFie 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); + } + + protected override void OnInit(EventArgs e) + { + this.Page.RegisterRequiresControlState(this); + base.OnInit(e); + } + + protected override object SaveControlState() + { + return this._value; + } + + 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); + } + } + } + private void UpdateDataSourceInternal(object oldValue, object newValue, string dataField) { if (this.DataSource != null) @@ -392,21 +408,5 @@ private void UpdateDataSourceInternal(object oldValue, object newValue, string d } } } - - protected string LocalizeString(string key) - { - return Localization.GetString(key, this.LocalResourceFile); - } - - protected override void OnInit(EventArgs e) - { - this.Page.RegisterRequiresControlState(this); - base.OnInit(e); - } - - protected override object SaveControlState() - { - return this._value; - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs index c40c0339298..31220f61a76 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLabel.cs @@ -33,18 +33,18 @@ public class DnnFormLabel : Panel protected override void CreateChildControls() { string toolTipText = this.LocalizeString(this.ToolTipKey); - if (string.IsNullOrEmpty(this.CssClass)) - { - this.CssClass = "dnnLabel"; + if (string.IsNullOrEmpty(this.CssClass)) + { + this.CssClass = "dnnLabel"; } - else if (!this.CssClass.Contains("dnnLabel")) - { - this.CssClass += " dnnLabel"; - } - - // var outerPanel = new Panel(); - // outerPanel.CssClass = "dnnLabel"; - // Controls.Add(outerPanel); + else if (!this.CssClass.Contains("dnnLabel")) + { + this.CssClass += " dnnLabel"; + } + + // var outerPanel = new Panel(); + // outerPanel.CssClass = "dnnLabel"; + // Controls.Add(outerPanel); var outerLabel = new System.Web.UI.HtmlControls.HtmlGenericControl { TagName = "label" }; this.Controls.Add(outerLabel); @@ -53,7 +53,7 @@ protected override void CreateChildControls() { label.CssClass += " dnnFormRequired"; } - + outerLabel.Controls.Add(label); var link = new LinkButton { ID = "Link", CssClass = "dnnFormHelp", TabIndex = -1 }; @@ -79,7 +79,7 @@ protected override void CreateChildControls() JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - + // ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs index f9c96b27775..48d357855c3 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormListItemBase.cs @@ -17,7 +17,7 @@ public IEnumerable ListSource { return this._listSource; } - + set { var changed = !Equals(this._listSource, value); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs index a14fdd979ac..6770c0bf816 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormLiteralItem.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnFormLiteralItem : DnnFormItemBase { - public DnnFormLiteralItem() + public DnnFormLiteralItem() : base() { this.ViewStateMode = ViewStateMode.Disabled; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs index 09194c202ec..186f61a18c2 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPanel.cs @@ -23,7 +23,7 @@ protected override void Render(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, "dnnSectionExpanded"); } - + writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write(this.Text); writer.RenderEndTag(); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs index 41eb322dd2b..87dc4d18552 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormPasswordItem.cs @@ -23,7 +23,7 @@ public string TextBoxCssClass { return this.ViewState.GetValue("TextBoxCssClass", string.Empty); } - + set { this.ViewState.SetValue("TextBoxCssClass", value, string.Empty); @@ -36,7 +36,7 @@ public string ContainerCssClass { return this.ViewState.GetValue("ContainerCssClass", string.Empty); } - + set { this.ViewState.SetValue("ContainerCssClass", value, string.Empty); @@ -85,18 +85,13 @@ 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); var options = new DnnPaswordStrengthOptions(); var optionsAsJsonString = Json.Serialize(options); - var script = string.Format( + var script = string.Format( "dnn.initializePasswordStrength('.{0}', {1});{2}", this.TextBoxCssClass, optionsAsJsonString, Environment.NewLine); @@ -110,5 +105,10 @@ protected override void OnPreRender(EventArgs e) this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", script, true); } } + + private void TextChanged(object sender, EventArgs e) + { + this.UpdateDataSource(this.Value, this._password.Text, this.DataField); + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs index 7a9e42ac362..712aa6b2477 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormRadioButtonListItem.cs @@ -37,7 +37,7 @@ protected override void BindList() this._radioButtonList.DataBind(); } - + if (string.IsNullOrEmpty(selectedValue)) { selectedValue = this.DefaultValue; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs index a6b14c6ed00..9cca0ed2c68 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSection.cs @@ -18,8 +18,8 @@ public DnnFormSection() public bool Expanded { get; set; } - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Items { get; private set; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs index 9eabf61e67a..a62267b577c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormSectionTemplate.cs @@ -16,8 +16,8 @@ public DnnFormSectionTemplate() public List Items { get; private set; } - public string LocalResourceFile { get; set; } - + public string LocalResourceFile { get; set; } + public void InstantiateIn(Control container) { var webControl = container as WebControl; @@ -25,6 +25,6 @@ public void InstantiateIn(Control container) { DnnFormEditor.SetUpItems(this.Items, webControl, this.LocalResourceFile, false); } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs index 058e269249c..a0d7c769b7f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTab.cs @@ -19,18 +19,17 @@ public DnnFormTab() public bool IncludeExpandAll { get; set; } - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Items { get; private set; } - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public List Sections { get; private set; } - internal string ExpandAllScript { get; set; } - public string ResourceKey { get; set; } + internal string ExpandAllScript { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs index 62ac54dbc29..a7dcc023609 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTemplateItem.cs @@ -9,11 +9,11 @@ namespace DotNetNuke.Web.UI.WebControls [ParseChildren(true)] public class DnnFormTemplateItem : DnnFormItemBase { - [Browsable(false)] - [DefaultValue(null)] - [Description("The Item Template.")] - [TemplateInstance(TemplateInstance.Single)] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(false)] + [DefaultValue(null)] + [Description("The Item Template.")] + [TemplateInstance(TemplateInstance.Single)] + [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer(typeof(DnnFormEmptyTemplate))] public ITemplate ItemTemplate { get; set; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs index a66604450be..fadee3f28bd 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnFormTextBoxItem.cs @@ -27,7 +27,7 @@ public string TextBoxCssClass { return this.ViewState.GetValue("TextBoxCssClass", string.Empty); } - + set { this.ViewState.SetValue("TextBoxCssClass", value, string.Empty); @@ -59,7 +59,7 @@ protected override WebControl CreateControlInternal(Control container) { this._textBox.Attributes.Add("autocomplete", "off"); } - + if (this.MaxLength > 0) { this._textBox.MaxLength = this.MaxLength; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs index 091df32a75b..14c133651d1 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnGenericHiddenField.cs @@ -16,20 +16,6 @@ public class DnnGenericHiddenField : HiddenField private T _typedValue = null; private bool _isValueSerialized = false; - - public T TypedValue - { - get - { - return this._typedValue; - } - - set - { - this._typedValue = value; - this._isValueSerialized = false; - } - } public T TypedValueOrDefault { @@ -44,6 +30,20 @@ public bool HasValue get { return this._typedValue != null; } } + public T TypedValue + { + get + { + return this._typedValue; + } + + set + { + this._typedValue = value; + this._isValueSerialized = false; + } + } + public override void RenderControl(HtmlTextWriter writer) { this.EnsureValue(); @@ -69,7 +69,7 @@ protected override bool LoadPostData(string postDataKey, NameValueCollection pos { this.SetTypedValue(); } - + return controlsStateChanged; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs index fc7ef1a6a0f..a6eaea421f6 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImage.cs @@ -9,15 +9,15 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnImage : Image { - public string IconKey { get; set; } + public string IconKey { get; set; } - public string IconSize { get; set; } + public string IconSize { get; set; } public string IconStyle { get; set; } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); if (string.IsNullOrEmpty(this.ImageUrl)) { this.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs index 93f55b42adf..495a9cd1611 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnImageButton.cs @@ -9,15 +9,15 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnImageButton : ImageButton { - public string IconKey { get; set; } + public string IconKey { get; set; } - public string IconSize { get; set; } + public string IconSize { get; set; } public string IconStyle { get; set; } - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); if (string.IsNullOrEmpty(this.ImageUrl)) { this.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs index 793ebc8723c..343f1451416 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLabel.cs @@ -11,20 +11,20 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnLabel : Label, ILocalizable { - private bool _localize = true; - + private bool _localize = true; + public DnnLabel() { this.CssClass = "dnnFormLabel"; - } - + } + public bool Localize { get { return !this.DesignMode && this._localize; } - + set { this._localize = value; @@ -54,8 +54,8 @@ public virtual void LocalizeStrings() } } } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -66,6 +66,6 @@ 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 71d8bdc1b15..20c8458a65c 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLanguageLabel.cs @@ -12,16 +12,16 @@ namespace DotNetNuke.Web.UI.WebControls using DotNetNuke.Services.Personalization; public class DnnLanguageLabel : CompositeControl, ILocalizable - { + { private Image _Flag; - private Label _Label; - + private Label _Label; + public DnnLanguageLabel() { this.Localize = true; - } - + } + public CultureDropDownTypes DisplayType { get; set; } public string Language @@ -30,21 +30,21 @@ public string Language { return (string)this.ViewState["Language"]; } - + set { this.ViewState["Language"] = value; } - } - + } + public bool Localize { get; set; } public string LocalResourceFile { get; set; } public virtual void LocalizeStrings() { - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -121,9 +121,9 @@ protected override void OnPreRender(EventArgs e) { localeName = Localization.GetLocaleName(this.Language, this.DisplayType); } - + this._Label.Text = localeName; this._Flag.AlternateText = localeName; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs index 3728f5e58e8..26de5096e6f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnLiteral.cs @@ -11,15 +11,15 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnLiteral : Literal, ILocalizable { - private bool _Localize = true; - + private bool _Localize = true; + public bool Localize { get { return this._Localize; } - + set { this._Localize = value; @@ -37,8 +37,8 @@ public virtual void LocalizeStrings() this.Text = Localization.GetString(this.Text, this.LocalResourceFile); } } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -49,6 +49,6 @@ protected override void Render(HtmlTextWriter writer) { this.LocalizeStrings(); base.Render(writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs index e96c68909ef..040d20dbd87 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnMemberListControl.cs @@ -20,66 +20,66 @@ namespace DotNetNuke.Web.UI.WebControls /// [ToolboxData("<{0}:DnnMemberListControl runat=\"server\">")] public class DnnMemberListControl : WebControl - { + { private UserInfo _currentUser; - private RelationshipController _relationshipController; - + private RelationshipController _relationshipController; + /// /// Gets or sets the template for displaying the header section of a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string HeaderTemplate { get; set; } /// /// Gets or sets the template for the row header. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string RowHeaderTemplate { get; set; } /// /// Gets or sets the template for displaying an item in a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string ItemTemplate { get; set; } /// /// Gets or sets the template for the row footer. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string RowFooterTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating row headers in a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingRowHeaderTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating items in a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingItemTemplate { get; set; } /// /// Gets or sets the template for displaying the alternating row footers in a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string AlternatingRowFooterTemplate { get; set; } /// /// Gets or sets the template for displaying the footer section of a DnnMemberListControl object. /// - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] - public string FooterTemplate { get; set; } - + public string FooterTemplate { get; set; } + /// /// Gets or sets the index of the currently displayed page. /// @@ -116,8 +116,8 @@ public class DnnMemberListControl : WebControl /// /// Posible keys are: RoleId, RelationshipTypeId, UserId, Profile:PropertyName, FirstName, LastName, DisplayName, Username, Email. /// - public IDictionary Filters { get; set; } - + public IDictionary Filters { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -128,19 +128,19 @@ protected override void OnInit(EventArgs e) protected override void Render(HtmlTextWriter writer) { - if (this.ItemTemplate == string.Empty) - { - return; - } - + if (this.ItemTemplate == string.Empty) + { + return; + } + writer.Write(this.HeaderTemplate); // Filters - if (this.Filters == null) - { - this.Filters = new Dictionary(); - } - + if (this.Filters == null) + { + this.Filters = new Dictionary(); + } + var additionalFilters = new Dictionary(); additionalFilters.Add("Records", this.PageSize.ToString()); additionalFilters.Add("PageIndex", this.PageIndex.ToString()); @@ -189,6 +189,6 @@ protected override void Render(HtmlTextWriter writer) } writer.Write(this.FooterTemplate); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs index e103b5a029b..d8fda47febc 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPageDropDownList.cs @@ -37,54 +37,6 @@ public class DnnPageDropDownList : DnnDropDownList /// 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); - - this.Roles = new List(); - - this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); - this.Services.GetTreeMethod = "ItemListService/GetPages"; - this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendants"; - this.Services.SearchTreeMethod = "ItemListService/SearchPages"; - this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPage"; - this.Services.ServiceRoot = "InternalServices"; - this.Services.SortTreeMethod = "ItemListService/SortPages"; - } - - protected override void OnPreRender(EventArgs e) - { - this.AddCssClass("page"); - if (this.InternalPortalId.HasValue) - { - this.Services.Parameters.Add("PortalId", this.InternalPortalId.Value.ToString(CultureInfo.InvariantCulture)); - } - - this.Services.Parameters.Add("includeDisabled", this.IncludeDisabledTabs.ToString().ToLowerInvariant()); - this.Services.Parameters.Add("includeAllTypes", this.IncludeAllTabTypes.ToString().ToLowerInvariant()); - this.Services.Parameters.Add("includeActive", this.IncludeActiveTab.ToString().ToLowerInvariant()); - this.Services.Parameters.Add("disabledNotSelectable", this.DisabledNotSelectable.ToString().ToLowerInvariant()); - this.Services.Parameters.Add("includeHostPages", (this.IncludeHostPages && UserController.Instance.GetCurrentUserInfo().IsSuperUser).ToString().ToLowerInvariant()); - this.Services.Parameters.Add("roles", string.Join(";", this.Roles.ToArray())); - - base.OnPreRender(e); - - // add the selected folder's level path so that it can expand to the selected node in client side. - var selectedPage = this.SelectedPage; - if (selectedPage != null && selectedPage.ParentId > Null.NullInteger) - { - var tabLevel = string.Empty; - var parentTab = TabController.Instance.GetTab(selectedPage.ParentId, this.PortalId, false); - while (parentTab != null) - { - tabLevel = string.Format("{0},{1}", parentTab.TabID, tabLevel); - parentTab = TabController.Instance.GetTab(parentTab.ParentId, this.PortalId, false); - } - - this.ExpandPath = tabLevel.TrimEnd(','); - } - } /// /// Gets or sets a value indicating whether whether include pages which tab type is not normal. @@ -104,10 +56,10 @@ public int PortalId { return this.InternalPortalId.Value; } - + return PortalSettings.Current.ActiveTab.IsSuperTab ? -1 : PortalSettings.Current.PortalId; } - + set { this.InternalPortalId = value; @@ -117,7 +69,7 @@ public int PortalId /// /// Gets or sets the selected Page in the control, or selects the Page in the control. /// - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabInfo SelectedPage { @@ -126,7 +78,7 @@ public TabInfo SelectedPage var pageId = this.SelectedItemValueAsInt; return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, this.PortalId, false); } - + set { this.SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; @@ -144,11 +96,59 @@ private int? InternalPortalId { return this.ViewState.GetValue("PortalId", null); } - + set { this.ViewState.SetValue("PortalId", value, null); } } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + this.Roles = new List(); + + this.SelectItemDefaultText = Localization.GetString("DropDownList.SelectWebPageDefaultText", Localization.SharedResourceFile); + this.Services.GetTreeMethod = "ItemListService/GetPages"; + this.Services.GetNodeDescendantsMethod = "ItemListService/GetPageDescendants"; + this.Services.SearchTreeMethod = "ItemListService/SearchPages"; + this.Services.GetTreeWithNodeMethod = "ItemListService/GetTreePathForPage"; + this.Services.ServiceRoot = "InternalServices"; + this.Services.SortTreeMethod = "ItemListService/SortPages"; + } + + protected override void OnPreRender(EventArgs e) + { + this.AddCssClass("page"); + if (this.InternalPortalId.HasValue) + { + this.Services.Parameters.Add("PortalId", this.InternalPortalId.Value.ToString(CultureInfo.InvariantCulture)); + } + + this.Services.Parameters.Add("includeDisabled", this.IncludeDisabledTabs.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeAllTypes", this.IncludeAllTabTypes.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeActive", this.IncludeActiveTab.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("disabledNotSelectable", this.DisabledNotSelectable.ToString().ToLowerInvariant()); + this.Services.Parameters.Add("includeHostPages", (this.IncludeHostPages && UserController.Instance.GetCurrentUserInfo().IsSuperUser).ToString().ToLowerInvariant()); + this.Services.Parameters.Add("roles", string.Join(";", this.Roles.ToArray())); + + base.OnPreRender(e); + + // add the selected folder's level path so that it can expand to the selected node in client side. + var selectedPage = this.SelectedPage; + if (selectedPage != null && selectedPage.ParentId > Null.NullInteger) + { + var tabLevel = string.Empty; + var parentTab = TabController.Instance.GetTab(selectedPage.ParentId, this.PortalId, false); + while (parentTab != null) + { + tabLevel = string.Format("{0},{1}", parentTab.TabID, tabLevel); + parentTab = TabController.Instance.GetTab(parentTab.ParentId, this.PortalId, false); + } + + this.ExpandPath = tabLevel.TrimEnd(','); + } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs index 24cfbac9bf3..dad62bf509f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnPortalPageDropDownList.cs @@ -24,7 +24,7 @@ public class DnnPortalPageDropDownList : DnnDropDownList /// /// Gets or sets the selected Page in the control, or selects the Page in the control. /// - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public TabInfo SelectedPage { @@ -33,7 +33,7 @@ public TabInfo SelectedPage var pageId = this.SelectedItemValueAsInt; return (pageId == Null.NullInteger) ? null : TabController.Instance.GetTab(pageId, this._portalId.Value, false); } - + set { this.SelectedItem = (value != null) ? new ListItem() { Text = value.IndentedTabName, Value = value.TabID.ToString(CultureInfo.InvariantCulture) } : null; diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs index de0b5ab76de..a8962fe80e3 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRadioButton.cs @@ -11,20 +11,20 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnRadioButton : RadioButton, ILocalizable { - private bool _Localize = true; - + private bool _Localize = true; + public DnnRadioButton() { this.CssClass = "SubHead dnnLabel"; - } - + } + public bool Localize { get { return this._Localize; } - + set { this._Localize = value; @@ -52,8 +52,8 @@ public virtual void LocalizeStrings() } } } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -64,6 +64,6 @@ protected override void Render(HtmlTextWriter writer) { this.LocalizeStrings(); base.Render(writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs index d7971f2cfea..3e7d67c45ab 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBar.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Web.UI.WebControls [ParseChildren(true)] public class DnnRibbonBar : WebControl { - public DnnRibbonBar() + public DnnRibbonBar() : base("div") { this.CssClass = "dnnRibbon"; @@ -19,8 +19,8 @@ public DnnRibbonBar() Utilities.ApplySkin(control, string.Empty, "RibbonBar", "RibbonBar"); } - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public DnnRibbonBarGroupCollection Groups { @@ -84,16 +84,16 @@ protected override void Render(HtmlTextWriter writer) writer.RenderEndTag(); } } - + // MyBase.RenderChildren(writer) writer.RenderEndTag(); - + // tr writer.RenderEndTag(); - + // table writer.RenderEndTag(); - + // div writer.AddAttribute("class", "barBottomLeft"); writer.RenderBeginTag("div"); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs index b86f37fc4bd..3132e5aeb70 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroup.cs @@ -13,7 +13,7 @@ public class DnnRibbonBarGroup : WebControl private bool _CheckToolVisibility = true; private HtmlGenericControl _contentContainer; - public DnnRibbonBarGroup() + public DnnRibbonBarGroup() : base("div") { this.CssClass = "dnnRibbonGroup"; @@ -40,7 +40,7 @@ public virtual bool CheckToolVisibility { return this._CheckToolVisibility; } - + set { this._CheckToolVisibility = value; @@ -111,7 +111,7 @@ private bool CheckVisibility() ControlCollection controls = this._contentContainer.Controls; returnValue = this.AreChildToolsVisible(ref controls, ref foundTool); } - + return returnValue; } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs index 706cbc96427..5c93afdf57d 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarGroupCollection.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnRibbonBarGroupCollection : ControlCollection { - public DnnRibbonBarGroupCollection(Control owner) + public DnnRibbonBarGroupCollection(Control owner) : base(owner) { } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs index 6cdee9ac980..aeff3ea7c7a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnRibbonBarTool.cs @@ -36,8 +36,6 @@ public DnnRibbonBarTool() this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } - protected INavigationManager NavigationManager { get; } - public virtual RibbonBarToolInfo ToolInfo { get @@ -128,6 +126,8 @@ public virtual string ToolName } } + protected INavigationManager NavigationManager { get; } + protected virtual DnnTextButton DnnLinkButton { get diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs index 7d17418df2a..c7c12baafdf 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTab.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Web.UI.WebControls [ParseChildren(true)] public class DnnTab : WebControl { - public DnnTab() + public DnnTab() : base("div") { } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs index 1f8aefc1313..d5c68a04a51 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTabCollection.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnTabCollection : ControlCollection { - public DnnTabCollection(Control owner) + public DnnTabCollection(Control owner) : base(owner) { } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs index ee218de93b7..cf0bfc5f5c1 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextButton.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnTextButton : LinkButton, ILocalizable { - private bool _localize = true; - + private bool _localize = true; + [Bindable(true)] [Category("Appearance")] [DefaultValue("")] @@ -24,7 +24,7 @@ public string ConfirmMessage { return this.ViewState["ConfirmMessage"] == null ? string.Empty : (string)this.ViewState["ConfirmMessage"]; } - + set { this.ViewState["ConfirmMessage"] = value; @@ -41,7 +41,7 @@ public override string CssClass { return this.ViewState["CssClass"] == null ? string.Empty : (string)this.ViewState["CssClass"]; } - + set { this.ViewState["CssClass"] = value; @@ -58,7 +58,7 @@ public override string CssClass { return this.ViewState["DisabledCssClass"] == null ? string.Empty : (string)this.ViewState["DisabledCssClass"]; } - + set { this.ViewState["DisabledCssClass"] = value; @@ -75,20 +75,20 @@ public override string CssClass { return this.ViewState["Text"] == null ? string.Empty : (string)this.ViewState["Text"]; } - + set { this.ViewState["Text"] = value; } - } - + } + public bool Localize { get { return this._localize; } - + set { this._localize = value; @@ -121,8 +121,8 @@ public virtual void LocalizeStrings() } } } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -137,9 +137,9 @@ protected override void Render(HtmlTextWriter writer) { 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 6c7732be3e0..c557db38248 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTextLink.cs @@ -15,7 +15,7 @@ public class DnnTextLink : WebControl, ILocalizable private bool _localize = true; private HyperLink _textHyperlinkControl; - public DnnTextLink() + public DnnTextLink() : base("span") { this.CssClass = "dnnTextLink"; @@ -32,7 +32,7 @@ public string Text { return this.TextHyperlinkControl.Text; } - + set { this.TextHyperlinkControl.Text = value; @@ -49,7 +49,7 @@ public override string ToolTip { return this.TextHyperlinkControl.ToolTip; } - + set { this.TextHyperlinkControl.ToolTip = value; @@ -66,7 +66,7 @@ public string NavigateUrl { return this.TextHyperlinkControl.NavigateUrl; } - + set { this.TextHyperlinkControl.NavigateUrl = value; @@ -83,7 +83,7 @@ public string Target { return this.TextHyperlinkControl.Target; } - + set { this.TextHyperlinkControl.Target = value; @@ -100,20 +100,20 @@ public string Target { return this.ViewState["DisabledCssClass"] == null ? string.Empty : (string)this.ViewState["DisabledCssClass"]; } - + set { this.ViewState["DisabledCssClass"] = value; } } - + public bool Localize { get { return this._localize; } - + set { this._localize = value; @@ -130,7 +130,7 @@ private HyperLink TextHyperlinkControl { this._textHyperlinkControl = new HyperLink(); } - + return this._textHyperlinkControl; } } @@ -159,14 +159,14 @@ public virtual void LocalizeStrings() } } } - } + } protected override void CreateChildControls() { this.Controls.Clear(); this.Controls.Add(this.TextHyperlinkControl); - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -183,13 +183,13 @@ protected override void Render(HtmlTextWriter writer) { this.CssClass = this.DisabledCssClass; } - + this.NavigateUrl = "javascript:void(0);"; } this.RenderBeginTag(writer); this.RenderChildren(writer); this.RenderEndTag(writer); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs index 85608ee10eb..b761b5493db 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnTimeZoneEditControl.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Web.UI.WebControls public class DnnTimeZoneEditControl : TextEditControl { - private DnnTimeZoneComboBox TimeZones; - + private DnnTimeZoneComboBox TimeZones; + public DnnTimeZoneEditControl() { } @@ -25,7 +25,7 @@ public override string EditControlClientId this.EnsureChildControls(); return this.TimeZones.ClientID; } - } + } public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { @@ -40,7 +40,7 @@ public override bool LoadPostData(string postDataKey, System.Collections.Special return dataChanged; } - + protected override void CreateChildControls() { this.TimeZones = new DnnTimeZoneComboBox(); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs index 8ec9bbd1360..2b202c59f53 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedList.cs @@ -22,12 +22,12 @@ public class DnnUnsortedList : WebControl, INamingContainer { private UniformControlCollection _listItems = null; - public DnnUnsortedList() + public DnnUnsortedList() : base(HtmlTextWriterTag.Ul) { } - [PersistenceMode(PersistenceMode.InnerDefaultProperty)] + [PersistenceMode(PersistenceMode.InnerDefaultProperty)] [MergableProperty(false)] public virtual UniformControlCollection ListItems { diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs index c9829570bed..235330f6f4f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUnsortedListItem.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Web.UI.WebControls /// public class DnnUnsortedListItem : WebControl { - public DnnUnsortedListItem() + public DnnUnsortedListItem() : base(HtmlTextWriterTag.Li) { } @@ -37,7 +37,7 @@ protected override void AddAttributesToRender(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass); } - + if (!string.IsNullOrEmpty(this.ToolTip)) { writer.AddAttribute(HtmlTextWriterAttribute.Title, this.ToolTip); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs index a9f3f42e691..b588dd2b37f 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/DnnUrlControl.cs @@ -25,7 +25,7 @@ namespace DotNetNuke.Web.UI.WebControls using Globals = DotNetNuke.Common.Globals; public abstract class DnnUrlControl : UserControlBase - { + { protected Panel ErrorRow; protected Panel FileRow; protected Panel ImagesRow; @@ -35,11 +35,6 @@ public abstract class DnnUrlControl : UserControlBase 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 cboUrls; protected CheckBox chkLog; protected CheckBox chkNewWindow; @@ -56,8 +51,43 @@ public abstract class DnnUrlControl : UserControlBase protected RadioButtonList optType; protected TextBox txtUrl; protected TextBox txtUser; - protected DnnFilePickerUploader ctlFile; - + protected DnnFilePickerUploader ctlFile; + private bool _doChangeURL; + private bool _doRenderTypeControls; + private bool _doRenderTypes; + private string _localResourceFile; + private PortalInfo _objPortal; + + public bool Log + { + get + { + if (this.chkLog.Visible) + { + return this.chkLog.Checked; + } + else + { + return false; + } + } + } + + public bool Track + { + get + { + if (this.chkTrack.Visible) + { + return this.chkTrack.Checked; + } + else + { + return false; + } + } + } + public string FileFilter { get @@ -69,7 +99,7 @@ public string FileFilter return string.Empty; } - + set { this.ViewState["FileFilter"] = value; @@ -89,7 +119,7 @@ public bool IncludeActiveTab return false; // Set as default } } - + set { this.ViewState["IncludeActiveTab"] = value; @@ -113,31 +143,16 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } } - public bool Log - { - get - { - if (this.chkLog.Visible) - { - return this.chkLog.Checked; - } - else - { - return false; - } - } - } - public int ModuleID { get @@ -151,10 +166,10 @@ public int ModuleID { int.TryParse(this.Request.QueryString["mid"], out myMid); } - + return myMid; } - + set { this.ViewState["ModuleId"] = value; @@ -167,7 +182,7 @@ public bool NewWindow { return this.chkNewWindow.Visible && this.chkNewWindow.Checked; } - + set { this.chkNewWindow.Checked = this.chkNewWindow.Visible && value; @@ -187,7 +202,7 @@ public bool Required return true; // Set as default in the old variable } } - + set { this.ViewState["Required"] = value; @@ -211,7 +226,7 @@ public bool ShowFiles return true; // Set as default in the old variable } } - + set { this.ViewState["ShowFiles"] = value; @@ -235,7 +250,7 @@ public bool ShowImages return false; } } - + set { this.ViewState["ShowImages"] = value; @@ -252,7 +267,7 @@ public bool ShowLog { return this.chkLog.Visible; } - + set { this.chkLog.Visible = value; @@ -265,7 +280,7 @@ public bool ShowNewWindow { return this.chkNewWindow.Visible; } - + set { this.chkNewWindow.Visible = value; @@ -285,7 +300,7 @@ public bool ShowNone return false; // Set as default in the old variable } } - + set { this.ViewState["ShowNone"] = value; @@ -309,7 +324,7 @@ public bool ShowTabs return true; // Set as default in the old variable } } - + set { this.ViewState["ShowTabs"] = value; @@ -326,7 +341,7 @@ public bool ShowTrack { return this.chkTrack.Visible; } - + set { this.chkTrack.Visible = value; @@ -346,7 +361,7 @@ public bool ShowUpLoad return true; // Set as default in the old variable } } - + set { this.ViewState["ShowUpLoad"] = value; @@ -370,7 +385,7 @@ public bool ShowUrls return true; // Set as default in the old variable } } - + set { this.ViewState["ShowUrls"] = value; @@ -394,7 +409,7 @@ public bool ShowUsers return false; // Set as default in the old variable } } - + set { this.ViewState["ShowUsers"] = value; @@ -405,21 +420,6 @@ public bool ShowUsers } } - public bool Track - { - get - { - if (this.chkTrack.Visible) - { - return this.chkTrack.Checked; - } - else - { - return false; - } - } - } - public string Url { get @@ -430,7 +430,7 @@ public string Url { strCurrentType = this.optType.SelectedItem.Value; } - + switch (strCurrentType) { case "I": @@ -438,7 +438,7 @@ public string Url { r = this.cboImages.SelectedItem.Value; } - + break; case "U": if (this.cboUrls.Visible) @@ -461,7 +461,7 @@ public string Url r = Globals.AddHTTP(mCustomUrl); } } - + break; case "T": string strTab = string.Empty; @@ -474,7 +474,7 @@ public string Url r = strTab; } } - + break; case "F": if (this.ctlFile.FileID > Null.NullInteger) @@ -485,7 +485,7 @@ public string Url { r = string.Empty; } - + break; case "M": if (!string.IsNullOrEmpty(this.txtUser.Text)) @@ -502,13 +502,13 @@ public string Url this.txtUser.Text = string.Empty; } } - + break; } - + return r; } - + set { this.ViewState["Url"] = value; @@ -527,7 +527,7 @@ public string UrlType { return Convert.ToString(this.ViewState["UrlType"]); } - + set { if (value != null && !string.IsNullOrEmpty(value.Trim())) @@ -547,7 +547,7 @@ public string Width { return Convert.ToString(this.ViewState["SkinControlWidth"]); } - + set { if (!string.IsNullOrEmpty(value)) @@ -560,8 +560,8 @@ public string Width this.ViewState["SkinControlWidth"] = value; } } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -596,7 +596,7 @@ protected override void OnLoad(EventArgs e) { this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); } - + if (this.ViewState["IsUrlControlLoaded"] == null) { // If Not Page.IsPostBack Then @@ -606,7 +606,7 @@ protected override void OnLoad(EventArgs e) 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" } @@ -616,7 +616,94 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + try + { + if (this._doRenderTypes) + { + this.DoRenderTypes(); + } + + if (this._doChangeURL) + { + this.DoChangeURL(); + } + + this.DoCorrectRadioButtonList(); + + if (this._doRenderTypeControls) + { + this.DoRenderTypeControls(); + } + + this.ViewState["Url"] = null; + this.ViewState["IsUrlControlLoaded"] = "Loaded"; + + this.ctlFile.FileFilter = this.FileFilter; + } + catch (Exception exc) + { + // Let's detect possible problems + Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); + } + } + + protected void cmdAdd_Click(object sender, EventArgs e) + { + this.cboUrls.Visible = false; + this.cmdSelect.Visible = true; + this.txtUrl.Visible = true; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + } + + protected void cmdDelete_Click(object sender, EventArgs e) + { + if (this.cboUrls.SelectedItem != null) + { + var objUrls = new UrlController(); + objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); + this.LoadUrls(); // we must reload the url list + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + } + + protected void cmdSelect_Click(object sender, EventArgs e) + { + this.cboUrls.Visible = true; + this.cmdSelect.Visible = false; + this.txtUrl.Visible = false; + this.cmdAdd.Visible = true; + this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); + this.LoadUrls(); + if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) + { + this.cboUrls.ClearSelection(); + this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + } + + protected void optType_SelectedIndexChanged(object sender, EventArgs e) + { + // Type changed, render the correct control set + this.ViewState["UrlType"] = this.optType.SelectedItem.Value; + this._doRenderTypeControls = true; + } + private void LoadUrls() { var objUrls = new UrlController(); @@ -639,7 +726,7 @@ private void DoChangeURL() { _Urltype = "I"; } - + this.ViewState["UrlType"] = _Urltype; if (_Urltype == "F") { @@ -667,11 +754,11 @@ private void DoChangeURL() fileId = file.FileId; } } - + TrackingUrl = "FileID=" + fileId.ToString(); } } - + if (_Urltype == "M") { if (_Url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) @@ -683,7 +770,7 @@ private void DoChangeURL() } } } - + UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this._objPortal.PortalID, TrackingUrl, this.ModuleID); if (objUrlTracking != null) { @@ -696,7 +783,7 @@ private void DoChangeURL() this.chkTrack.Checked = false; this.chkLog.Checked = false; } - + this.ViewState["Url"] = _Url; } else @@ -721,7 +808,7 @@ private void DoChangeURL() this.optType.Items[0].Selected = true; } } - + this.chkNewWindow.Checked = false; // Need check this.chkTrack.Checked = false; // Need check this.chkLog.Checked = false; // Need check @@ -739,7 +826,7 @@ private void DoRenderTypes() { strCurrent = this.optType.SelectedItem.Value; // Save current selected value } - + this.optType.Items.Clear(); if (this.ShowNone) { @@ -755,7 +842,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("N")); } } - + if (this.ShowUrls) { if (this.optType.Items.FindByValue("U") == null) @@ -770,7 +857,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("U")); } } - + if (this.ShowTabs) { if (this.optType.Items.FindByValue("T") == null) @@ -785,7 +872,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("T")); } } - + if (this.ShowFiles) { if (this.optType.Items.FindByValue("F") == null) @@ -800,7 +887,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("F")); } } - + if (this.ShowImages) { if (this.optType.Items.FindByValue("I") == null) @@ -815,7 +902,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("I")); } } - + if (this.ShowUsers) { if (this.optType.Items.FindByValue("M") == null) @@ -830,7 +917,7 @@ private void DoRenderTypes() this.optType.Items.Remove(this.optType.Items.FindByValue("M")); } } - + if (this.optType.Items.Count > 0) { if (!string.IsNullOrEmpty(strCurrent)) @@ -850,7 +937,7 @@ private void DoRenderTypes() this.optType.Items[0].Selected = true; this._doRenderTypeControls = true; // Type changed, re-draw } - + this.TypeRow.Visible = this.optType.Items.Count > 1; } else @@ -926,7 +1013,7 @@ private void DoRenderTypeControls() { selecteItem.Selected = true; } - + break; case "U": // Url @@ -939,12 +1026,12 @@ private void DoRenderTypeControls() { this.txtUrl.Text = _Url; } - + if (string.IsNullOrEmpty(this.txtUrl.Text)) { this.txtUrl.Text = "http://"; } - + this.txtUrl.Visible = true; this.cmdSelect.Visible = true; @@ -973,7 +1060,7 @@ private void DoRenderTypeControls() var page = TabController.Instance.GetTab(tabId, _settings.PortalId); this.cboTabs.SelectedPage = page; } - + break; case "F": // file this.URLRow.Visible = false; @@ -988,18 +1075,18 @@ private void DoRenderTypeControls() string FolderPath = string.Empty; string LastFileName = string.Empty; string LastFolderPath = string.Empty; - + // Let's try to remember last selection if (this.ViewState["LastFolderPath"] != null) { LastFolderPath = Convert.ToString(this.ViewState["LastFolderPath"]); } - + if (this.ViewState["LastFileName"] != null) { LastFileName = Convert.ToString(this.ViewState["LastFileName"]); } - + if (_Url != string.Empty) { // Let's use the new URL @@ -1027,7 +1114,7 @@ private void DoRenderTypeControls() { this.txtUser.Text = _Url; } - + break; } } @@ -1039,93 +1126,6 @@ private void DoRenderTypeControls() this.FileRow.Visible = false; this.UserRow.Visible = false; } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - try - { - if (this._doRenderTypes) - { - this.DoRenderTypes(); - } - - if (this._doChangeURL) - { - this.DoChangeURL(); - } - - this.DoCorrectRadioButtonList(); - - if (this._doRenderTypeControls) - { - this.DoRenderTypeControls(); - } - - this.ViewState["Url"] = null; - this.ViewState["IsUrlControlLoaded"] = "Loaded"; - - this.ctlFile.FileFilter = this.FileFilter; - } - catch (Exception exc) - { - // Let's detect possible problems - Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); - } - } - - protected void cmdAdd_Click(object sender, EventArgs e) - { - this.cboUrls.Visible = false; - this.cmdSelect.Visible = true; - this.txtUrl.Visible = true; - this.cmdAdd.Visible = false; - this.cmdDelete.Visible = false; - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - } - - protected void cmdDelete_Click(object sender, EventArgs e) - { - if (this.cboUrls.SelectedItem != null) - { - var objUrls = new UrlController(); - objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); - this.LoadUrls(); // we must reload the url list - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - } - - protected void cmdSelect_Click(object sender, EventArgs e) - { - this.cboUrls.Visible = true; - this.cmdSelect.Visible = false; - this.txtUrl.Visible = false; - this.cmdAdd.Visible = true; - this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); - this.LoadUrls(); - if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) - { - this.cboUrls.ClearSelection(); - this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; } - - protected void optType_SelectedIndexChanged(object sender, EventArgs e) - { - // Type changed, render the correct control set - this.ViewState["UrlType"] = this.optType.SelectedItem.Value; - this._doRenderTypeControls = true; - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs index 6538ac1a9a1..26d23483227 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Extensions/ListControlExtensions.cs @@ -68,7 +68,7 @@ public static void Select(this ListControl control, string initial, bool findByT } } } - + /// /// Use this method instead of ListItemCollection.FindByText to find the specific item with case-insensitive. /// diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs index df929f7ffe0..2ecf3a825db 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnCheckBoxList.cs @@ -19,14 +19,14 @@ namespace DotNetNuke.Web.UI.WebControls.Internal public class DnnCheckBoxList : CheckBoxList { private string _initValue; - + public override string SelectedValue { get { return base.SelectedValue; } - + set { if (this.RequiresDataBinding) @@ -56,20 +56,6 @@ 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) { @@ -121,6 +107,20 @@ public int FindItemIndexByValue(string value) return this.Items.IndexOf(this.FindItemByValue(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); + } + private void RegisterRequestResources() { JavaScript.RequestRegistration(CommonJs.DnnPlugins); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs index 717218b8def..b44e7750a38 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBox.cs @@ -20,17 +20,17 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnComboBox : DropDownList - { + { private string _initValue; - private string _multipleValue; - + private string _multipleValue; + public override string SelectedValue { get { return base.SelectedValue; } - + set { if (this.RequiresDataBinding) @@ -62,7 +62,7 @@ public string Value return this.SelectedValue ?? string.Empty; } - + set { if (this.TagKey == HtmlTextWriterTag.Input) @@ -75,7 +75,7 @@ public string Value } } - public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); + public DnnComboBoxOption Options { get; set; } = new DnnComboBoxOption(); protected override HtmlTextWriterTag TagKey { @@ -95,13 +95,63 @@ public override void DataBind() { 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)); + } + + public void DataBind(string initialValue) + { + this.DataBind(initialValue, false); + } + + public void DataBind(string initial, bool findByText) + { + base.DataBind(); + + this.Select(initial, findByText); + } + + public void Select(string initial, bool findByText) + { + if (findByText) + { + if (this.FindItemByText(initial, true) != null) + { + this.FindItemByText(initial, true).Selected = true; + } + } + else + { + if (this.FindItemByValue(initial, true) != null) + { + this.FindItemByValue(initial, true).Selected = true; + } + } + } + + public ListItem FindItemByText(string text, bool ignoreCase = false) + { + return ignoreCase ? this.Items.FindByText(text) : this.Items.FindByTextWithIgnoreCase(text); + } + + public ListItem FindItemByValue(string value, bool ignoreCase = false) + { + return ignoreCase ? this.Items.FindByValue(value) : this.Items.FindByValueWithIgnoreCase(value); + } + + public int FindItemIndexByValue(string value) + { + return this.Items.IndexOf(this.FindItemByValue(value)); + } + protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { var postData = postCollection[postDataKey]; @@ -142,7 +192,7 @@ protected override void OnPreRender(EventArgs e) { this.Options.Localization.Add("ItemsChecked", Utilities.GetLocalizedString("ItemsCheckedString")); } - + if (!this.Options.Localization.ContainsKey("AllItemsChecked")) { this.Options.Localization.Add("AllItemsChecked", Utilities.GetLocalizedString("AllItemsCheckedString")); @@ -156,56 +206,6 @@ protected override void OnPreRender(EventArgs e) base.OnPreRender(e); } - public void InsertItem(int index, string text, string value) - { - this.Items.Insert(index, new ListItem(text, value)); - } - - public void DataBind(string initialValue) - { - this.DataBind(initialValue, false); - } - - public void DataBind(string initial, bool findByText) - { - base.DataBind(); - - this.Select(initial, findByText); - } - - public void Select(string initial, bool findByText) - { - if (findByText) - { - if (this.FindItemByText(initial, true) != null) - { - this.FindItemByText(initial, true).Selected = true; - } - } - else - { - if (this.FindItemByValue(initial, true) != null) - { - this.FindItemByValue(initial, true).Selected = true; - } - } - } - - public ListItem FindItemByText(string text, bool ignoreCase = false) - { - return ignoreCase ? this.Items.FindByText(text) : this.Items.FindByTextWithIgnoreCase(text); - } - - public ListItem FindItemByValue(string value, bool ignoreCase = false) - { - return ignoreCase ? this.Items.FindByValue(value) : this.Items.FindByValueWithIgnoreCase(value); - } - - public int FindItemIndexByValue(string value) - { - return this.Items.IndexOf(this.FindItemByValue(value)); - } - private void RegisterRequestResources() { JavaScript.RequestRegistration(CommonJs.DnnPlugins); @@ -235,6 +235,6 @@ private void RegisterRequestResources() ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), $"{this.ClientID}Sctipts", initScripts, true); } } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs index 5f1f1b64495..182912e1949 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnComboBoxOption.cs @@ -30,6 +30,12 @@ public class DnnComboBoxOption [DataMember(Name = "searchField")] public string SearchField { get; } = "text"; + [DataMember(Name = "options")] + public IEnumerable Options + { + get { return this.Items?.Select(i => new OptionItem { Text = i.Text, Value = i.Value, Selected = i.Selected }); } + } + [DataMember(Name = "create")] public bool Create { get; set; } = false; @@ -57,15 +63,9 @@ public class DnnComboBoxOption [IgnoreDataMember] public IEnumerable Items { get; set; } - [DataMember(Name = "options")] - public IEnumerable Options - { - get { return this.Items?.Select(i => new OptionItem { Text = i.Text, Value = i.Value, Selected = i.Selected }); } - } - [DataMember(Name = "localization")] - public IDictionary Localization { get; set; } = new Dictionary(); - + public IDictionary Localization { get; set; } = new Dictionary(); + [DataMember(Name = "render")] public RenderOption Render { get; set; } @@ -73,7 +73,7 @@ public IEnumerable Options public string Load { get; set; } [DataMember(Name = "onChange")] - public string OnChangeEvent { get; set; } + public string OnChangeEvent { get; set; } } [DataContract] diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs index cc3cca1c93e..35dafc84808 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDatePicker.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// public class DnnDatePicker : TextBox { - public DateTime? SelectedDate + public DateTime? SelectedDate { get { @@ -30,7 +30,7 @@ public DateTime? SelectedDate return null; } - + set { this.Text = value?.ToString(this.Format) ?? string.Empty; @@ -38,13 +38,13 @@ public DateTime? SelectedDate } public DateTime MinDate { get; set; } = new DateTime(1900, 1, 1); - + + public DateTime MaxDate { get; set; } = DateTime.MaxValue; + protected virtual string Format => "yyyy-MM-dd"; - + protected virtual string ClientFormat => "YYYY-MM-DD"; - public DateTime MaxDate { get; set; } = DateTime.MaxValue; - protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs index f6b7e13ef08..7c7ab149e30 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnDateTimePicker.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Web.UI.WebControls.Internal public class DnnDateTimePicker : DnnDatePicker { protected override string Format => "yyyy-MM-dd HH:mm:ss"; - + protected override string ClientFormat => "YYYY-MM-DD HH:mm:ss"; protected override IDictionary GetSettings() diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs index 84feff33b24..357bcb302a4 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormComboBoxItem.cs @@ -47,10 +47,10 @@ internal static void BindListInternal(DnnComboBox comboBox, object value, IEnume // Reset SelectedValue // comboBox.Select(selectedValue); var selectedItem = comboBox.FindItemByValue(selectedValue); - if (selectedItem != null) - { - selectedItem.Selected = true; - } + if (selectedItem != null) + { + selectedItem.Selected = true; + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs index f9b507716d4..ef0e8c46290 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnFormToggleButtonItem.cs @@ -13,21 +13,21 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnFormToggleButtonItem : DnnFormItemBase - { - // private DnnRadButton _checkBox; + { + // private DnnRadButton _checkBox; private CheckBox _checkBox; public DnnFormToggleButtonItem() { this.Mode = CheckBoxMode.TrueFalse; } - + public enum CheckBoxMode { TrueFalse = 0, YN = 1, YesNo = 2, - } + } public CheckBoxMode Mode { get; set; } @@ -43,7 +43,7 @@ protected override WebControl CreateControlInternal(Control container) if (!this._checkBox.Page.IsPostBack) { } - + switch (this.Mode) { case CheckBoxMode.YN: @@ -53,7 +53,7 @@ protected override WebControl CreateControlInternal(Control container) { this._checkBox.Checked = stringValue.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase); } - + break; default: this._checkBox.Checked = Convert.ToBoolean(this.Value); @@ -85,7 +85,7 @@ private void CheckedChanged(object sender, EventArgs e) newValue = this._checkBox.Checked ? "true" : "false"; break; } - + this.UpdateDataSource(this.Value, newValue, this.DataField); } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs index b8e43387f48..9d06e8b0cdf 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGrid.cs @@ -12,7 +12,14 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGrid : GridView - { + { + public TableItemStyle ItemStyle => this.RowStyle; + + public TableItemStyle AlternatingItemStyle => this.AlternatingRowStyle; + + public TableItemStyle EditItemStyle => this.EditRowStyle; + + public TableItemStyle SelectedItemStyle => this.SelectedRowStyle; public int ScreenRowNumber { get; set; } public int RowHeight { get; set; } @@ -23,18 +30,10 @@ public int CurrentPageIndex { return this.PageIndex; } - + set { this.PageIndex = value; } } - public TableItemStyle ItemStyle => this.RowStyle; - - public TableItemStyle AlternatingItemStyle => this.AlternatingRowStyle; - - public TableItemStyle EditItemStyle => this.EditRowStyle; - - public TableItemStyle SelectedItemStyle => this.SelectedRowStyle; - protected override void OnInit(EventArgs e) { base.OnInit(e); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs index 8f20367a1df..d13629e99a6 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridBoundColumn.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGridBoundColumn : BoundField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs index 8fde5a21b93..28c8aa6c205 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnGridTemplateColumn.cs @@ -9,6 +9,5 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class DnnGridTemplateColumn : TemplateField - { - } + {} } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs index cb15f0e3056..405d812b071 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnModuleComboBox.cs @@ -20,14 +20,12 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// public class DnnModuleComboBox : DnnComboBox { - private const string DefaultExtensionImage = "icon_extensions_32px.png"; - + private const string DefaultExtensionImage = "icon_extensions_32px.png"; + private DnnComboBox _moduleCombo; private string _originalValue; - - public event EventHandler ItemChanged; - - public Func, bool> Filter { get; set; } + + public event EventHandler ItemChanged; public int ItemCount { @@ -37,35 +35,37 @@ public int ItemCount } } - public override string SelectedValue + public string RadComboBoxClientId { get { - return this._moduleCombo.SelectedValue; + return this._moduleCombo.ClientID; } } - public string RadComboBoxClientId + public Func, bool> Filter { get; set; } + + public override string SelectedValue { get { - return this._moduleCombo.ClientID; + return this._moduleCombo.SelectedValue; } } - public override bool Enabled + public override bool Enabled { get { return this._moduleCombo.Enabled; } - + set { this._moduleCombo.Enabled = value; } - } - + } + public void BindAllPortalDesktopModules() { this._moduleCombo.SelectedValue = null; @@ -81,7 +81,12 @@ public void BindTabModulesByTabID(int tabID) this._moduleCombo.DataBind(); this.BindTabModuleImages(tabID); } - + + public void SetModule(string code) + { + this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -97,6 +102,25 @@ protected override void OnLoad(EventArgs e) this._originalValue = this.SelectedValue; } + protected virtual void OnItemChanged() + { + if (this.ItemChanged != null) + { + this.ItemChanged(this, new EventArgs()); + } + } + + protected override void OnPreRender(EventArgs e) + { + if (this._moduleCombo.FindItemByValue(this._originalValue) != null) + { + this._moduleCombo.FindItemByValue(this._originalValue).Selected = true; + } + + this._moduleCombo.Width = this.Width; + base.OnPreRender(e); + } + private static Dictionary GetTabModules(int tabID) { var tabModules = ModuleController.Instance.GetTabModules(tabID); @@ -120,7 +144,7 @@ private static bool ModuleSuportsSharing(ModuleInfo moduleInfo) return false; } } - + private Dictionary GetPortalDesktopModules() { IOrderedEnumerable> portalModulesList; @@ -137,7 +161,7 @@ private Dictionary GetPortalDesktopModules() .OrderBy(c => c.Key); } - return portalModulesList.ToDictionary( + return portalModulesList.ToDictionary( portalModule => portalModule.Value.DesktopModuleID, portalModule => portalModule.Key); } @@ -177,30 +201,6 @@ private void BindTabModuleImages(int tabID) // item.ImageUrl = String.IsNullOrEmpty(imageUrl) ? Globals.ImagePath + DefaultExtensionImage : imageUrl; // } - } - - protected virtual void OnItemChanged() - { - if (this.ItemChanged != null) - { - this.ItemChanged(this, new EventArgs()); - } } - - protected override void OnPreRender(EventArgs e) - { - if (this._moduleCombo.FindItemByValue(this._originalValue) != null) - { - this._moduleCombo.FindItemByValue(this._originalValue).Selected = true; - } - - this._moduleCombo.Width = this.Width; - base.OnPreRender(e); - } - - public void SetModule(string code) - { - this._moduleCombo.SelectedIndex = this._moduleCombo.FindItemIndexByValue(code); - } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs index 85703c9435c..ca5b7c383b7 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/DnnSkinComboBox.cs @@ -20,12 +20,12 @@ 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; } @@ -34,13 +34,13 @@ public DnnSkinComboBox() public bool IncludeNoneSpecificItem { get; set; } - public string NoneSpecificText { get; set; } - + public string NoneSpecificText { get; set; } + private PortalInfo Portal { get { return this.PortalId == Null.NullInteger ? null : PortalController.Instance.GetPortal(this.PortalId); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -80,8 +80,8 @@ protected override void PerformDataBinding(IEnumerable dataSource) base.PerformDataBinding(dataSource); this.SelectedValue = selectedValue; - } - + } + private void AttachEvents() { if (!UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -120,6 +120,6 @@ private void AttachEvents() // ToolTip = tooltip; // } // } - } + } } } 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 46b0549d2b1..2ce0e5a632a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateEditControl.cs @@ -26,30 +26,30 @@ namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls public class DateEditControl : EditControl { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); - private DnnDatePicker _dateControl; - + private DnnDatePicker _dateControl; + + public override string EditControlClientId + { + get + { + this.EnsureChildControls(); + return this.DateControl.ClientID; + } + } + 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. @@ -70,7 +70,7 @@ protected DateTime DateValue { Logger.Error(exc); } - + return dteValue; } } @@ -115,7 +115,7 @@ protected virtual string Format } } } - + return _Format; } } @@ -144,7 +144,7 @@ protected DateTime OldDateValue { Logger.Error(exc); } - + return dteValue; } } @@ -161,16 +161,16 @@ protected override string StringValue { _StringValue = this.DateValue.ToString(this.Format); } - + return _StringValue; } - + set { this.Value = DateTime.Parse(value); } - } - + } + private DnnDatePicker DateControl { get @@ -182,7 +182,7 @@ private DnnDatePicker DateControl return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -203,15 +203,15 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo dataChanged = true; } } - + this.LoadDateControls(); return dataChanged; } - + protected override void CreateChildControls() { base.CreateChildControls(); - + this.DateControl.ControlStyle.CopyFrom(this.ControlStyle); this.DateControl.ID = base.ID + "_control"; 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 a3d7debca7f..a99173941ba 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/PropertyEditorControls/DateTimeEditControl.cs @@ -30,21 +30,21 @@ namespace DotNetNuke.Web.UI.WebControls.Internal.PropertyEditorControls public class DateTimeEditControl : EditControl { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateTimeEditControl)); - private DnnDateTimePicker _dateControl; - + 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. @@ -65,7 +65,7 @@ protected DateTime DateValue { Logger.Error(exc); } - + return dteValue; } } @@ -110,7 +110,7 @@ protected virtual string Format } } } - + return _Format; } } @@ -139,7 +139,7 @@ protected DateTime OldDateValue { Logger.Error(exc); } - + return dteValue; } } @@ -156,16 +156,16 @@ protected override string StringValue { _StringValue = this.DateValue.ToString(this.Format); } - + return _StringValue; } - + set { this.Value = DateTime.Parse(value); } - } - + } + private DnnDateTimePicker DateControl { get @@ -177,7 +177,7 @@ private DnnDateTimePicker DateControl return this._dateControl; } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -203,11 +203,11 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo } } } - + this.LoadDateControls(); return dataChanged; } - + protected override void CreateChildControls() { base.CreateChildControls(); diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs index 2379701fcd5..88f62f74b66 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Internal/TermsSelector.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Web.UI.WebControls.Internal /// This control is only for internal use, please don't reference it in any other place as it may be removed in future. /// public class TermsSelector : DnnComboBox - { + { public int PortalId { get; set; } public bool IncludeSystemVocabularies { get; set; } = false; @@ -52,7 +52,7 @@ public List Terms return terms; } - + set { this.Value = string.Join(",", value.Select(t => t.TermId.ToString())); @@ -62,8 +62,8 @@ public List Terms } } - public override bool MultipleSelect { get; set; } = true; - + public override bool MultipleSelect { get; set; } = true; + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -83,9 +83,9 @@ 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) {{ @@ -101,6 +101,6 @@ protected override void OnInit(EventArgs e) }}); }} "; - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs index 36cc677edc4..1d75e2812db 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/Tags.cs @@ -23,22 +23,13 @@ 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 - { - get - { - VocabularyController vocabularyController = new VocabularyController(); - return (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); - } - } - public string CancelImageUrl { get; set; } public ContentItem ContentItem { get; set; } @@ -52,10 +43,10 @@ public bool IsEditMode { _IsEditMode = Convert.ToBoolean(this.ViewState["IsEditMode"]); } - + return _IsEditMode; } - + set { this.ViewState["IsEditMode"] = value; @@ -70,7 +61,7 @@ public string RepeatDirection { return this._RepeatDirection; } - + set { this._RepeatDirection = value; @@ -85,7 +76,7 @@ public string Separator { return this._Separator; } - + set { this._Separator = value; @@ -94,8 +85,17 @@ public string Separator public bool ShowCategories { get; set; } - public bool ShowTags { get; set; } - + public bool ShowTags { get; set; } + + private Vocabulary TagVocabulary + { + get + { + VocabularyController vocabularyController = new VocabularyController(); + return (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); + } + } + public override void RenderControl(HtmlTextWriter writer) { // Render Outer Div @@ -125,7 +125,7 @@ public override void RenderControl(HtmlTextWriter writer) // Last Category writer.AddAttribute(HtmlTextWriterAttribute.Class, "last_tag"); } - + writer.RenderBeginTag(HtmlTextWriterTag.Li); this.RenderTerm(writer, categories.ToList()[i], i < categories.Count() - 1 && this.RepeatDirection.ToLowerInvariant() == "horizontal"); @@ -158,7 +158,7 @@ public override void RenderControl(HtmlTextWriter writer) // Last Tag writer.AddAttribute(HtmlTextWriterAttribute.Class, "last_tag"); } - + writer.RenderBeginTag(HtmlTextWriterTag.Li); this.RenderTerm(writer, tags.ToList()[i], i < tags.Count() - 1 && this.RepeatDirection.ToLowerInvariant() == "horizontal"); @@ -204,8 +204,8 @@ public override void RenderControl(HtmlTextWriter writer) } writer.RenderEndTag(); - } - + } + public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { this._Tags = postCollection[postDataKey]; @@ -213,14 +213,37 @@ public bool LoadPostData(string postDataKey, NameValueCollection postCollection) return true; } + public void RaisePostDataChangedEvent() + { + } + + public void RaisePostBackEvent(string eventArgument) + { + switch (eventArgument) + { + case "Add": + this.IsEditMode = true; + break; + case "Cancel": + this.IsEditMode = false; + break; + case "Save": + this.SaveTags(); + break; + default: + this.IsEditMode = false; + break; + } + } + protected void OnTagsUpdate(EventArgs e) { if (this.TagsUpdated != null) { this.TagsUpdated(this, e); } - } - + } + protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); @@ -245,7 +268,7 @@ protected override void OnPreRender(EventArgs e) this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), this.UniqueID, sb.ToString()); } } - + private string LocalizeString(string key) { string LocalResourceFile = Utilities.GetLocalResourceFile(this); @@ -258,7 +281,7 @@ private string LocalizeString(string key) { localizedString = Null.NullString; } - + return localizedString; } @@ -335,29 +358,6 @@ private void SaveTags() // Raise the Tags Updated Event this.OnTagsUpdate(EventArgs.Empty); - } - - public void RaisePostDataChangedEvent() - { - } - - public void RaisePostBackEvent(string eventArgument) - { - switch (eventArgument) - { - case "Add": - this.IsEditMode = true; - break; - case "Cancel": - this.IsEditMode = false; - break; - case "Save": - this.SaveTags(); - break; - default: - this.IsEditMode = false; - break; - } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs index 45f8201e17c..0aceff84178 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/TermsEventArgs.cs @@ -9,19 +9,19 @@ namespace DotNetNuke.Web.UI.WebControls public class TermsEventArgs : EventArgs { - private readonly Term _SelectedTerm; - + private readonly Term _SelectedTerm; + public TermsEventArgs(Term selectedTerm) { this._SelectedTerm = selectedTerm; - } - + } + public Term SelectedTerm { get { return this._SelectedTerm; } - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs index 4a37e94e691..b960b9f5af6 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/TypedControlCollection.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Web.UI.WebControls public sealed class TypedControlCollection : ControlCollection where T : Control { - public TypedControlCollection(Control owner) + public TypedControlCollection(Control owner) : base(owner) { } @@ -25,7 +25,7 @@ public override void Add(Control child) { throw new InvalidOperationException("Not supported"); } - + base.Add(child); } @@ -35,7 +35,7 @@ public override void AddAt(int index, Control child) { throw new InvalidOperationException("Not supported"); } - + base.AddAt(index, child); } } diff --git a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs index 81d63e8ca20..1ce835ecc4a 100644 --- a/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs +++ b/DNN Platform/DotNetNuke.Web/UI/WebControls/UniformControlCollection.cs @@ -69,7 +69,7 @@ public TChildren this[int index] { return this._owner.Controls[index] as TChildren; } - + set { this.RemoveAt(index); diff --git a/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs index 0c396f8b963..1fdadff4c12 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/AttributeBasedObjectValidator.cs @@ -12,12 +12,12 @@ public abstract class AttributeBasedObjectValidator : PropertyBasedO { protected override ValidationResult ValidateProperty(object target, PropertyInfo targetProperty) { - return targetProperty.GetCustomAttributes(true).OfType().Aggregate( + return targetProperty.GetCustomAttributes(true).OfType().Aggregate( ValidationResult.Successful, (result, attribute) => result.CombineWith(this.ValidateAttribute(target, targetProperty, attribute) ?? ValidationResult.Successful)); } - + protected abstract ValidationResult ValidateAttribute(object target, PropertyInfo targetProperty, TAttribute attribute); } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs b/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs index 530b10972e0..6a4bb0a8b92 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/DataAnnotationsObjectValidator.cs @@ -12,7 +12,7 @@ protected override ValidationResult ValidateAttribute(object target, PropertyInf { return !attribute.IsValid(targetProperty.GetValue(target, new object[] { })) ? new ValidationResult(new[] { this.CreateError(targetProperty.Name, attribute) }) : ValidationResult.Successful; } - + protected virtual ValidationError CreateError(string propertyName, ValidationAttribute attribute) { return new ValidationError { ErrorMessage = attribute.FormatErrorMessage(propertyName), PropertyName = propertyName, Validator = attribute }; diff --git a/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs b/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs index a6322356b05..29e4e0c300f 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ValidationError.cs @@ -5,11 +5,11 @@ namespace DotNetNuke.Web.Validators { public class ValidationError - { + { public string ErrorMessage { get; set; } public string PropertyName { get; set; } - public object Validator { get; set; } + public object Validator { get; set; } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs index a5c51dacd25..67e0da513a9 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/ValidationResult.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.Web.Validators public class ValidationResult { - private readonly IEnumerable _Errors; - + private readonly IEnumerable _Errors; + public ValidationResult() { this._Errors = Enumerable.Empty(); @@ -21,7 +21,7 @@ public ValidationResult(IEnumerable errors) { Requires.NotNull("errors", errors); this._Errors = errors; - } + } public static ValidationResult Successful { @@ -29,8 +29,8 @@ public static ValidationResult Successful { return new ValidationResult(); } - } - + } + public IEnumerable Errors { get @@ -46,13 +46,13 @@ public bool IsValid return this._Errors.Count() == 0; } } - + public ValidationResult CombineWith(ValidationResult other) { Requires.NotNull("other", other); // Just concatenate the errors collection return new ValidationResult(this._Errors.Concat(other.Errors)); - } + } } } diff --git a/DNN Platform/DotNetNuke.Web/Validators/Validator.cs b/DNN Platform/DotNetNuke.Web/Validators/Validator.cs index 1680d8dece3..38659e9fe29 100644 --- a/DNN Platform/DotNetNuke.Web/Validators/Validator.cs +++ b/DNN Platform/DotNetNuke.Web/Validators/Validator.cs @@ -15,7 +15,7 @@ public Validator() this._Validators = new List(); } - public Validator(ObjectValidator validator) + public Validator(ObjectValidator validator) : this() { this._Validators.Add(validator); 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 b13c073fdc3..855440db9a7 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddModule.ascx.cs @@ -47,14 +47,14 @@ public AddModule() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - + public override bool Visible { get { return base.Visible && TabPermissionController.CanAddContentToPage(); } - + set { base.Visible = value; @@ -67,7 +67,7 @@ public bool Enabled { return this._enabled && this.CanAddModuleToPage(); } - + set { this._enabled = value; @@ -80,13 +80,68 @@ public string ToolName { return "QuickAddModule"; } - + set { throw new NotSupportedException("Set ToolName not supported"); } } + /// Gets the currently-selected module. + protected DesktopModuleInfo SelectedModule + { + get + { + if (this.AddExistingModule.Checked) + { + var tabId = -1; + if (!string.IsNullOrEmpty(this.PageLst.SelectedValue)) + { + tabId = int.Parse(this.PageLst.SelectedValue); + } + + if (tabId < 0) + { + tabId = PortalSettings.Current.ActiveTab.TabID; + } + + if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) + { + var moduleId = int.Parse(this.ModuleLst.SelectedValue); + if (moduleId >= 0) + { + return ModuleController.Instance.GetModule(moduleId, tabId, false).DesktopModule; + } + } + } + else + { + var portalId = -1; + + if (this.SiteListPanel.Visible) + { + portalId = int.Parse(this.SiteList.SelectedValue); + } + + if (portalId < 0) + { + portalId = PortalSettings.Current.PortalId; + } + + if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) + { + var moduleId = int.Parse(this.ModuleLst.SelectedValue); + if (moduleId >= 0) + { + return DesktopModuleController.GetDesktopModule(moduleId, portalId); + } + } + } + + return null; + } + } + /// /// Gets return the for the selected portal (from the Site list), unless /// the site list is not visible or there are no other sites in our site group, in which case @@ -119,8 +174,27 @@ private PortalSettings SelectedPortalSettings return portalSettings; } - } - + } + + 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 void AddNewOrExisting_OnClick(object sender, EventArgs e) { this.LoadAllLists(); @@ -191,7 +265,7 @@ protected override void OnLoad(EventArgs e) { this.hlMoreExtensions.Enabled = false; } - + this.hlMoreExtensions.Text = this.GetString("hlMoreExtensions"); this.hlMoreExtensions.Visible = true; } @@ -250,7 +324,7 @@ protected void CmdAddModuleClick(object sender, EventArgs e) { position = 0; } - + break; case "BELOW": if (!string.IsNullOrEmpty(this.PaneModulesLst.SelectedValue)) @@ -270,7 +344,7 @@ protected void CmdAddModuleClick(object sender, EventArgs e) { position = -1; } - + break; case "BOTTOM": position = -1; @@ -321,106 +395,16 @@ protected void CmdAddModuleClick(object sender, EventArgs e) { Personalization.SetProfile("Usability", "UserMode" + this.PortalSettings.PortalId, "EDIT"); } - - this.Response.Redirect(this.Request.RawUrl, true); - } - } - - 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(); - } - - /// Gets the currently-selected module. - protected DesktopModuleInfo SelectedModule - { - get - { - if (this.AddExistingModule.Checked) - { - var tabId = -1; - if (!string.IsNullOrEmpty(this.PageLst.SelectedValue)) - { - tabId = int.Parse(this.PageLst.SelectedValue); - } - - if (tabId < 0) - { - tabId = PortalSettings.Current.ActiveTab.TabID; - } - - if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) - { - var moduleId = int.Parse(this.ModuleLst.SelectedValue); - if (moduleId >= 0) - { - return ModuleController.Instance.GetModule(moduleId, tabId, false).DesktopModule; - } - } - } - else - { - var portalId = -1; - - if (this.SiteListPanel.Visible) - { - portalId = int.Parse(this.SiteList.SelectedValue); - } - - if (portalId < 0) - { - portalId = PortalSettings.Current.PortalId; - } - - if (!string.IsNullOrEmpty(this.ModuleLst.SelectedValue)) - { - var moduleId = int.Parse(this.ModuleLst.SelectedValue); - if (moduleId >= 0) - { - return DesktopModuleController.GetDesktopModule(moduleId, portalId); - } - } - } - 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; + this.Response.Redirect(this.Request.RawUrl, true); } - - // 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) { var objModulePermission = new ModulePermissionInfo @@ -444,7 +428,7 @@ private static ModulePermissionInfo AddModulePermission(ModuleInfo objModule, Pe private static void SetCloneModuleContext(bool cloneModuleContext) { - Thread.SetData( + Thread.SetData( Thread.GetNamedDataSlot("CloneModuleContext"), cloneModuleContext ? bool.TrueString : bool.FalseString); } @@ -494,7 +478,7 @@ private static void DoAddNewModule(string title, int desktopModuleId, string pan 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) @@ -510,7 +494,7 @@ private static void DoAddNewModule(string title, int desktopModuleId, string pan { objModule.CultureCode = Null.NullString; } - + objModule.AllTabs = false; objModule.Alignment = align; @@ -518,6 +502,47 @@ private static void DoAddNewModule(string title, int desktopModuleId, string pan } } + private static bool GetIsPortable(string moduleID, string tabID) + { + bool isPortable = false; + int parsedModuleID; + int parsedTabID; + + bool validModuleID = int.TryParse(moduleID, out parsedModuleID); + bool validTabID = int.TryParse(tabID, out parsedTabID); + + if (validModuleID && validTabID) + { + ModuleInfo moduleInfo = ModuleController.Instance.GetModule(parsedModuleID, parsedTabID, false); + if (moduleInfo != null) + { + DesktopModuleInfo moduleDesktopInfo = moduleInfo.DesktopModule; + if (moduleDesktopInfo != null) + { + isPortable = moduleDesktopInfo.IsPortable; + } + } + } + + return isPortable; + } + + 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(); + } + private void DoAddExistingModule(int moduleId, int tabId, string paneName, int position, string align, bool cloneModule) { ModuleInfo moduleInfo = ModuleController.Instance.GetModule(moduleId, tabId, false); @@ -542,7 +567,7 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p { case ModuleSharing.Unsupported: // Should never happen since the module should not be listed in the first place. - throw new ApplicationException(string.Format( + throw new ApplicationException(string.Format( "Module '{0}' does not support Shareable and should not be listed in Add Existing Module from a different source site", moduleInfo.DesktopModule.FriendlyName)); case ModuleSharing.Supported: @@ -621,7 +646,7 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p // Ensure the Portal Admin has View rights var permissionController = new PermissionController(); ArrayList arrSystemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - AddModulePermission( + AddModulePermission( newModule, (PermissionInfo)arrSystemModuleViewPermissions[0], PortalSettings.Current.AdministratorRoleId, @@ -639,39 +664,14 @@ private void DoAddExistingModule(int moduleId, int tabId, string paneName, int p } } - private static bool GetIsPortable(string moduleID, string tabID) - { - bool isPortable = false; - int parsedModuleID; - int parsedTabID; - - bool validModuleID = int.TryParse(moduleID, out parsedModuleID); - bool validTabID = int.TryParse(tabID, out parsedTabID); - - if (validModuleID && validTabID) - { - ModuleInfo moduleInfo = ModuleController.Instance.GetModule(parsedModuleID, parsedTabID, false); - if (moduleInfo != null) - { - DesktopModuleInfo moduleDesktopInfo = moduleInfo.DesktopModule; - if (moduleDesktopInfo != null) - { - isPortable = moduleDesktopInfo.IsPortable; - } - } - } - - return isPortable; - } - 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) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) select portals.ToArray()).FirstOrDefault(); // Are we in a group of one? @@ -702,7 +702,7 @@ private void LoadCategoryList() ITermController termController = Util.GetTermController(); this.CategoryList.DataSource = termController.GetTermsByVocabulary("Module_Categories").OrderBy(t => t.Weight).Where(t => t.Name != "< None >").ToList(); this.CategoryList.DataBind(); - + // CategoryList.Items.Add(new ListItem(Localization.GetString("AllCategories", LocalResourceFile), "All")); this.CategoryList.AddItem(Localization.GetString("AllCategories", this.LocalResourceFile), "All"); if (!this.IsPostBack) @@ -723,7 +723,7 @@ private void LoadModuleList() { this.ModuleLst.BindTabModulesByTabID(tabId); } - + if (this.ModuleLst.ItemCount > 0) { this.chkCopyModule.Visible = true; @@ -769,7 +769,7 @@ private void LoadPageList() { this.PageLst.DataSource = TabController.GetPortalTabs(portalSettings.PortalId, Null.NullInteger, true, string.Empty, true, false, false, false, true); } - + this.PageLst.DataBind(); } } @@ -805,7 +805,7 @@ private void LoadPaneModulesList() { moduleOrder++; } - + items.Add(moduleOrder.ToString(), m.ModuleTitle); } } @@ -826,13 +826,13 @@ private void LoadPaneModulesList() { this.PositionLst.Items.Remove(listItem); } - + listItem = this.PositionLst.FindItemByValue("BELOW"); if (listItem != null) { this.PositionLst.Items.Remove(listItem); } - + this.PaneModulesLst.Enabled = false; } @@ -907,6 +907,6 @@ private void SetCopyModuleMessage(bool isPortable) this.chkCopyModule.Text = Localization.GetString("CopyModuleWOcontent", this.LocalResourceFile); this.chkCopyModule.ToolTip = Localization.GetString("CopyModuleWOcontent.ToolTip", this.LocalResourceFile); } - } + } } } 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 86d913c6d7b..70fce6625c3 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/AddPage.ascx.cs @@ -26,21 +26,21 @@ namespace DotNetNuke.UI.ControlPanel 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; @@ -53,12 +53,12 @@ public string ToolName { return "QuickAddPage"; } - + set { throw new NotSupportedException("Set ToolName not supported"); } - } + } protected TabInfo NewTabObject { @@ -68,11 +68,27 @@ protected TabInfo NewTabObject { this._newTabObject = RibbonBarManager.InitTabInfoObject(PortalSettings.ActiveTab); } - + return this._newTabObject; } } - + + private static PortalSettings PortalSettings + { + get + { + return PortalSettings.Current; + } + } + + private string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -90,7 +106,7 @@ protected override void OnLoad(EventArgs e) this.cmdAddPage.Enabled = false; this.cmdAddPage.ToolTip = Localization.GetString("ExceededQuota", this.LocalResourceFile); } - + if (!this.IsPostBack) { if (this.Visible) @@ -150,22 +166,6 @@ protected void CmdAddPageClick(object sender, EventArgs e) errMsg = string.Format("

{0}

{1}

", this.GetString("Err.Header"), errMsg); Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = this.GetString("Err.Title") }); } - } - - private static PortalSettings PortalSettings - { - get - { - return PortalSettings.Current; - } - } - - private string LocalResourceFile - { - get - { - return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); - } } private void LoadAllLists() @@ -230,6 +230,6 @@ private void LoadPageList() private string GetString(string key) { return Localization.GetString(key, this.LocalResourceFile); - } + } } } 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 53983b3dcc1..46eddbdc013 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/ControlBar.ascx.cs @@ -45,19 +45,19 @@ namespace DotNetNuke.UI.ControlPanels public partial class ControlBar : ControlPanelBase { protected DnnFileUpload FileUploader; - + private readonly INavigationManager _navigationManager; - private readonly IList _adminCommonTabs = new List - { + private readonly IList _adminCommonTabs = new List + { "Site Settings", "Security Roles", "User Accounts", - "File Management", + "File Management", }; - private readonly IList _hostCommonTabs = new List - { + private readonly IList _hostCommonTabs = new List + { "Host Settings", "Site Management", "File Management", @@ -66,23 +66,24 @@ public partial class ControlBar : ControlPanelBase "Health Monitoring", "Technical Support", "Knowledge Base", - "Software and Documentation", + "Software and Documentation", }; - + private List _adminBookmarkItems; - - public ControlBar() - { - this._navigationManager = Globals.DependencyProvider.GetRequiredService(); - } private List _hostBookmarkItems; private List _adminTabs; private List _adminBaseTabs; private List _adminAdvancedTabs; + private List _hostTabs; + private List _hostBaseTabs; + private List _hostAdvancedTabs; - public override bool IsDockable { get; set; } + public ControlBar() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } public override bool IncludeInControlHierarchy { @@ -90,13 +91,9 @@ public override bool IncludeInControlHierarchy { return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); } - } - - protected string CurrentUICulture { get; set; } - - protected string LoginUrl { get; set; } + } - protected string LoadTabModuleMessage { get; set; } + public override bool IsDockable { get; set; } protected string BookmarkModuleCategory { @@ -115,11 +112,11 @@ protected string BookmarkedModuleKeys { return string.Empty; } - + return bookmarkModules.ToString(); } } - + protected List AdminBookmarkItems { get @@ -136,7 +133,7 @@ protected List AdminBookmarkItems return this._adminBookmarkItems; } } - + protected List HostBookmarkItems { get @@ -153,7 +150,74 @@ protected List HostBookmarkItems return this._hostBookmarkItems; } } - + + protected List AdminBaseTabs + { + get + { + if (this._adminBaseTabs == null) + { + this.GetAdminTabs(); + } + + return this._adminBaseTabs; + } + } + + protected List AdminAdvancedTabs + { + get + { + if (this._adminAdvancedTabs == null) + { + this.GetAdminTabs(); + } + + return this._adminAdvancedTabs; + } + } + + protected List HostBaseTabs + { + get + { + if (this._hostBaseTabs == null) + { + this.GetHostTabs(); + } + + return this._hostBaseTabs; + } + } + + protected List HostAdvancedTabs + { + get + { + if (this._hostAdvancedTabs == null) + { + this.GetHostTabs(); + } + + return this._hostAdvancedTabs; + } + } + + protected bool IsBeaconEnabled + { + get + { + var user = UserController.Instance.GetCurrentUserInfo(); + return BeaconService.Instance.IsBeaconEnabledForControlBar(user); + } + } + + protected string CurrentUICulture { get; set; } + + protected string LoginUrl { get; set; } + + protected string LoadTabModuleMessage { get; set; } + private new string LocalResourceFile { get @@ -161,7 +225,7 @@ protected List HostBookmarkItems return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType?.Name); } } - + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -219,8 +283,8 @@ protected override void OnLoad(EventArgs e) } this.LoadTabModuleMessage = multipleSite ? this.GetString("LoadingTabModuleCE.Text") : this.GetString("LoadingTabModule.Text"); - } - + } + protected bool CheckPageQuota() { UserInfo objUser = UserController.Instance.GetCurrentUserInfo(); @@ -233,14 +297,14 @@ protected string GetUpgradeIndicator() if (objUser != null && objUser.IsSuperUser) { - var upgradeIndicator = ControlBarController.Instance.GetUpgradeIndicator( + var upgradeIndicator = ControlBarController.Instance.GetUpgradeIndicator( DotNetNukeContext.Current.Application.Version, this.Request.IsLocal, this.Request.IsSecureConnection); if (upgradeIndicator == null) { return string.Empty; } - + return this.GetUpgradeIndicatorButton(upgradeIndicator); } @@ -249,7 +313,7 @@ protected string GetUpgradeIndicator() protected string PreviewPopup() { - var previewUrl = string.Format( + var previewUrl = string.Format( "{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias), "MobilePreview", @@ -272,14 +336,14 @@ protected IEnumerable LoadPaneList() { foreach (var p in panes) { - var topPane = new[] + var topPane = new[] { string.Format(this.GetString("Pane.AddTop.Text"), p), p.ToString(), "TOP", }; - var botPane = new[] + var botPane = new[] { string.Format(this.GetString("Pane.AddBottom.Text"), p), p.ToString(), @@ -294,7 +358,7 @@ protected IEnumerable LoadPaneList() { foreach (var p in panes) { - var botPane = new[] + var botPane = new[] { string.Format(this.GetString("Pane.Add.Text"), p), p.ToString(), @@ -308,29 +372,6 @@ 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) { return Localization.GetString(key, this.LocalResourceFile); @@ -357,70 +398,70 @@ protected string BuildToolUrl(string toolName, bool isHostTool, string moduleFri { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=settingTab"); } - + break; case "CopyPage": if (TabPermissionController.CanCopyPage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=copy&activeTab=copyTab"); } - + break; case "DeletePage": if (TabPermissionController.CanDeletePage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=delete"); } - + break; case "PageTemplate": if (TabPermissionController.CanManagePage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=advancedTab"); } - + break; case "PageLocalization": if (TabPermissionController.CanManagePage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=localizationTab"); } - + break; case "PagePermission": if (TabPermissionController.CanAdminPage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Tab", "action=edit&activeTab=permissionsTab"); } - + break; case "ImportPage": if (TabPermissionController.CanImportPage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "ImportTab"); } - + break; case "ExportPage": if (TabPermissionController.CanExportPage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "ExportTab"); } - + break; case "NewPage": if (TabPermissionController.CanAddPage()) { returnValue = this._navigationManager.NavigateURL("Tab", "activeTab=settingTab"); } - + break; case "PublishPage": if (TabPermissionController.CanAdminPage()) { returnValue = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID); } - + break; default: if (!string.IsNullOrEmpty(moduleFriendlyName)) @@ -429,10 +470,10 @@ protected string BuildToolUrl(string toolName, bool isHostTool, string moduleFri returnValue = this.GetTabURL(additionalParams, toolName, isHostTool, moduleFriendlyName, controlKey, showAsPopUp); } - + break; } - + return returnValue; } @@ -522,7 +563,7 @@ protected string GetPublishConfirmHeader() ? this.GetButtonConfirmHeader("UnpublishPage") : this.GetButtonConfirmHeader("PublishPage"); } - + protected string GetMenuItem(string tabName, bool isHostTool) { if (isHostTool && !UserController.Instance.GetCurrentUserInfo().IsSuperUser) @@ -533,20 +574,20 @@ protected string GetMenuItem(string tabName, bool isHostTool) List tabList; if (isHostTool) { - if (this._hostTabs == null) - { - this.GetHostTabs(); - } - + if (this._hostTabs == null) + { + this.GetHostTabs(); + } + tabList = this._hostTabs; } else { - if (this._adminTabs == null) - { - this.GetAdminTabs(); - } - + if (this._adminTabs == null) + { + this.GetAdminTabs(); + } + tabList = this._adminTabs; } @@ -564,20 +605,20 @@ protected string GetMenuItem(string tabName, bool isHostTool, bool isRemoveBookm List tabList; if (isHostTool) { - if (this._hostTabs == null) - { - this.GetHostTabs(); - } - + if (this._hostTabs == null) + { + this.GetHostTabs(); + } + tabList = this._hostTabs; } else { - if (this._adminTabs == null) - { - this.GetAdminTabs(); - } - + if (this._adminTabs == null) + { + this.GetAdminTabs(); + } + tabList = this._adminTabs; } @@ -587,40 +628,40 @@ protected string GetMenuItem(string tabName, bool isHostTool, bool isRemoveBookm protected string GetMenuItem(TabInfo tab, bool isRemoveBookmark = false, bool isHideBookmark = false) { - if (tab == null) - { - return string.Empty; - } - + if (tab == null) + { + return string.Empty; + } + if (tab.IsVisible && !tab.IsDeleted && !tab.DisableLink) { string name = !string.IsNullOrEmpty(tab.LocalizedTabName) ? tab.LocalizedTabName : tab.Title; var linkClass = DotNetNukeContext.Current.Application.Name == "DNNCORP.CE" && tab.FullUrl.Contains("ProfessionalFeatures") ? "class=\"PE\"" : string.Empty; if (!isRemoveBookmark) { - if (!isHideBookmark) - { - return string.Format( + if (!isHideBookmark) + { + return string.Format( "
  • {1}
  • ", tab.FullUrl, name, ClientAPI.GetSafeJSString(this.GetString("Tool.AddToBookmarks.ToolTip")), ClientAPI.GetSafeJSString(tab.TabName), - linkClass); - } - else - { - return string.Format( + linkClass); + } + else + { + return string.Format( "
  • {1}
  • ", tab.FullUrl, name, ClientAPI.GetSafeJSString(this.GetString("Tool.AddToBookmarks.ToolTip")), ClientAPI.GetSafeJSString(tab.TabName), - linkClass); - } + linkClass); + } } - return string.Format( + return string.Format( "
  • {1}
  • ", tab.FullUrl, name, @@ -628,10 +669,10 @@ protected string GetMenuItem(TabInfo tab, bool isRemoveBookmark = false, bool is ClientAPI.GetSafeJSString(tab.TabName), linkClass); } - + return string.Empty; } - + protected string GetAdminBaseMenu() { var tabs = this.AdminBaseTabs; @@ -697,7 +738,7 @@ protected string GetBookmarkItems(string title) { sb.Append(this.GetMenuItem(itemKey, isHostTool, true)); } - + return sb.ToString(); } @@ -759,7 +800,7 @@ protected IEnumerable LoadLanguagesList() this.SetLanguage(true, this.CurrentUICulture); } } - + IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, this.CurrentUICulture, string.Empty, false); foreach (var cultureItem in cultureListItems) { @@ -778,28 +819,28 @@ 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; - } - + { + 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; } @@ -855,7 +896,15 @@ protected virtual bool ActiveTabHasChildren() protected bool IsLanguageModuleInstalled() { return DesktopModuleController.GetDesktopModuleByFriendlyName("Languages") != null; - } + } + + protected string GetBeaconUrl() + { + var beaconService = BeaconService.Instance; + var user = UserController.Instance.GetCurrentUserInfo(); + var path = this.PortalSettings.ActiveTab.TabPath; + return beaconService.GetBeaconUrl(user, path); + } private static IEnumerable GetCurrentPortalsGroup() { @@ -863,8 +912,8 @@ private static IEnumerable GetCurrentPortalsGroup() var result = (from @group in groups select PortalGroupController.Instance.GetPortalsByGroup(@group.PortalGroupId) - into portals - where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) select portals.ToArray()).FirstOrDefault(); // Are we in a group of one? @@ -876,6 +925,29 @@ where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) return result; } + 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); + } + private void LoadCategoryList() { ITermController termController = Util.GetTermController(); @@ -966,11 +1038,11 @@ private void SetLastPageHistory(string pageId) private string GetLastPageHistory() { var cookie = this.Request.Cookies["LastPageId"]; - if (cookie != null) - { - return cookie.Value; - } - + if (cookie != null) + { + return cookie.Value; + } + return "NEW"; } @@ -1007,78 +1079,6 @@ private void BindLanguagesList() this.controlBar_SwitchLanguage.Items.Add(item); } } - } - private List _hostTabs; - private List _hostBaseTabs; - private List _hostAdvancedTabs; - - protected List AdminBaseTabs - { - get - { - if (this._adminBaseTabs == null) - { - this.GetAdminTabs(); - } - - return this._adminBaseTabs; - } - } - - protected List AdminAdvancedTabs - { - get - { - if (this._adminAdvancedTabs == null) - { - this.GetAdminTabs(); - } - - return this._adminAdvancedTabs; - } - } - - protected List HostBaseTabs - { - get - { - if (this._hostBaseTabs == null) - { - this.GetHostTabs(); - } - - return this._hostBaseTabs; - } - } - - protected List HostAdvancedTabs - { - get - { - if (this._hostAdvancedTabs == null) - { - this.GetHostTabs(); - } - - return this._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() @@ -1140,8 +1140,8 @@ private bool IsCommonTab(TabInfo tab, bool isHost = false) { return true; } - + return isHost ? this._hostCommonTabs.Contains(tab.TabName) : this._adminCommonTabs.Contains(tab.TabName); - } + } } } 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 3e40b27b082..cefbdb08f4b 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/RibbonBar.ascx.cs @@ -30,15 +30,15 @@ namespace DotNetNuke.UI.ControlPanels public partial class RibbonBar : ControlPanelBase { - public override bool IsDockable { get; set; } - public override bool IncludeInControlHierarchy { get { return base.IncludeInControlHierarchy && (this.IsPageAdmin() || this.IsModuleAdmin()); } - } + } + + public override bool IsDockable { get; set; } protected string GetButtonConfirmMessage(string toolName) { @@ -78,66 +78,7 @@ protected void DetermineNodesToInclude(object sender, EventArgs e) skinObject.IncludeNodes = admin + ", " + host; } - - private void Localize() - { - Control ctrl = this.AdminPanel.FindControl("SiteNewPage"); - if ((ctrl != null) && ctrl is DnnRibbonBarTool) - { - var toolCtrl = (DnnRibbonBarTool)ctrl; - toolCtrl.Text = Localization.GetString("SiteNewPage", this.LocalResourceFile); - toolCtrl.ToolTip = Localization.GetString("SiteNewPage.ToolTip", this.LocalResourceFile); - } - } - private void SetMode(bool update) - { - if (update) - { - this.SetUserMode(this.ddlMode.SelectedValue); - } - - if (!TabPermissionController.CanAddContentToPage()) - { - this.RemoveModeDropDownItem("LAYOUT"); - } - - if (!(new PreviewProfileController().GetProfilesByPortal(this.PortalSettings.PortalId).Count > 0)) - { - this.RemoveModeDropDownItem("PREVIEW"); - } - - switch (this.UserMode) - { - case PortalSettings.Mode.View: - this.ddlMode.FindItemByValue("VIEW").Selected = true; - break; - case PortalSettings.Mode.Edit: - this.ddlMode.FindItemByValue("EDIT").Selected = true; - break; - case PortalSettings.Mode.Layout: - this.ddlMode.FindItemByValue("LAYOUT").Selected = true; - break; - } - } - - private void RemoveModeDropDownItem(string value) - { - var item = this.ddlMode.FindItemByValue(value); - if (item != null) - { - this.ddlMode.Items.Remove(item); - } - } - - private void SetLanguage(bool update) - { - if (update) - { - DotNetNuke.Services.Personalization.Personalization.SetProfile("Usability", "UICulture", this.ddlUICulture.SelectedValue); - } - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -170,7 +111,7 @@ protected override void OnLoad(EventArgs e) { copyPageButton.Visible = LocaleController.Instance.IsDefaultLanguage(LocaleController.Instance.GetCurrentLocale(this.PortalSettings.PortalId).Code); } - + if (this.Request.IsAuthenticated) { UserInfo user = UserController.Instance.GetCurrentUserInfo(); @@ -231,7 +172,7 @@ protected override void OnLoad(EventArgs e) this.CommonTasksPanel.Visible = false; } } - + if (this.PortalSettings.AllowUserUICulture) { object oCulture = DotNetNuke.Services.Personalization.Personalization.GetProfile("Usability", "UICulture"); @@ -245,7 +186,7 @@ protected override void OnLoad(EventArgs e) Localization l = new Localization(); currentCulture = l.CurrentUICulture; } - + // Localization.LoadCultureDropDownList(ddlUICulture, CultureDropDownTypes.NativeName, currentCulture); IEnumerable cultureListItems = Localization.LoadCultureInListItems(CultureDropDownTypes.NativeName, currentCulture, string.Empty, false); foreach (var cultureItem in cultureListItems) @@ -272,7 +213,7 @@ protected override void OnLoad(EventArgs e) } } } - + this.SetMode(false); } } @@ -297,32 +238,20 @@ protected override void OnLoad(EventArgs e) } } - private string StripLocalizationPrefix(string s) - { - const string prefix = "[L]"; - - if (s.StartsWith(prefix)) - { - return s.Substring(prefix.Length); - } - - return s; - } - protected void ddlMode_SelectedIndexChanged(object sender, EventArgs e) { if (this.Page.IsCallback) { return; } - + this.SetMode(true); this.Response.Redirect(this.Request.RawUrl, true); } - + protected string PreviewPopup() { - var previewUrl = string.Format( + var previewUrl = string.Format( "{0}/Default.aspx?ctl={1}&previewTab={2}&TabID={2}", Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias), "MobilePreview", @@ -336,7 +265,78 @@ protected string PreviewPopup() { return string.Format("location.href = \"{0}\"", previewUrl); } - } + } + + private void Localize() + { + Control ctrl = this.AdminPanel.FindControl("SiteNewPage"); + if ((ctrl != null) && ctrl is DnnRibbonBarTool) + { + var toolCtrl = (DnnRibbonBarTool)ctrl; + toolCtrl.Text = Localization.GetString("SiteNewPage", this.LocalResourceFile); + toolCtrl.ToolTip = Localization.GetString("SiteNewPage.ToolTip", this.LocalResourceFile); + } + } + + private void SetMode(bool update) + { + if (update) + { + this.SetUserMode(this.ddlMode.SelectedValue); + } + + if (!TabPermissionController.CanAddContentToPage()) + { + this.RemoveModeDropDownItem("LAYOUT"); + } + + if (!(new PreviewProfileController().GetProfilesByPortal(this.PortalSettings.PortalId).Count > 0)) + { + this.RemoveModeDropDownItem("PREVIEW"); + } + + switch (this.UserMode) + { + case PortalSettings.Mode.View: + this.ddlMode.FindItemByValue("VIEW").Selected = true; + break; + case PortalSettings.Mode.Edit: + this.ddlMode.FindItemByValue("EDIT").Selected = true; + break; + case PortalSettings.Mode.Layout: + this.ddlMode.FindItemByValue("LAYOUT").Selected = true; + break; + } + } + + private void RemoveModeDropDownItem(string value) + { + var item = this.ddlMode.FindItemByValue(value); + if (item != null) + { + this.ddlMode.Items.Remove(item); + } + } + + private void SetLanguage(bool update) + { + if (update) + { + DotNetNuke.Services.Personalization.Personalization.SetProfile("Usability", "UICulture", this.ddlUICulture.SelectedValue); + } + } + + private string StripLocalizationPrefix(string s) + { + const string prefix = "[L]"; + + if (s.StartsWith(prefix)) + { + return s.Substring(prefix.Length); + } + + return s; + } private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) { @@ -344,9 +344,9 @@ private void ddlUICulture_SelectedIndexChanged(object sender, EventArgs e) { 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 e25d0474f03..1abfa1c2ed6 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/SwitchSite.ascx.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.UI.ControlPanel using DotNetNuke.Web.UI.WebControls; public partial class SwitchSite : UserControl, IDnnRibbonBarTool - { + { public override bool Visible { get @@ -26,10 +26,10 @@ public override bool Visible { return false; } - + return PortalSettings.Current.UserInfo.IsSuperUser && base.Visible; } - + set { base.Visible = value; @@ -42,13 +42,13 @@ public string ToolName { return "QuickSwitchSite"; } - + set { throw new NotSupportedException("Set ToolName not supported"); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -84,15 +84,15 @@ 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) { Exceptions.LogException(ex); } - } - + } + private void LoadPortalsList() { var portals = PortalController.Instance.GetPortals(); @@ -107,6 +107,6 @@ private void LoadPortalsList() // SitesLst.Items.Insert(0, new ListItem(string.Empty)); this.SitesLst.InsertItem(0, string.Empty, string.Empty); - } + } } } 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 567e46e6c0e..e00d004f9f6 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/UpdatePage.ascx.cs @@ -26,21 +26,21 @@ namespace DotNetNuke.UI.ControlPanel 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; @@ -53,12 +53,12 @@ public string ToolName { return "QuickUpdatePage"; } - + set { throw new NotSupportedException("Set ToolName not supported"); } - } + } private static PortalSettings PortalSettings { @@ -77,11 +77,19 @@ private TabInfo CurrentTab { this._currentTab = TabController.Instance.GetTab(PortalSettings.ActiveTab.TabID, PortalSettings.ActiveTab.PortalID, false); } - + return this._currentTab; } } - + + private string LocalResourceFile + { + get + { + return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); + } + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -168,14 +176,6 @@ protected void CmdUpdateClick(object sender, EventArgs e) Web.UI.Utilities.RegisterAlertOnPageLoad(this, new MessageWindowParameters(errMsg) { Title = this.GetString("Err.Title") }); } } - } - - private string LocalResourceFile - { - get - { - return string.Format("{0}/{1}/{2}.ascx.resx", this.TemplateSourceDirectory, Localization.LocalResourceDirectory, this.GetType().BaseType.Name); - } } private static string FormatSkinName(string strSkinFolder, string strSkinFile) @@ -184,7 +184,7 @@ private static string FormatSkinName(string strSkinFolder, string strSkinFile) { return strSkinFile; } - + switch (strSkinFile.ToLowerInvariant()) { case "skin": @@ -238,11 +238,11 @@ private void LoadSkinList() { this.SkinLst.Items.Add(this.GetSeparatorItem()); } - + strLastFolder = folder; } - - this.SkinLst.Items.Add(new RadComboBoxItem( + + this.SkinLst.Items.Add(new RadComboBoxItem( FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), "[L]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); } @@ -277,11 +277,11 @@ private void LoadSkinList() { this.SkinLst.Items.Add(this.GetSeparatorItem()); } - + strLastFolder = folder; } - - this.SkinLst.Items.Add(new RadComboBoxItem( + + this.SkinLst.Items.Add(new RadComboBoxItem( FormatSkinName(folder, Path.GetFileNameWithoutExtension(strFile)), "[G]" + SkinController.RootSkin + "/" + folder + "/" + Path.GetFileName(strFile))); } @@ -351,11 +351,11 @@ private bool IsParentTab(TabInfo tab, int parentTabId) { return true; } - + tab = tab.ParentId != Null.NullInteger ? TabController.Instance.GetTab(tab.ParentId, tab.PortalID, false) : null; } return false; - } + } } } 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 8f4f0a38340..0240d0a0a36 100644 --- a/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs +++ b/DNN Platform/DotNetNuke.Website.Deprecated/admin/ControlPanel/WebUpload.ascx.cs @@ -42,18 +42,19 @@ 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; - + + private string _RootFolder; + private string _UploadRoles; + public WebUpload() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - private string _RootFolder; - private string _UploadRoles; - + } + public string DestinationFolder { get @@ -66,7 +67,7 @@ public string DestinationFolder this._DestinationFolder = Globals.QueryStringDecode(this.Request.QueryString["dest"]); } } - + return PathUtils.Instance.RemoveTrailingSlash(this._DestinationFolder.Replace("\\", "/")); } } @@ -86,7 +87,7 @@ public UploadType FileType break; } } - + return this._FileType; } } @@ -99,7 +100,7 @@ public string FileTypeName { this._FileTypeName = Localization.GetString(this.FileType.ToString(), this.LocalResourceFile); } - + return this._FileTypeName; } } @@ -134,7 +135,7 @@ public string RootFolder this._RootFolder = this.PortalSettings.HomeDirectoryMapPath; } } - + return this._RootFolder; } } @@ -152,17 +153,17 @@ public string UploadRoles this._UploadRoles = Convert.ToString(this.Settings["uploadroles"]); } } - + return this._UploadRoles; } - } - + } + /// ----------------------------------------------------------------------------- /// /// This routine determines the Return Url. /// /// - /// + /// /// /// ----------------------------------------------------------------------------- public string ReturnURL() @@ -173,7 +174,7 @@ public string ReturnURL() { TabID = int.Parse(this.Request.Params["rtab"]); } - + return this._navigationManager.NavigateURL(TabID); } @@ -184,49 +185,6 @@ protected override void OnInit(EventArgs e) // Customise the Control Title this.ModuleConfiguration.ModuleTitle = Localization.GetString("UploadType" + this.FileType, this.LocalResourceFile); } - - /// ----------------------------------------------------------------------------- - /// - /// This routine checks the Access Security. - /// - /// - /// - /// ----------------------------------------------------------------------------- - private void CheckSecurity() - { - if (!ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "CONTENT,EDIT") && !UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators")) - { - this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// This routine populates the Folder List Drop Down - /// There is no reference to permissions here as all folders should be available to the admin. - /// - /// - /// - /// ----------------------------------------------------------------------------- - private void LoadFolders() - { - var user = UserController.Instance.GetCurrentUserInfo(); - - var folders = FolderManager.Instance.GetFolders(this.FolderPortalID, "ADD", user.UserID); - this.ddlFolders.Services.Parameters.Add("permission", "ADD"); - if (!string.IsNullOrEmpty(this.DestinationFolder)) - { - this.ddlFolders.SelectedFolder = folders.SingleOrDefault(f => f.FolderPath == this.DestinationFolder); - } - else - { - var rootFolder = folders.SingleOrDefault(f => f.FolderPath == string.Empty); - if (rootFolder != null) - { - this.ddlFolders.SelectedItem = new ListItem() { Text = DynamicSharedConstants.RootFolder, Value = rootFolder.FolderID.ToString() }; - } - } - } /// ----------------------------------------------------------------------------- /// @@ -273,10 +231,10 @@ protected override void OnLoad(EventArgs e) this.lblRootType.Text = strPortal + ":"; this.lblRootFolder.Text = this.RootFolder; } - + this.LoadFolders(); } - + this.chkUnzip.Checked = false; } } @@ -286,6 +244,49 @@ protected override void OnLoad(EventArgs e) } } + /// ----------------------------------------------------------------------------- + /// + /// This routine checks the Access Security. + /// + /// + /// + /// ----------------------------------------------------------------------------- + private void CheckSecurity() + { + if (!ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "CONTENT,EDIT") && !UserController.Instance.GetCurrentUserInfo().IsInRole("Administrators")) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// This routine populates the Folder List Drop Down + /// There is no reference to permissions here as all folders should be available to the admin. + /// + /// + /// + /// ----------------------------------------------------------------------------- + private void LoadFolders() + { + var user = UserController.Instance.GetCurrentUserInfo(); + + var folders = FolderManager.Instance.GetFolders(this.FolderPortalID, "ADD", user.UserID); + this.ddlFolders.Services.Parameters.Add("permission", "ADD"); + if (!string.IsNullOrEmpty(this.DestinationFolder)) + { + this.ddlFolders.SelectedFolder = folders.SingleOrDefault(f => f.FolderPath == this.DestinationFolder); + } + else + { + var rootFolder = folders.SingleOrDefault(f => f.FolderPath == string.Empty); + if (rootFolder != null) + { + this.ddlFolders.SelectedItem = new ListItem() { Text = DynamicSharedConstants.RootFolder, Value = rootFolder.FolderID.ToString() }; + } + } + } + /// ----------------------------------------------------------------------------- /// /// The cmdAdd_Click runs when the Add Button is clicked. @@ -342,7 +343,7 @@ private void cmdAdd_Click(object sender, EventArgs e) Logger.Error(exc); strMessage += "
    " + string.Format(Localization.GetString("SaveFileError"), strFileName); } - + break; } } @@ -350,7 +351,7 @@ private void cmdAdd_Click(object sender, EventArgs e) { strMessage = Localization.GetString("NoFile", this.LocalResourceFile); } - + if (this.phPaLogs.Controls.Count > 0) { this.tblLogs.Visible = true; @@ -382,6 +383,6 @@ private void cmdAdd_Click(object sender, EventArgs e) private void cmdReturn_Click(object sender, EventArgs e) { this.Response.Redirect(this.ReturnURL(), true); - } + } } } diff --git a/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs b/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs index 1a8326373e6..62ae8261b1a 100644 --- a/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs +++ b/DNN Platform/HttpModules/Analytics/AnalyticsModule.cs @@ -30,8 +30,8 @@ public string ModuleName { return "AnalyticsModule"; } - } - + } + public void Init(HttpApplication application) { application.PreRequestHandlerExecute += OnPreRequestHandlerExecute; @@ -39,8 +39,8 @@ public void Init(HttpApplication application) public void Dispose() { - } - + } + private static void OnPreRequestHandlerExecute(object sender, EventArgs e) { try @@ -49,29 +49,29 @@ private static void OnPreRequestHandlerExecute(object sender, EventArgs e) var app = (HttpApplication)sender; var request = app.Request; - if (!Initialize.ProcessHttpModule(request, false, false)) - { - return; - } - - if (HttpContext.Current == null) - { - return; - } - + if (!Initialize.ProcessHttpModule(request, false, false)) + { + return; + } + + if (HttpContext.Current == null) + { + return; + } + var context = HttpContext.Current; - if (context == null) - { - return; - } - + if (context == null) + { + return; + } + var page = context.Handler as CDefault; - if (page == null) - { - return; - } - + if (page == null) + { + return; + } + page.InitComplete += OnPageInitComplete; page.PreRender += OnPagePreRender; } @@ -89,7 +89,7 @@ private static void OnPageInitComplete(object sender, EventArgs e) { InitializeAnalyticsControls(sender as Page, true); } - + private static void OnPagePreRender(object sender, EventArgs e) { InitializeAnalyticsControls(sender as Page, false); @@ -100,16 +100,16 @@ private static void InitializeAnalyticsControls(Page page, bool injectTop) try { var analyticsEngines = AnalyticsEngineConfiguration.GetConfig().AnalyticsEngines; - if (analyticsEngines == null || analyticsEngines.Count == 0) - { - return; - } - - if (page == null) - { - return; - } - + if (analyticsEngines == null || analyticsEngines.Count == 0) + { + return; + } + + if (page == null) + { + return; + } + foreach (AnalyticsEngine engine in analyticsEngines) { if (string.IsNullOrEmpty(engine.ElementId) || engine.InjectTop != injectTop) @@ -121,43 +121,43 @@ private static void InitializeAnalyticsControls(Page page, bool injectTop) if (!string.IsNullOrEmpty(engine.EngineType)) { var engineType = Type.GetType(engine.EngineType); - if (engineType == null) - { - objEngine = new GenericAnalyticsEngine(); - } - else - { - objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType); - } + if (engineType == null) + { + objEngine = new GenericAnalyticsEngine(); + } + else + { + objEngine = (AnalyticsEngineBase)Activator.CreateInstance(engineType); + } } else { objEngine = new GenericAnalyticsEngine(); } - - if (objEngine == null) - { - continue; - } - + + if (objEngine == null) + { + continue; + } + var script = engine.ScriptTemplate; - if (string.IsNullOrEmpty(script)) - { - continue; - } - + if (string.IsNullOrEmpty(script)) + { + continue; + } + script = objEngine.RenderScript(script); - if (string.IsNullOrEmpty(script)) - { - continue; - } - + if (string.IsNullOrEmpty(script)) + { + continue; + } + var element = (HtmlContainerControl)page.FindControl(engine.ElementId); - if (element == null) - { - continue; - } - + if (element == null) + { + continue; + } + var scriptControl = new LiteralControl { Text = script }; if (engine.InjectTop) { diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs index 69d1bcf3e14..5a392df6db4 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngine.cs @@ -19,7 +19,7 @@ public string EngineType { return this._engineType; } - + set { this._engineType = value; @@ -32,7 +32,7 @@ public string ScriptTemplate { return this._scriptTemplate; } - + set { this._scriptTemplate = value; @@ -45,7 +45,7 @@ public string ElementId { return this._elementId; } - + set { this._elementId = value; @@ -58,7 +58,7 @@ public bool InjectTop { return this._injectTop; } - + set { this._injectTop = value; diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs index 4ce0e757107..3b6cffd8776 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineCollection.cs @@ -15,7 +15,7 @@ public virtual AnalyticsEngine this[int index] { return (AnalyticsEngine)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs index dca96466c54..80c5c5860c0 100644 --- a/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs +++ b/DNN Platform/HttpModules/Analytics/Config/AnalyticsEngineConfiguration.cs @@ -38,7 +38,7 @@ public AnalyticsEngineCollection AnalyticsEngines { return this._analyticsEngines; } - + set { this._analyticsEngines = value; @@ -64,16 +64,16 @@ 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); } - + if (File.Exists(filePath)) { // Set back into Cache @@ -86,11 +86,11 @@ public static AnalyticsEngineConfiguration GetConfig() // log it var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.AddProperty("Analytics.AnalyticsEngineConfiguration", "GetConfig Failed"); - if (!string.IsNullOrEmpty(filePath)) - { - log.AddProperty("FilePath", filePath); - } - + if (!string.IsNullOrEmpty(filePath)) + { + log.AddProperty("FilePath", filePath); + } + log.AddProperty("ExceptionMessage", ex.Message); LogController.Instance.AddLog(log); Logger.Error(log); @@ -103,7 +103,7 @@ public static AnalyticsEngineConfiguration GetConfig() fileReader.Close(); } } - + return config; } } diff --git a/DNN Platform/HttpModules/Compression/CompressionModule.cs b/DNN Platform/HttpModules/Compression/CompressionModule.cs index 62b43cd30da..7e032547dcd 100644 --- a/DNN Platform/HttpModules/Compression/CompressionModule.cs +++ b/DNN Platform/HttpModules/Compression/CompressionModule.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.HttpModules.Compression [Obsolete("The http modules in web.config removed in 9.2.0, this class need to be removed in future release for upgrade compactible.. Scheduled removal in v11.0.0.")] public class CompressionModule : IHttpModule - { + { /// /// Init the handler and fulfill . /// @@ -35,6 +35,6 @@ public void Init(HttpApplication context) /// public void Dispose() { - } + } } } diff --git a/DNN Platform/HttpModules/Compression/Config/Settings.cs b/DNN Platform/HttpModules/Compression/Config/Settings.cs index f369c1c5d69..6dce1dd5e69 100644 --- a/DNN Platform/HttpModules/Compression/Config/Settings.cs +++ b/DNN Platform/HttpModules/Compression/Config/Settings.cs @@ -52,7 +52,7 @@ public Algorithms PreferredAlgorithm /// /// Get the current settings from the xml config file. - /// + ///
    /// public static Settings GetSettings() { @@ -60,7 +60,7 @@ public static Settings GetSettings() if (settings == null) { settings = Default; - + // Place this in a try/catch as during install the host settings will not exist try { @@ -82,14 +82,14 @@ public static Settings GetSettings() settings._excludedPaths.Add(nav.Value.ToLowerInvariant()); } } - + if (File.Exists(filePath)) { // Set back into Cache DataCache.SetCache("CompressionConfig", settings, new DNNCacheDependency(filePath)); } } - + return settings; } @@ -109,7 +109,7 @@ public bool IsExcludedPath(string relUrl) break; } } - + return match; } } diff --git a/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs b/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs index 070291ae25d..62c4379e383 100644 --- a/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/CompressingFilter.cs @@ -17,14 +17,14 @@ namespace DotNetNuke.HttpModules.Compression /// public abstract class CompressingFilter : HttpOutputFilter { - private bool _HasWrittenHeaders; - - /// + private bool _HasWrittenHeaders; + + /// /// Initializes a new instance of the class. /// Protected constructor that sets up the underlying stream we're compressing into. /// /// The stream we're wrapping up. - protected CompressingFilter(Stream baseStream) + protected CompressingFilter(Stream baseStream) : base(baseStream) { } diff --git a/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs b/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs index 25229305e32..762a69efb9d 100644 --- a/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/DeflateFilter.cs @@ -13,7 +13,7 @@ public class DeflateFilter : CompressingFilter { private readonly DeflateStream m_stream; - public DeflateFilter(Stream baseStream) + public DeflateFilter(Stream baseStream) : base(baseStream) { this.m_stream = new DeflateStream(baseStream, CompressionMode.Compress); @@ -33,7 +33,7 @@ public override void Write(byte[] buffer, int offset, int count) { this.WriteHeaders(); } - + this.m_stream.Write(buffer, offset, count); } diff --git a/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs b/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs index 79b993b87cc..2fd78378d90 100644 --- a/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/GZipFilter.cs @@ -13,7 +13,7 @@ public class GZipFilter : CompressingFilter { private readonly GZipStream m_stream; - public GZipFilter(Stream baseStream) + public GZipFilter(Stream baseStream) : base(baseStream) { this.m_stream = new GZipStream(baseStream, CompressionMode.Compress); @@ -33,7 +33,7 @@ public override void Write(byte[] buffer, int offset, int count) { this.WriteHeaders(); } - + this.m_stream.Write(buffer, offset, count); } diff --git a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs index c73dc96310c..89e9ccd2586 100644 --- a/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs +++ b/DNN Platform/HttpModules/Compression/Filters/HttpOutputFilter.cs @@ -31,14 +31,6 @@ public override bool CanSeek } } - protected Stream BaseStream - { - get - { - return this._sink; - } - } - public override bool CanWrite { get @@ -61,13 +53,21 @@ public override long Position { throw new NotSupportedException(); } - + set { throw new NotSupportedException(); } } + protected Stream BaseStream + { + get + { + return this._sink; + } + } + public override long Seek(long offset, SeekOrigin direction) { throw new NotSupportedException(); diff --git a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs index e9eadf74035..11853f29e93 100644 --- a/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs +++ b/DNN Platform/HttpModules/DependencyInjection/ServiceRequestScopeModule.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.HttpModules.DependencyInjection public class ServiceRequestScopeModule : IHttpModule { private static IServiceProvider _serviceProvider; - + public static void InitModule() { DynamicModuleUtility.RegisterModule(typeof(ServiceRequestScopeModule)); diff --git a/DNN Platform/HttpModules/Exception/ExceptionModule.cs b/DNN Platform/HttpModules/Exception/ExceptionModule.cs index 99a505b3672..c93241665b7 100644 --- a/DNN Platform/HttpModules/Exception/ExceptionModule.cs +++ b/DNN Platform/HttpModules/Exception/ExceptionModule.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.HttpModules.Exceptions public class ExceptionModule : IHttpModule { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExceptionModule)); - + /// /// Gets the name of the module. /// @@ -29,8 +29,8 @@ public string ModuleName { return "ExceptionModule"; } - } - + } + /// /// Initializes the error handling for the specified application. /// @@ -42,8 +42,8 @@ public void Init(HttpApplication application) public void Dispose() { - } - + } + /// /// Called when error handling is requested. /// diff --git a/DNN Platform/HttpModules/Membership/MembershipModule.cs b/DNN Platform/HttpModules/Membership/MembershipModule.cs index f3135359d83..79ba22d01a0 100644 --- a/DNN Platform/HttpModules/Membership/MembershipModule.cs +++ b/DNN Platform/HttpModules/Membership/MembershipModule.cs @@ -39,7 +39,7 @@ public class MembershipModule : IHttpModule private static readonly Regex NameRegex = new Regex(@"\w+[\\]+(?=)", RegexOptions.Compiled); private static string _cultureCode; - + /// /// Gets the name of the module. /// @@ -65,8 +65,8 @@ private static string CurrentCulture return _cultureCode; } - } - + } + /// /// Called when unverified user skin initialize. /// @@ -110,7 +110,7 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow if (request.IsAuthenticated && !isActiveDirectoryAuthHeaderPresent && portalSettings != null) { var user = UserController.GetCachedUser(portalSettings.PortalId, context.User.Identity.Name); - + // if current login is from windows authentication, the ignore the process if (user == null && context.User is WindowsPrincipal) { @@ -188,7 +188,7 @@ public static void AuthenticateRequest(HttpContextBase context, bool allowUnknow context.Items.Add("UserInfo", new UserInfo()); } } - + /// /// Initializes the specified application. /// @@ -204,36 +204,6 @@ public void Init(HttpApplication application) /// 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) @@ -263,5 +233,35 @@ private static bool RequireLogout(HttpContextBase context, UserInfo user) return true; } } + + 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); + } + } + } + } } } diff --git a/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs b/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs index b5ba2015973..60fc5c92a80 100644 --- a/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs +++ b/DNN Platform/HttpModules/MobileRedirect/MobileRedirectModule.cs @@ -16,12 +16,12 @@ namespace DotNetNuke.HttpModules public class MobileRedirectModule : IHttpModule { - private IRedirectionController _redirectionController; private readonly IList _specialPages = new List { "/login.aspx", "/register.aspx", "/terms.aspx", "/privacy.aspx", "/login", "/register", "/terms", "/privacy" }; private readonly Regex MvcServicePath = new Regex(@"DesktopModules/MVC/", RegexOptions.Compiled); - - public string ModuleName => "MobileRedirectModule"; - + private IRedirectionController _redirectionController; + + public string ModuleName => "MobileRedirectModule"; + public void Init(HttpApplication application) { this._redirectionController = new RedirectionController(); @@ -30,8 +30,8 @@ public void Init(HttpApplication application) public void Dispose() { - } - + } + public void OnBeginRequest(object s, EventArgs e) { var app = (HttpApplication)s; @@ -66,7 +66,7 @@ public void OnBeginRequest(object s, EventArgs e) { redirectUrl = string.Concat(redirectUrl, redirectUrl.Contains("?") ? "&" : "?", queryString); } - + app.Response.Redirect(redirectUrl); } } @@ -100,7 +100,7 @@ private bool IsSpecialPage(string url) { tabPath = tabPath.Replace(alias.Substring(idx), string.Empty); } - + return this._specialPages.Contains(tabPath); } } diff --git a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs index a86efdde995..84d18926f1a 100644 --- a/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs +++ b/DNN Platform/HttpModules/OutputCaching/OutputCacheModule.cs @@ -25,14 +25,14 @@ public class OutputCacheModule : IHttpModule private const string ContextKeyResponseFilter = "OutputCache:ResponseFilter"; private const string ContextKeyTabId = "OutputCache:TabId"; private const string ContextKeyTabOutputCacheProvider = "OutputCache:TabOutputCacheProvider"; - private HttpApplication _app; - + private HttpApplication _app; + private enum IncludeExcludeType { IncludeByDefault, ExcludeByDefault, - } - + } + public void Init(HttpApplication httpApp) { this._app = httpApp; @@ -40,11 +40,11 @@ public void Init(HttpApplication httpApp) httpApp.ResolveRequestCache += this.OnResolveRequestCache; httpApp.UpdateRequestCache += this.OnUpdateRequestCache; } - + public void Dispose() { - } - + } + private bool IsInstallInProgress(HttpApplication app) { return InstallBlocker.Instance.IsInstallInProgress(); @@ -67,7 +67,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) { return; } - + var portalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; int tabId = portalSettings.ActiveTab.TabID; @@ -93,7 +93,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) includeExclude = IncludeExcludeType.IncludeByDefault; } } - + string tabOutputCacheProvider = tabSettings["CacheProvider"].ToString(); this._app.Context.Items[ContextKeyTabOutputCacheProvider] = tabOutputCacheProvider; int maxCachedVariationsForTab = 250; // by default, prevent DOS attacks @@ -109,7 +109,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) includeVaryByKeys.Add("portalid"); includeVaryByKeys.Add("locale"); includeVaryByKeys.Add("alias"); - + // make sure to always add keys in lowercase only if (includeExclude == IncludeExcludeType.ExcludeByDefault) { @@ -135,7 +135,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) } } } - + var excludeVaryByKeys = new StringCollection(); if (includeExclude == IncludeExcludeType.IncludeByDefault) { @@ -177,27 +177,27 @@ private void OnResolveRequestCache(object sender, EventArgs e) } } } - + if (!varyBy.ContainsKey("portalid")) { varyBy.Add("portalid", portalId.ToString()); } - + if (!varyBy.ContainsKey("tabid")) { varyBy.Add("tabid", tabId.ToString()); } - + if (!varyBy.ContainsKey("locale")) { varyBy.Add("locale", locale); } - + if (!varyBy.ContainsKey("alias")) { varyBy.Add("alias", portalSettings.PortalAlias.HTTPAlias); } - + string cacheKey = OutputCachingProvider.Instance(tabOutputCacheProvider).GenerateCacheKey(tabId, includeVaryByKeys, excludeVaryByKeys, varyBy); bool returnedFromCache = OutputCachingProvider.Instance(tabOutputCacheProvider).StreamOutput(tabId, cacheKey, this._app.Context); @@ -206,7 +206,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) { // output the content type heade when read content from cache. this._app.Context.Response.AddHeader("Content-Type", string.Format("{0}; charset={1}", this._app.Response.ContentType, this._app.Response.Charset)); - + // This is to give a site owner the ability // to visually verify that a page was rendered via // the output cache. Use FireFox FireBug or another @@ -230,7 +230,7 @@ private void OnResolveRequestCache(object sender, EventArgs e) int seconds = Convert.ToInt32(tabSettings["CacheDuration"].ToString()); var duration = new TimeSpan(0, 0, seconds); - OutputCacheResponseFilter responseFilter = OutputCachingProvider.Instance(this._app.Context.Items[ContextKeyTabOutputCacheProvider].ToString()).GetResponseFilter( + OutputCacheResponseFilter responseFilter = OutputCachingProvider.Instance(this._app.Context.Items[ContextKeyTabOutputCacheProvider].ToString()).GetResponseFilter( Convert.ToInt32(this._app.Context.Items[ContextKeyTabId]), maxCachedVariationsForTab, this._app.Response.Filter, @@ -252,6 +252,6 @@ private void OnUpdateRequestCache(object sender, EventArgs e) responseFilter.StopFiltering(Convert.ToInt32(this._app.Context.Items[ContextKeyTabId]), false); } } - } + } } } diff --git a/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs b/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs index 23f91c38843..2055ea7ef8c 100644 --- a/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs +++ b/DNN Platform/HttpModules/Personalization/PersonalizationModule.cs @@ -19,8 +19,8 @@ public string ModuleName { return "PersonalizationModule"; } - } - + } + public void Init(HttpApplication application) { application.EndRequest += this.OnEndRequest; @@ -28,8 +28,8 @@ public void Init(HttpApplication application) public void Dispose() { - } - + } + public void OnEndRequest(object s, EventArgs e) { HttpContext context = ((HttpApplication)s).Context; diff --git a/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs b/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs index 2aa24cccdac..6833b9f6803 100644 --- a/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs +++ b/DNN Platform/HttpModules/RequestFilter/Config/RequestFilterSettings.cs @@ -37,7 +37,7 @@ public List Rules { return this._rules; } - + set { this._rules = value; @@ -46,7 +46,7 @@ public List Rules /// /// Get the current settings from the xml config file. - /// + ///
    /// public static RequestFilterSettings GetSettings() { @@ -79,14 +79,14 @@ public static RequestFilterSettings GetSettings() } } } - + if (File.Exists(filePath)) { // Set back into Cache DataCache.SetCache(RequestFilterConfig, settings, new DNNCacheDependency(filePath)); } } - + return settings; } @@ -101,7 +101,7 @@ public static void Save(List rules) File.Copy(defaultConfigFile, filePath, true); } } - + var doc = new XmlDocument { XmlResolver = null }; doc.Load(filePath); XmlNode ruleRoot = doc.SelectSingleNode("/configuration/blockrequests"); @@ -126,7 +126,7 @@ public static void Save(List rules) xmlRule.Attributes.Append(location); ruleRoot.AppendChild(xmlRule); } - + var settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(filePath, settings)) diff --git a/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs b/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs index 3aa9742af8f..2eb91a5675d 100644 --- a/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs +++ b/DNN Platform/HttpModules/RequestFilter/RequestFilterModule.cs @@ -13,8 +13,8 @@ namespace DotNetNuke.HttpModules.RequestFilter public class RequestFilterModule : IHttpModule { - private const string InstalledKey = "httprequestfilter.attemptedinstall"; - + private const string InstalledKey = "httprequestfilter.attemptedinstall"; + /// /// Implementation of . /// @@ -28,8 +28,8 @@ public void Dispose() public void Init(HttpApplication context) { context.BeginRequest += FilterRequest; - } - + } + private static void FilterRequest(object sender, EventArgs e) { var app = (HttpApplication)sender; @@ -37,7 +37,7 @@ private static void FilterRequest(object sender, EventArgs e) { return; } - + var request = app.Context.Request; if (!Initialize.ProcessHttpModule(request, true, true)) @@ -64,7 +64,7 @@ private static void FilterRequest(object sender, EventArgs e) { return; } - + foreach (var rule in settings.Rules) { // Added ability to determine the specific value types for addresses @@ -84,7 +84,7 @@ private static void FilterRequest(object sender, EventArgs e) break; } } - + if (!string.IsNullOrEmpty(varVal)) { if (rule.Matches(varVal)) diff --git a/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs b/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs index a0d996fe934..4ce95e35cd5 100644 --- a/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs +++ b/DNN Platform/HttpModules/RequestFilter/RequestFilterRule.cs @@ -15,9 +15,9 @@ public class RequestFilterRule private string _Location; private RequestFilterOperatorType _Operator; private string _ServerVariable; - private List _Values = new List(); - - /// + private List _Values = new List(); + + /// /// Initializes a new instance of the class. /// /// @@ -32,22 +32,30 @@ public RequestFilterRule(string serverVariable, string values, RequestFilterOper this._Operator = op; this._Action = action; this._Location = location; - } - - /// + } + + /// /// Initializes a new instance of the class. /// public RequestFilterRule() { } + public string RawValue + { + get + { + return string.Join(" ", this._Values.ToArray()); + } + } + public string ServerVariable { get { return this._ServerVariable; } - + set { this._ServerVariable = value; @@ -60,28 +68,20 @@ public List Values { return this._Values; } - + set { this._Values = value; } } - public string RawValue - { - get - { - return string.Join(" ", this._Values.ToArray()); - } - } - public RequestFilterRuleType Action { get { return this._Action; } - + set { this._Action = value; @@ -94,7 +94,7 @@ public RequestFilterOperatorType Operator { return this._Operator; } - + set { this._Operator = value; @@ -107,7 +107,7 @@ public string Location { return this._Location; } - + set { this._Location = value; @@ -142,7 +142,7 @@ public bool Matches(string ServerVariableValue) case RequestFilterOperatorType.Regex: return Regex.IsMatch(ServerVariableValue, this.Values[0], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } - + return false; } diff --git a/DNN Platform/HttpModules/Services/ServicesModule.cs b/DNN Platform/HttpModules/Services/ServicesModule.cs index dd281283f41..b04d524edfa 100644 --- a/DNN Platform/HttpModules/Services/ServicesModule.cs +++ b/DNN Platform/HttpModules/Services/ServicesModule.cs @@ -43,7 +43,7 @@ private void OnPreSendRequestHeaders(object sender, EventArgs e) // they reveal too much info and are security risk var headers = app.Response.Headers; headers.Remove("Server"); - + // DNN-8325 // if (ServiceApi.IsMatch(app.Context.Request.RawUrl.ToLowerInvariant())) // { diff --git a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs index 11aa4c84148..1ba660e0f20 100644 --- a/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs +++ b/DNN Platform/HttpModules/UrlRewrite/BasicUrlRewriter.cs @@ -25,10 +25,10 @@ namespace DotNetNuke.HttpModules.UrlRewrite internal class BasicUrlRewriter : UrlRewriterBase { 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); - + 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; @@ -59,7 +59,7 @@ internal override void RewriteUrl(object sender, EventArgs e) { DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } - + try { // fix for ASP.NET canonicalization issues http://support.microsoft.com/?kbid=887459 @@ -75,7 +75,7 @@ internal override void RewriteUrl(object sender, EventArgs e) // example to test: http://localhost/dotnetnuke_2/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/default.aspx Logger.Error(exc); } - + string domainName; this.RewriteUrl(app, out domainName); @@ -119,7 +119,7 @@ internal override void RewriteUrl(object sender, EventArgs e) // The tabId or PortalId are incorrectly formatted (potential DOS) DotNetNuke.Services.Exceptions.Exceptions.ProcessHttpException(request); } - + try { // alias parameter can be used to switch portals @@ -178,12 +178,12 @@ internal override void RewriteUrl(object sender, EventArgs e) { strURL = "http://" + portalAliasInfo.HTTPAlias.Replace("*.", string.Empty); } - + if (strURL.IndexOf(domainName, StringComparison.InvariantCultureIgnoreCase) == -1) { strURL += app.Request.Url.PathAndQuery; } - + response.Redirect(strURL, true); } } @@ -195,7 +195,7 @@ internal override void RewriteUrl(object sender, EventArgs e) { portalAlias = domainName; } - + // using the DomainName above will find that alias that is the domainname portion of the Url // ie. dotnetnuke.com will be found even if zzz.dotnetnuke.com was entered on the Url portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias); @@ -235,7 +235,7 @@ internal override void RewriteUrl(object sender, EventArgs e) HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer(strURL); } - + if (portalId != -1) { // load the PortalSettings into current context @@ -246,10 +246,10 @@ internal override void RewriteUrl(object sender, EventArgs e) // specifically for use in DotNetNuke.Web.Client, which can't reference DotNetNuke.dll to get settings the normal way app.Context.Items.Add("PortalSettingsDictionary", PortalController.Instance.GetPortalSettings(portalId)); app.Context.Items.Add("HostSettingsDictionary", HostController.Instance.GetSettingsDictionary()); - + 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; @@ -290,7 +290,7 @@ internal override void RewriteUrl(object sender, EventArgs e) { // request is for a standard page strURL = string.Empty; - + // if SSL is enabled if (portalSettings.SSLEnabled) { @@ -303,7 +303,7 @@ internal override void RewriteUrl(object sender, EventArgs e) strURL = this.FormatDomain(strURL, portalSettings.STDURL, portalSettings.SSLURL); } } - + // if SSL is enforced if (portalSettings.SSLEnforced) { @@ -327,21 +327,21 @@ internal override void RewriteUrl(object sender, EventArgs e) // redirect to secure connection response.RedirectPermanent(strURL); } - else - - // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning + else + + // when switching to an unsecure page, use a clientside redirector to avoid the browser security warning { response.Clear(); - + // add a refresh header to the response response.AddHeader("Refresh", "0;URL=" + strURL); - + // add the clientside javascript redirection script response.Write(""); response.Write(""); response.Write(""); - + // send the response response.End(); } @@ -366,9 +366,9 @@ internal override void RewriteUrl(object sender, EventArgs e) // Process any messages in the EventQueue for the Application_Start_FirstRequest event EventQueueController.ProcessMessages("Application_Start_FirstRequest"); } - } - - // Note these formerly lived in the 'UrlRewriteModule.cs' class + } + + // Note these formerly lived in the 'UrlRewriteModule.cs' class private string FormatDomain(string url, string replaceDomain, string withDomain) { if (!string.IsNullOrEmpty(replaceDomain) && !string.IsNullOrEmpty(withDomain)) @@ -378,7 +378,7 @@ private string FormatDomain(string url, string replaceDomain, string withDomain) url = url.Replace(replaceDomain, withDomain); } } - + return url; } @@ -387,7 +387,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) HttpRequest request = app.Request; HttpResponse response = app.Response; string requestedPath = app.Request.Url.AbsoluteUri; - + portalAlias = string.Empty; // determine portal alias looking for longest possible match @@ -405,9 +405,9 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) int slashIndex = myAlias.LastIndexOf('/'); myAlias = slashIndex > 1 ? myAlias.Substring(0, slashIndex) : string.Empty; - } + } while (myAlias.Length > 0); - + app.Context.Items.Add("UrlRewrite:OriginalUrl", app.Request.Url.AbsoluteUri); // Friendly URLs are exposed externally using the following format @@ -443,26 +443,26 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) if (objMatch.Success) { // create a new URL using the SendTo regex value - sendTo = RewriterUtils.ResolveUrl( + sendTo = RewriterUtils.ResolveUrl( app.Context.Request.ApplicationPath, Regex.Replace(requestedPath, pattern, rules[ruleIndex].SendTo, RegexOptions.IgnoreCase)); string parameters = objMatch.Groups[2].Value; - + // process the parameters if (parameters.Trim().Length > 0) { // split the value into an array based on "/" ( ie. /tabid/##/ ) parameters = parameters.Replace("\\", "/"); string[] splitParameters = parameters.Split('/'); - + // icreate a well formed querystring based on the array of parameters for (int parameterIndex = 0; parameterIndex < splitParameters.Length; parameterIndex++) { // ignore the page name if ( - splitParameters[parameterIndex].IndexOf( + splitParameters[parameterIndex].IndexOf( ".aspx", StringComparison.InvariantCultureIgnoreCase) == -1) @@ -473,17 +473,17 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { // add parameter to SendTo if it does not exist already if ( - sendTo.IndexOf( + sendTo.IndexOf( "?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 && - sendTo.IndexOf( + sendTo.IndexOf( "&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1) { // get parameter delimiter string parameterDelimiter = sendTo.IndexOf("?", StringComparison.Ordinal) != -1 ? "&" : "?"; sendTo = sendTo + parameterDelimiter + parameterName; - + // get parameter value string parameterValue = string.Empty; if (parameterIndex < splitParameters.Length - 1) @@ -494,7 +494,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) parameterValue = splitParameters[parameterIndex].Trim(); } } - + // add the parameter value if (parameterValue.Length > 0) { @@ -505,17 +505,17 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } } } - + matchIndex = ruleIndex; break; // exit as soon as it processes the first match } } - + if (!string.IsNullOrEmpty(strQueryString)) { // add querystring parameters back to SendTo string[] parameters = strQueryString.Split('&'); - + // iterate through the array of parameters for (int parameterIndex = 0; parameterIndex <= parameters.Length - 1; parameterIndex++) { @@ -525,7 +525,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { parameterName = parameterName.Substring(0, parameterName.IndexOf("=", StringComparison.Ordinal)); } - + // check if parameter already exists if (sendTo.IndexOf("?" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1 && sendTo.IndexOf("&" + parameterName + "=", StringComparison.InvariantCultureIgnoreCase) == -1) @@ -572,14 +572,14 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) if (objPortalAlias != null) { int portalID = objPortalAlias.PortalID; - + // Identify Tab Name string tabPath = url; if (tabPath.StartsWith(myAlias)) { tabPath = url.Remove(0, myAlias.Length); } - + // Default Page has been Requested if (tabPath == "/" + Globals.glbDefaultPage.ToLowerInvariant()) { @@ -612,7 +612,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } // Check to see if the tab exists (if localization is enable, check for the specified culture) - int tabID = TabController.GetTabByTabPath( + int tabID = TabController.GetTabByTabPath( portalID, tabPath.Replace("/", "//").Replace(".aspx", string.Empty), cultureCode); @@ -620,11 +620,11 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) // Check to see if neutral culture tab exists if (tabID == Null.NullInteger && cultureCode.Length > 0) { - tabID = TabController.GetTabByTabPath( + tabID = TabController.GetTabByTabPath( portalID, tabPath.Replace("/", "//").Replace(".aspx", string.Empty), string.Empty); } - + // End of patch if (tabID != Null.NullInteger) { @@ -633,16 +633,16 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { sendToUrl = sendToUrl + "&language=" + cultureCode; } - + if (!string.IsNullOrEmpty(app.Request.Url.Query)) { sendToUrl = sendToUrl + "&" + app.Request.Url.Query.TrimStart('?'); } - + RewriterUtils.RewriteUrl(app.Context, sendToUrl); return; } - + tabPath = tabPath.ToLowerInvariant(); if (tabPath.IndexOf('?') != -1) { @@ -658,21 +658,21 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) requestQuery = PortalIdRegex.Replace(requestQuery, string.Empty); requestQuery = requestQuery.TrimStart('?', '&'); } - + if (tabPath == "/login.aspx") { if (portal.LoginTabId > Null.NullInteger && Globals.ValidateLoginTabID(portal.LoginTabId)) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId + "&" + requestQuery); } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.LoginTabId); @@ -682,7 +682,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login&" + @@ -690,23 +690,23 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=login"); } } - + return; } - + if (tabPath == "/register.aspx") { if (portal.RegisterTabId > Null.NullInteger) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID + "&" + @@ -714,7 +714,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.RegisterTabId + "&portalid=" + portalID); @@ -724,7 +724,7 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + @@ -732,57 +732,57 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Register"); } } - + return; } - + if (tabPath == "/terms.aspx") { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms&" + requestQuery); } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Terms"); } - + return; } - + if (tabPath == "/privacy.aspx") { if (!string.IsNullOrEmpty(requestQuery)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy&" + requestQuery); } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + portal.HomeTabId + "&portalid=" + portalID + "&ctl=Privacy"); } - + return; } - + tabPath = tabPath.Replace("/", "//"); tabPath = tabPath.Replace(".aspx", string.Empty); TabCollection objTabs = TabController.Instance.GetTabsByPortal(tabPath.StartsWith("//host") ? Null.NullInteger : portalID); @@ -792,24 +792,24 @@ private void RewriteUrl(HttpApplication app, out string portalAlias) { if (!string.IsNullOrEmpty(app.Request.Url.Query)) { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID + "&" + app.Request.Url.Query.TrimStart('?')); } else { - RewriterUtils.RewriteUrl( + RewriterUtils.RewriteUrl( app.Context, "~/" + Globals.glbDefaultPage + "?TabID=" + kvp.Value.TabID); } - + return; } } } } } - } + } } } diff --git a/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs b/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs index 884d5d5edf3..bf011b11b81 100644 --- a/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs +++ b/DNN Platform/HttpModules/UrlRewrite/FriendlyUrlProvider.cs @@ -50,7 +50,7 @@ public DNNFriendlyUrlProvider() break; } } - + // instance the correct provider implementation switch (this._urlFormat) { diff --git a/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs b/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs index c5e52088b6c..01a3e707026 100644 --- a/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs +++ b/DNN Platform/HttpModules/UrlRewrite/UrlRewriteModule.cs @@ -17,8 +17,8 @@ public class UrlRewriteModule : IHttpModule public string ModuleName { get { return "UrlRewriteModule"; } - } - + } + public void Init(HttpApplication application) { this._providerToUse = DotNetNuke.Common.Utilities.Config.GetFriendlyUrlProvider(); @@ -31,7 +31,7 @@ public void Init(HttpApplication application) case "advanced": var advancedRewriter = new AdvancedUrlRewriter(); this._urlRewriter = advancedRewriter; - + // bind the rewrite event to the begin request event application.BeginRequest += this._urlRewriter.RewriteUrl; break; @@ -45,6 +45,6 @@ public void Init(HttpApplication application) public void Dispose() { - } + } } } diff --git a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs index 6ee0d7d1024..636d49025b8 100644 --- a/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs +++ b/DNN Platform/HttpModules/Users Online/UsersOnlineModule.cs @@ -19,8 +19,8 @@ public string ModuleName { return "UsersOnlineModule"; } - } - + } + public void Init(HttpApplication application) { application.AuthorizeRequest += this.OnAuthorizeRequest; @@ -28,8 +28,8 @@ public void Init(HttpApplication application) public void Dispose() { - } - + } + [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 OnAuthorizeRequest(object s, EventArgs e) { diff --git a/DNN Platform/Library/Application/Application.cs b/DNN Platform/Library/Application/Application.cs index 3db14dbd800..194b44e673c 100644 --- a/DNN Platform/Library/Application/Application.cs +++ b/DNN Platform/Library/Application/Application.cs @@ -133,7 +133,7 @@ public ReleaseMode Status } } } - + return _status; } } @@ -187,7 +187,7 @@ public string UpgradeUrl { return "https://dnnplatform.io"; } - + return url; } } @@ -216,8 +216,8 @@ public virtual Version Version var fileVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).FileVersion; return new Version(fileVersion); } - } - + } + /// /// Determine whether a product specific change is to be applied. /// @@ -228,6 +228,6 @@ public virtual Version Version public virtual bool ApplyToProduct(string productNames) { return productNames.Contains(this.Name); - } + } } } diff --git a/DNN Platform/Library/Application/AssemblyStatusAttribute.cs b/DNN Platform/Library/Application/AssemblyStatusAttribute.cs index 324e8c1f3b4..ad09d72bd6b 100644 --- a/DNN Platform/Library/Application/AssemblyStatusAttribute.cs +++ b/DNN Platform/Library/Application/AssemblyStatusAttribute.cs @@ -68,7 +68,7 @@ public AssemblyStatusAttribute(ReleaseMode releaseMode) { this._releaseMode = releaseMode; } - + /// /// Gets status of current assembly. /// diff --git a/DNN Platform/Library/Application/DotNetNukeContext.cs b/DNN Platform/Library/Application/DotNetNukeContext.cs index 558ad76b508..ef2ac0dd2c6 100644 --- a/DNN Platform/Library/Application/DotNetNukeContext.cs +++ b/DNN Platform/Library/Application/DotNetNukeContext.cs @@ -22,7 +22,7 @@ public class DotNetNukeContext /// /// Initializes a new instance of the class. /// - protected DotNetNukeContext() + protected DotNetNukeContext() : this(new Application()) { } @@ -49,10 +49,10 @@ public static DotNetNukeContext Current { _current = new DotNetNukeContext(); } - + return _current; } - + set { _current = value; diff --git a/DNN Platform/Library/Collections/CollectionExtensions.cs b/DNN Platform/Library/Collections/CollectionExtensions.cs index fa8051c7818..5d7f3fe9e73 100644 --- a/DNN Platform/Library/Collections/CollectionExtensions.cs +++ b/DNN Platform/Library/Collections/CollectionExtensions.cs @@ -47,19 +47,19 @@ public static Dictionary CreateDictionaryFromString(string strin { key = keyValues[0]; } - + if (keyValues.GetUpperBound(0) >= 1) { value = keyValues[1]; } - + if (!string.IsNullOrEmpty(key) && value != null && !dictionary.ContainsKey(key)) { dictionary.Add(key, value); } } } - + return dictionary; } @@ -97,8 +97,8 @@ public static Func GetFlexibleBooleanParsingFunction() public static Func GetFlexibleBooleanParsingFunction(params string[] trueValues) { return value => trueValues.Contains(value, StringComparer.OrdinalIgnoreCase); - } - + } + /// Gets the value from the dictionary. /// The type of the value to retrieve. /// The dictionary. @@ -326,8 +326,8 @@ public static T GetValue(this NameValueCollection collection, string key, Fun public static T GetValue(this XContainer node, string key, Func converter) { return node.ToDictionary().GetValue(key, converter); - } - + } + /// Gets the value from the dictionary, returning the default value of if the value doesn't exist. /// The type of the value to retrieve. /// The dictionary. @@ -763,10 +763,10 @@ public static T GetValueOrDefault(this IDictionary dictionary, string key, T { Logger.ErrorFormat("Error loading portal setting: {0} Default value {1} was used instead", key + ":" + dictionary[key], defaultValue.ToString()); } - + return value; - } - + } + /// Gets the values from the lookup. /// The type of the values to retrieve. /// The lookup. @@ -814,8 +814,8 @@ public static IEnumerable GetValues(this ILookup lookup, s public static IEnumerable GetValues(this NameValueCollection collection, string key, Func converter) { return collection.ToLookup().GetValues(key, converter); - } - + } + /// Converts the to an . /// The collection. /// An instance. @@ -853,8 +853,8 @@ public static IEnumerable ForEach(this IEnumerable source, } return source; - } - + } + /// Converts the into a instance. /// The type of the value to return. /// The value to convert. @@ -970,6 +970,6 @@ private static Dictionary ToDictionary(this ILookup items) { var data = items.ToArray(); - if (!data.Any()) - { - return null; - } - + if (!data.Any()) + { + return null; + } + var dt = new DataTable(); // Create the columns @@ -40,7 +40,7 @@ public static DataTable ToDataTable(this IEnumerable items) { dt.Rows.Add(((IDictionary)d).Values.ToArray()); } - + return dt; } } diff --git a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs index d72c81f00b2..e278ffea3d0 100644 --- a/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs +++ b/DNN Platform/Library/Collections/ExclusiveLockStrategy.cs @@ -11,7 +11,7 @@ public class ExclusiveLockStrategy : ILockStrategy private readonly object _lock = new object(); private bool _isDisposed; - private Thread _lockedThread; + private Thread _lockedThread; public bool ThreadCanRead { @@ -38,7 +38,7 @@ public bool SupportsConcurrentReads return false; } } - + public ISharedCollectionLock GetReadLock() { return this.GetLock(TimeSpan.FromMilliseconds(-1)); @@ -62,9 +62,9 @@ public ISharedCollectionLock GetWriteLock(TimeSpan timeout) public void Dispose() { this._isDisposed = true; - + // todo remove disposable from interface? - } + } public void Exit() { @@ -72,7 +72,7 @@ public void Exit() Monitor.Exit(this._lock); this._lockedThread = null; } - + private ISharedCollectionLock GetLock(TimeSpan timeout) { this.EnsureNotDisposed(); diff --git a/DNN Platform/Library/Collections/ILockStrategy.cs b/DNN Platform/Library/Collections/ILockStrategy.cs index 67956cdaa80..de9477f935f 100644 --- a/DNN Platform/Library/Collections/ILockStrategy.cs +++ b/DNN Platform/Library/Collections/ILockStrategy.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.Collections.Internal public interface ILockStrategy : IDisposable { bool ThreadCanRead { get; } - + bool ThreadCanWrite { get; } - + bool SupportsConcurrentReads { get; } ISharedCollectionLock GetReadLock(); diff --git a/DNN Platform/Library/Collections/ISharedCollectionLock.cs b/DNN Platform/Library/Collections/ISharedCollectionLock.cs index e8c77527704..1667793facd 100644 --- a/DNN Platform/Library/Collections/ISharedCollectionLock.cs +++ b/DNN Platform/Library/Collections/ISharedCollectionLock.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Collections.Internal using System; public interface ISharedCollectionLock : IDisposable - { - } + {} } diff --git a/DNN Platform/Library/Collections/MonitorLock.cs b/DNN Platform/Library/Collections/MonitorLock.cs index 3ad20df1ddc..acc73bd56b0 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 + + // To detect redundant calls private bool _isDisposed; public MonitorLock(ExclusiveLockStrategy lockStrategy) { this._lockStrategy = lockStrategy; - } - + } + public void Dispose() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. @@ -34,8 +34,8 @@ protected virtual void Dispose(bool disposing) this._lockStrategy = null; } } - + this._isDisposed = true; - } + } } } diff --git a/DNN Platform/Library/Collections/NaiveLockingList.cs b/DNN Platform/Library/Collections/NaiveLockingList.cs index c869481f8bb..f4b98675b3a 100644 --- a/DNN Platform/Library/Collections/NaiveLockingList.cs +++ b/DNN Platform/Library/Collections/NaiveLockingList.cs @@ -48,7 +48,7 @@ public T this[int index] { return this.DoInReadLock(() => this._list[index]); } - + set { this.DoInWriteLock(() => this._list[index] = value); @@ -64,46 +64,6 @@ public IEnumerator GetEnumerator() 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) - { - this.DoInReadLock(() => - { - action.Invoke(); - return true; - }); - } - - private TRet DoInReadLock(Func func) - { - using (this._list.GetReadLock()) - { - return func.Invoke(); - } - } - - private void DoInWriteLock(Action action) - { - this.DoInWriteLock(() => - { - action.Invoke(); - return true; - }); - } - - private TRet DoInWriteLock(Func func) - { - using (this._list.GetWriteLock()) - { - return func.Invoke(); - } - } - public void Add(T item) { this.DoInWriteLock(() => this._list.Add(item)); @@ -144,11 +104,51 @@ public void RemoveAt(int index) this.DoInWriteLock(() => this._list.RemoveAt(index)); } + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator(); + } + + // TODO is no recursion the correct policy + private void DoInReadLock(Action action) + { + this.DoInReadLock(() => + { + action.Invoke(); + return true; + }); + } + + private TRet DoInReadLock(Func func) + { + using (this._list.GetReadLock()) + { + return func.Invoke(); + } + } + + private void DoInWriteLock(Action action) + { + this.DoInWriteLock(() => + { + action.Invoke(); + return true; + }); + } + + private TRet DoInWriteLock(Func func) + { + using (this._list.GetWriteLock()) + { + return func.Invoke(); + } + } + public class NaiveLockingEnumerator : IEnumerator { private readonly IEnumerator _enumerator; - private bool _isDisposed; private readonly ISharedCollectionLock _readLock; + private bool _isDisposed; public NaiveLockingEnumerator(IEnumerator enumerator, ISharedCollectionLock readLock) { diff --git a/DNN Platform/Library/Collections/PagedList.cs b/DNN Platform/Library/Collections/PagedList.cs index b02c345eee0..43c136d7bd7 100644 --- a/DNN Platform/Library/Collections/PagedList.cs +++ b/DNN Platform/Library/Collections/PagedList.cs @@ -15,8 +15,8 @@ namespace DotNetNuke.Collections /// /// The type of objects contained in this list. public class PagedList : List, IPagedList - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new instance of the a paged list containing objects from the selected enumerable source. /// @@ -27,9 +27,9 @@ public PagedList(IEnumerable source, int pageIndex, int pageSize) { var enumerable = source as T[] ?? source.ToArray(); this.CommonConstruct(enumerable.Skip(pageIndex * pageSize).Take(pageSize).ToList(), enumerable.Count(), pageIndex, pageSize); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the a paged list containing objects from the selected enumerable source. /// @@ -40,8 +40,8 @@ public PagedList(IEnumerable source, int pageIndex, int pageSize) public PagedList(IEnumerable items, int totalCount, int pageIndex, int pageSize) { this.CommonConstruct(items, totalCount, pageIndex, pageSize); - } - + } + /// /// Gets a value indicating whether gets a boolean indicating if there is a next page available. /// @@ -56,7 +56,32 @@ public PagedList(IEnumerable items, int totalCount, int pageIndex, int pageSi /// 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. + /// + public bool IsLastPage { get; private set; } + + /// + /// Gets or sets the number of pages in this list. + /// + public int PageCount { get; set; } + + /// + /// Gets or sets the index of the page contained in this list. + /// + public int PageIndex { get; set; } + + /// + /// Gets or sets the size of the page in this list. + /// + public int PageSize { get; set; } + + /// + /// Gets or sets or ses the total number of objects in the data store. + /// + public int TotalCount { get; set; } + private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex, int pageSize) { this.PageCount = (int)Math.Ceiling(totalCount / (double)pageSize); @@ -74,13 +99,13 @@ private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex { throw new IndexOutOfRangeException("Index cannot be negative"); } - + if (pageIndex >= this.PageCount) { throw new IndexOutOfRangeException("Invalid Page Index"); } } - + this.TotalCount = totalCount; this.PageSize = pageSize; this.PageIndex = pageIndex; @@ -90,31 +115,6 @@ private void CommonConstruct(IEnumerable items, int totalCount, int pageIndex this.HasPreviousPage = this.PageIndex > 0; this.IsFirstPage = this.PageIndex <= 0; this.IsLastPage = this.PageIndex >= (this.PageCount - 1); - } - - /// - /// Gets a value indicating whether gets a boolean indicating if this is the last page. - /// - public bool IsLastPage { get; private set; } - - /// - /// Gets or sets the number of pages in this list. - /// - public int PageCount { get; set; } - - /// - /// Gets or sets the index of the page contained in this list. - /// - public int PageIndex { get; set; } - - /// - /// Gets or sets the size of the page in this list. - /// - public int PageSize { get; set; } - - /// - /// Gets or sets or ses the total number of objects in the data store. - /// - public int TotalCount { get; set; } + } } } diff --git a/DNN Platform/Library/Collections/PagedSelector.cs b/DNN Platform/Library/Collections/PagedSelector.cs index ec69fab021d..d76515efefc 100644 --- a/DNN Platform/Library/Collections/PagedSelector.cs +++ b/DNN Platform/Library/Collections/PagedSelector.cs @@ -16,9 +16,9 @@ namespace DotNetNuke.Collections public class PageSelector { private readonly int _pageSize; - private readonly IEnumerable _source; - - /// + private readonly IEnumerable _source; + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the for use on the specified data store. /// @@ -28,8 +28,8 @@ public PageSelector(IEnumerable source, int pageSize) { this._source = source; this._pageSize = pageSize; - } - + } + /// /// Retrieves the specified page as a . /// @@ -41,6 +41,6 @@ public PageSelector(IEnumerable source, int pageSize) public IPagedList GetPage(int pageIndex) { return new PagedList(this._source, pageIndex, this._pageSize); - } + } } } diff --git a/DNN Platform/Library/Collections/PagingExtensions.cs b/DNN Platform/Library/Collections/PagingExtensions.cs index 20ee86d2e39..73ff44896b2 100644 --- a/DNN Platform/Library/Collections/PagingExtensions.cs +++ b/DNN Platform/Library/Collections/PagingExtensions.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Collections /// Contains filters that can be applied to stores. /// public static class PagingExtensions - { + { /// /// Filters the incoming store to retrieve pages of a specified size. /// @@ -37,6 +37,6 @@ public static PageSelector InPagesOf(this IEnumerable source, int pageS public static IPagedList ToPagedList(this IEnumerable source, int pageIndex, int pageSize) { return new PagedList(source, pageIndex, pageSize); - } + } } } diff --git a/DNN Platform/Library/Collections/ReadLockRequiredException.cs b/DNN Platform/Library/Collections/ReadLockRequiredException.cs index 2bed480d2a6..78d4fec2df1 100644 --- a/DNN Platform/Library/Collections/ReadLockRequiredException.cs +++ b/DNN Platform/Library/Collections/ReadLockRequiredException.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Collections.Internal using System; public class ReadLockRequiredException : Exception - { - } + {} } diff --git a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs index fb70a956453..012d37ba46f 100644 --- a/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs +++ b/DNN Platform/Library/Collections/ReaderWriterLockStrategy.cs @@ -15,7 +15,7 @@ public class ReaderWriterLockStrategy : IDisposable, ILockStrategy private ReaderWriterLockSlim _lock; private LockRecursionPolicy _lockRecursionPolicy; - + private bool _isDisposed; public ReaderWriterLockStrategy() @@ -34,29 +34,13 @@ public ReaderWriterLockStrategy(SerializationInfo info, StreamingContext context { this._lockRecursionPolicy = (LockRecursionPolicy)info.GetValue("_lockRecursionPolicy", typeof(LockRecursionPolicy)); this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy); - } - - private ReaderWriterLockSlim Lock - { - get - { - return this._lock ?? (this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy)); - } - } - - // Implement this method to serialize data. The method is called - // on serialization. - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - // Use the AddValue method to specify serialized values. - info.AddValue("_lockRecursionPolicy", this._lockRecursionPolicy, typeof(LockRecursionPolicy)); } ~ReaderWriterLockStrategy() { // Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above. this.Dispose(false); - } + } public bool ThreadCanRead { @@ -82,8 +66,24 @@ public bool SupportsConcurrentReads { return true; } - } - + } + + private ReaderWriterLockSlim Lock + { + get + { + return this._lock ?? (this._lock = new ReaderWriterLockSlim(this._lockRecursionPolicy)); + } + } + + // Implement this method to serialize data. The method is called + // on serialization. + public void GetObjectData(SerializationInfo info, StreamingContext context) + { + // Use the AddValue method to specify serialized values. + info.AddValue("_lockRecursionPolicy", this._lockRecursionPolicy, typeof(LockRecursionPolicy)); + } + public ISharedCollectionLock GetReadLock() { return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); @@ -147,7 +147,7 @@ protected virtual void Dispose(bool disposing) this._lock = null; } } - + this._isDisposed = true; } @@ -158,7 +158,7 @@ private void EnsureNotDisposed() throw new ObjectDisposedException("ReaderWriterLockStrategy"); } } - - // This code added by Visual Basic to correctly implement the disposable pattern. + + // 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 a1c9d1fbcb9..f1e78fce9f3 100644 --- a/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs +++ b/DNN Platform/Library/Collections/ReaderWriterSlimLock.cs @@ -14,19 +14,19 @@ internal class ReaderWriterSlimLock : ISharedCollectionLock public ReaderWriterSlimLock(ReaderWriterLockSlim @lock) { this._lock = @lock; - } + } ~ReaderWriterSlimLock() { this.Dispose(false); } - + public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); - } + } protected virtual void Dispose(bool disposing) { @@ -55,7 +55,7 @@ protected virtual void Dispose(bool disposing) this._disposed = true; } } - + private void EnsureNotDisposed() { if (this._disposed) diff --git a/DNN Platform/Library/Collections/SharedDictionary.cs b/DNN Platform/Library/Collections/SharedDictionary.cs index 8981a89431e..79ab114de3f 100644 --- a/DNN Platform/Library/Collections/SharedDictionary.cs +++ b/DNN Platform/Library/Collections/SharedDictionary.cs @@ -15,7 +15,7 @@ public class SharedDictionary : IDictionary, IDispos private bool _isDisposed; private ILockStrategy _lockController; - public SharedDictionary() + public SharedDictionary() : this(LockingStrategy.ReaderWriter) { } @@ -26,7 +26,7 @@ public SharedDictionary(ILockStrategy lockStrategy) this._lockController = lockStrategy; } - public SharedDictionary(LockingStrategy strategy) + public SharedDictionary(LockingStrategy strategy) : this(LockingStrategyFactory.Create(strategy)) { } @@ -66,17 +66,39 @@ public ICollection Keys } } + public ICollection Values + { + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict.Values; + } + } + internal IDictionary BackingDictionary { get { return this._dict; } - } - - IEnumerator> IEnumerable>.GetEnumerator() + } + + public TValue this[TKey key] { - return this.IEnumerable_GetEnumerator(); + get + { + this.EnsureNotDisposed(); + this.EnsureReadAccess(); + return this._dict[key]; + } + + set + { + this.EnsureNotDisposed(); + this.EnsureWriteAccess(); + this._dict[key] = value; + } } public IEnumerator GetEnumerator() @@ -119,33 +141,6 @@ public bool Remove(KeyValuePair item) return this._dict.Remove(item); } - public ICollection Values - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._dict.Values; - } - } - - public TValue this[TKey key] - { - get - { - this.EnsureNotDisposed(); - this.EnsureReadAccess(); - return this._dict[key]; - } - - set - { - this.EnsureNotDisposed(); - this.EnsureWriteAccess(); - this._dict[key] = value; - } - } - public bool ContainsKey(TKey key) { this.EnsureNotDisposed(); @@ -173,14 +168,14 @@ public bool TryGetValue(TKey key, out TValue value) this.EnsureReadAccess(); return this._dict.TryGetValue(key, out value); } - + public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); - } - + } + public ISharedCollectionLock GetReadLock() { return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); @@ -238,7 +233,12 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } } - + + IEnumerator> IEnumerable>.GetEnumerator() + { + return this.IEnumerable_GetEnumerator(); + } + private void EnsureReadAccess() { if (!this._lockController.ThreadCanRead) diff --git a/DNN Platform/Library/Collections/SharedList.cs b/DNN Platform/Library/Collections/SharedList.cs index 9bed4fa0cfd..c59a5b566a9 100644 --- a/DNN Platform/Library/Collections/SharedList.cs +++ b/DNN Platform/Library/Collections/SharedList.cs @@ -11,10 +11,10 @@ public class SharedList : IList, IDisposable { private readonly List _list = new List(); private ILockStrategy _lockStrategy; - + private bool _isDisposed; - public SharedList() + public SharedList() : this(LockingStrategy.ReaderWriter) { } @@ -24,7 +24,7 @@ public SharedList(ILockStrategy lockStrategy) this._lockStrategy = lockStrategy; } - public SharedList(LockingStrategy strategy) + public SharedList(LockingStrategy strategy) : this(LockingStrategyFactory.Create(strategy)) { } @@ -32,7 +32,7 @@ public SharedList(LockingStrategy strategy) ~SharedList() { this.Dispose(false); - } + } public int Count { @@ -60,7 +60,7 @@ internal IList BackingList { return this._list; } - } + } public T this[int index] { @@ -70,7 +70,7 @@ public T this[int index] this.EnsureReadAccess(); return this._list[index]; } - + set { this.EnsureNotDisposed(); @@ -78,7 +78,7 @@ public T this[int index] this._list[index] = value; } } - + public void Add(T item) { this.EnsureNotDisposed(); @@ -142,11 +142,6 @@ public void RemoveAt(int index) this._list.RemoveAt(index); } - IEnumerator IEnumerable.GetEnumerator() - { - return this.GetEnumerator1(); - } - public void Dispose() { this.Dispose(true); @@ -161,7 +156,7 @@ public void EnsureNotDisposed() throw new ObjectDisposedException("SharedList"); } } - + public ISharedCollectionLock GetReadLock() { return this.GetReadLock(TimeSpan.FromMilliseconds(-1)); @@ -173,23 +168,6 @@ public ISharedCollectionLock GetReadLock(TimeSpan timeOut) return this._lockStrategy.GetReadLock(timeOut); } - // IDisposable - protected virtual void Dispose(bool disposing) - { - if (!this._isDisposed) - { - if (disposing) - { - // dispose managed state (managed objects). - } - - this._lockStrategy.Dispose(); - this._lockStrategy = null; - } - - this._isDisposed = true; - } - public ISharedCollectionLock GetReadLock(int millisecondTimeout) { return this.GetReadLock(TimeSpan.FromMilliseconds(millisecondTimeout)); @@ -216,6 +194,28 @@ public IEnumerator GetEnumerator1() return this.GetEnumerator(); } + // IDisposable + protected virtual void Dispose(bool disposing) + { + if (!this._isDisposed) + { + if (disposing) + { + // dispose managed state (managed objects). + } + + this._lockStrategy.Dispose(); + this._lockStrategy = null; + } + + this._isDisposed = true; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return this.GetEnumerator1(); + } + private void EnsureReadAccess() { if (!this._lockStrategy.ThreadCanRead) diff --git a/DNN Platform/Library/Collections/WriteLockRequiredException.cs b/DNN Platform/Library/Collections/WriteLockRequiredException.cs index a5cd2de5a95..1edc63a3173 100644 --- a/DNN Platform/Library/Collections/WriteLockRequiredException.cs +++ b/DNN Platform/Library/Collections/WriteLockRequiredException.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Collections.Internal using System; public class WriteLockRequiredException : Exception - { - } + {} } diff --git a/DNN Platform/Library/Common/Controls/ActionLessForm.cs b/DNN Platform/Library/Common/Controls/ActionLessForm.cs index cd54401c381..88d5e549097 100644 --- a/DNN Platform/Library/Common/Controls/ActionLessForm.cs +++ b/DNN Platform/Library/Common/Controls/ActionLessForm.cs @@ -19,7 +19,7 @@ protected override void RenderAttributes(HtmlTextWriter writer) var htmlWriter = new HtmlTextWriter(stringWriter); base.RenderAttributes(htmlWriter); string html = stringWriter.ToString(); - + // Locate and replace action attribute int StartPoint = html.IndexOf("action=\""); if (StartPoint >= 0) @@ -28,10 +28,10 @@ protected override void RenderAttributes(HtmlTextWriter writer) html = html.Remove(StartPoint, EndPoint - StartPoint); html = html.Insert(StartPoint, "action=\"" + HttpUtility.HtmlEncode(HttpContext.Current.Request.RawUrl) + "\""); } - + if (this.ID != null) - { - // Locate and replace id attribute + { + // Locate and replace id attribute StartPoint = html.IndexOf("id=\""); if (StartPoint >= 0) { @@ -40,7 +40,7 @@ protected override void RenderAttributes(HtmlTextWriter writer) html = html.Insert(StartPoint, "id=\"" + this.ClientID + "\""); } } - + writer.Write(html); } } diff --git a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs index 546d084f0d6..7dbf8569c48 100644 --- a/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs +++ b/DNN Platform/Library/Common/Extensions/HttpContextDependencyInjectionExtensions.cs @@ -37,11 +37,11 @@ public static IServiceScope GetScope(this HttpContext httpContext) internal static IServiceScope GetScope(System.Collections.IDictionary contextItems) { - if (!contextItems.Contains(typeof(IServiceScope))) - { - return null; - } - + if (!contextItems.Contains(typeof(IServiceScope))) + { + return null; + } + return contextItems[typeof(IServiceScope)] is IServiceScope scope ? scope : null; } } diff --git a/DNN Platform/Library/Common/Globals.cs b/DNN Platform/Library/Common/Globals.cs index fb1f495d536..755afd7b815 100644 --- a/DNN Platform/Library/Common/Globals.cs +++ b/DNN Platform/Library/Common/Globals.cs @@ -84,129 +84,6 @@ public sealed class Globals /// -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); - public static readonly Regex BaseTagRegex = new Regex("]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public static readonly Regex FileEscapingRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); - public static readonly Regex FileExtensionRegex = new Regex(@"\..+;", RegexOptions.Compiled); - public static readonly Regex FileValidNameRegex = new Regex(@"^(?!(?:PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d)(?:\..+)?$)[^\x00-\x1F\xA5\\?*:\"";|\/<>]+(??[\\]^`{|}"; - - /// - /// Enumeration of site performance setting, say by another way that means how to set the cache. - /// - /// - /// Using cache will speed up the application to a great degree, we recommend to use cache for whole modules, - /// but sometimes cache also make confuse for user, if we didn't take care of how to make cache expired when needed, - /// such as if a data has already been deleted but the cache arn't clear, it will cause un expected errors. - /// so you should choose a correct performance setting type when you trying to cache some stuff, and always remember - /// update cache immediately after the data changed. - /// default cache policy in core api will use cache timeout muitple Host Performance setting's value as cache time(unit: minutes): - /// - /// HostSettingsCacheTimeOut: 20 - /// PortalAliasCacheTimeOut: 200 - /// PortalSettingsCacheTimeOut: 20 - /// More cache timeout definitions see - /// - /// - public enum PerformanceSettings - { - /// - /// No Caching - /// - NoCaching = 0, - - /// - /// Caching for a short time - /// - LightCaching = 1, - - /// - /// Caching for moderate - /// - ModerateCaching = 3, - - /// - /// Caching for a long time - /// - HeavyCaching = 6, - } - - /// - /// Enumeration Of Registration Type for portal. - /// - /// - /// NoRegistration: Disabled registration in portal. - /// PrivateRegistration: Once user's account information has been submitted, - /// the portal Administrator will be notified and user's application will be subjected to a screening procedure. - /// If user's application is authorized, the user will receive notification of access to the portal environment. - /// PublicRegistration: Once user's account information has been submitted, - /// user will be immediately granted access to the portal environment. - /// VerifiedRegistration: Once user's account information has been submitted, - /// user will receive an email containing unique Verification Code. - /// The Verification Code will be required the first time when user attempt to sign in to the portal environment. - /// - public enum PortalRegistrationType - { - /// - /// Disabled Registration - /// - NoRegistration = 0, - - /// - /// Account need be approved by portal's administrator. - /// - PrivateRegistration = 1, - - /// - /// Account will be available after post registration data successful. - /// - PublicRegistration = 2, - - /// - /// Account will be available by verify code. - /// - VerifiedRegistration = 3, - } - - /// - /// Enumeration Of Application upgrade status. - /// - public enum UpgradeStatus - { - /// - /// The application need update to a higher version. - /// - Upgrade, - - /// - /// 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, - } - /// /// Global role id by default. /// @@ -321,9 +198,22 @@ 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 ) + 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); + 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); + public static readonly Regex BaseTagRegex = new Regex("]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static readonly Regex FileEscapingRegex = new Regex("[\\\\/]\\.\\.[\\\\/]", RegexOptions.Compiled); + public static readonly Regex FileExtensionRegex = new Regex(@"\..+;", RegexOptions.Compiled); + public static readonly Regex FileValidNameRegex = new Regex(@"^(?!(?:PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d)(?:\..+)?$)[^\x00-\x1F\xA5\\?*:\"";|\/<>]+(??[\\]^`{|}"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Globals)); private static string _applicationPath; private static string _applicationMapPath; private static string _desktopModulePath; @@ -338,6 +228,118 @@ public enum UpgradeStatus private static readonly Stopwatch AppStopwatch = Stopwatch.StartNew(); + // global constants for the life of the application ( set in Application_Start ) + + + /// + /// Enumeration of site performance setting, say by another way that means how to set the cache. + /// + /// + /// Using cache will speed up the application to a great degree, we recommend to use cache for whole modules, + /// but sometimes cache also make confuse for user, if we didn't take care of how to make cache expired when needed, + /// such as if a data has already been deleted but the cache arn't clear, it will cause un expected errors. + /// so you should choose a correct performance setting type when you trying to cache some stuff, and always remember + /// update cache immediately after the data changed. + /// default cache policy in core api will use cache timeout muitple Host Performance setting's value as cache time(unit: minutes): + /// + /// HostSettingsCacheTimeOut: 20 + /// PortalAliasCacheTimeOut: 200 + /// PortalSettingsCacheTimeOut: 20 + /// More cache timeout definitions see + /// + /// + public enum PerformanceSettings + { + /// + /// No Caching + /// + NoCaching = 0, + + /// + /// Caching for a short time + /// + LightCaching = 1, + + /// + /// Caching for moderate + /// + ModerateCaching = 3, + + /// + /// Caching for a long time + /// + HeavyCaching = 6, + } + + /// + /// Enumeration Of Registration Type for portal. + /// + /// + /// NoRegistration: Disabled registration in portal. + /// PrivateRegistration: Once user's account information has been submitted, + /// the portal Administrator will be notified and user's application will be subjected to a screening procedure. + /// If user's application is authorized, the user will receive notification of access to the portal environment. + /// PublicRegistration: Once user's account information has been submitted, + /// user will be immediately granted access to the portal environment. + /// VerifiedRegistration: Once user's account information has been submitted, + /// user will receive an email containing unique Verification Code. + /// The Verification Code will be required the first time when user attempt to sign in to the portal environment. + /// + public enum PortalRegistrationType + { + /// + /// Disabled Registration + /// + NoRegistration = 0, + + /// + /// Account need be approved by portal's administrator. + /// + PrivateRegistration = 1, + + /// + /// Account will be available after post registration data successful. + /// + PublicRegistration = 2, + + /// + /// Account will be available by verify code. + /// + VerifiedRegistration = 3, + } + + /// + /// Enumeration Of Application upgrade status. + /// + public enum UpgradeStatus + { + /// + /// The application need update to a higher version. + /// + Upgrade, + + /// + /// 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, + } + /// /// Gets the application path. /// @@ -420,17 +422,6 @@ 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. /// @@ -478,66 +469,26 @@ public static string InstallMapPath _installMapPath = ApplicationMapPath + "\\Install\\"; } - return _installMapPath; - } - } - - /// - /// Gets the install path. - /// - /// ApplicationPath + "/Install/". - public static string InstallPath - { - get - { - if (_installPath == null) - { - _installPath = ApplicationPath + "/Install/"; - } - - return _installPath; - } - } - - /// - /// Gets or sets the name of the IIS app. - /// - /// - /// request.ServerVariables["APPL_MD_PATH"]. - /// - public static string IISAppName { get; set; } - - /// - /// Gets or sets the name of the server. - /// - /// - /// server name in config file or the server's marchine name. - /// - public static string ServerName { get; set; } - - /// - /// Gets or sets the operating system version. - /// - /// - /// The operating system version. - /// - public static Version OperatingSystemVersion { get; set; } + return _installMapPath; + } + } /// - /// Gets or sets the NET framework version. + /// Gets the install path. /// - /// - /// The NET framework version. - /// - public static Version NETFrameworkVersion { get; set; } + /// ApplicationPath + "/Install/". + public static string InstallPath + { + get + { + if (_installPath == null) + { + _installPath = ApplicationPath + "/Install/"; + } - /// - /// Gets or sets the database engine version. - /// - /// - /// The database engine version. - /// - public static Version DatabaseEngineVersion { get; set; } + return _installPath; + } + } /// /// Gets the status of application. @@ -654,6 +605,46 @@ public static TimeSpan ElapsedSinceAppStart } } + /// + /// Gets or sets the name of the IIS app. + /// + /// + /// request.ServerVariables["APPL_MD_PATH"]. + /// + public static string IISAppName { get; set; } + + /// + /// Gets or sets the name of the server. + /// + /// + /// server name in config file or the server's marchine name. + /// + public static string ServerName { get; set; } + + /// + /// Gets or sets the operating system version. + /// + /// + /// The operating system version. + /// + public static Version OperatingSystemVersion { get; set; } + + /// + /// Gets or sets the NET framework version. + /// + /// + /// The NET framework version. + /// + public static Version NETFrameworkVersion { get; set; } + + /// + /// Gets or sets the database engine version. + /// + /// + /// The database engine version. + /// + public static Version DatabaseEngineVersion { get; set; } + /// /// Gets or sets the Dependency Service. /// @@ -889,150 +880,6 @@ public static DataSet BuildCrossTabDataSet(string DataSetName, IDataReader resul 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; - } - - if (string.IsNullOrEmpty(cultureCode)) - { - cultureCode = Thread.CurrentThread.CurrentCulture.Name; - } - } - - return cultureCode; - } - - /// - /// 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; - } - } - - return false; - } - - /// - /// 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)) - { - return Directory.GetDirectories(dir).Length > 1; - } - - return false; - } - - /// - /// 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"); - } - /// /// Converts the datareader to dataset. /// @@ -2394,43 +2241,6 @@ public static string CleanFileName(string FileName, string BadChars) return CleanFileName(FileName, BadChars, string.Empty); } - private static void DeleteFile(string filePath) - { - try - { - FileSystemUtils.DeleteFile(filePath); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - private static void DeleteFolder(string strRoot) - { - try - { - Directory.Delete(strRoot); - } - catch (IOException) - { - // Force Deletion. Directory should be empty - try - { - Thread.Sleep(50); - Directory.Delete(strRoot, true); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - /// /// Cleans the name of the file. /// @@ -3782,38 +3592,6 @@ 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. @@ -4055,9 +3833,233 @@ public static string PreventSQLInjection(string strSQL) return PortalSecurity.Instance.InputFilter(strSQL, PortalSecurity.FilterFlag.NoSQL); } + /// + /// 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; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = Thread.CurrentThread.CurrentCulture.Name; + } + } + + return cultureCode; + } + internal static void ResetAppStartElapseTime() { AppStopwatch.Restart(); } + + 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; + } + + /// + /// 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; + } + } + + return false; + } + + /// + /// 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)) + { + return Directory.GetDirectories(dir).Length > 1; + } + + return false; + } + + /// + /// 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"); + } + + private static void DeleteFile(string filePath) + { + try + { + FileSystemUtils.DeleteFile(filePath); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + private static void DeleteFolder(string strRoot) + { + try + { + Directory.Delete(strRoot); + } + catch (IOException) + { + // Force Deletion. Directory should be empty + try + { + Thread.Sleep(50); + Directory.Delete(strRoot, true); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + /// + /// 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; + } } } diff --git a/DNN Platform/Library/Common/HttpContextSource.cs b/DNN Platform/Library/Common/HttpContextSource.cs index 368b57031ca..86ac9e8262d 100644 --- a/DNN Platform/Library/Common/HttpContextSource.cs +++ b/DNN Platform/Library/Common/HttpContextSource.cs @@ -30,7 +30,7 @@ public static HttpContextBase Current { return new HttpContextWrapper(HttpContext.Current); } - + return null; } } diff --git a/DNN Platform/Library/Common/Initialize.cs b/DNN Platform/Library/Common/Initialize.cs index 98a49bac67c..1a887faea62 100644 --- a/DNN Platform/Library/Common/Initialize.cs +++ b/DNN Platform/Library/Common/Initialize.cs @@ -35,8 +35,8 @@ namespace DotNetNuke.Common public class Initialize { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Initialize)); - private static bool InitializedAlready; private static readonly object InitializeLock = new object(); + private static bool InitializedAlready; /// ----------------------------------------------------------------------------- /// @@ -47,13 +47,13 @@ public class Initialize 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 @@ -61,11 +61,11 @@ public static void Init(HttpApplication app) { return; } - + // Initialize ... redirect = InitializeApp(app, ref InitializedAlready); } - + if (!string.IsNullOrEmpty(redirect)) { app.Response.Redirect(redirect, true); @@ -87,218 +87,6 @@ public static void LogStart() LogController.Instance.AddLog(log); } - private static string CheckVersion(HttpApplication app) - { - HttpServerUtility Server = app.Server; - - bool autoUpgrade = Config.GetSetting("AutoUpgrade") == null || bool.Parse(Config.GetSetting("AutoUpgrade")); - bool useWizard = Config.GetSetting("UseInstallWizard") == null || bool.Parse(Config.GetSetting("UseInstallWizard")); - - // Determine the Upgrade status and redirect as neccessary to InstallWizard.aspx - string retValue = Null.NullString; - switch (Globals.Status) - { - case Globals.UpgradeStatus.Install: - if (autoUpgrade || useWizard) - { - retValue = useWizard ? "~/Install/InstallWizard.aspx" : "~/Install/Install.aspx?mode=install"; - } - else - { - CreateUnderConstructionPage(Server); - retValue = "~/Install/UnderConstruction.htm"; - Logger.Info("UnderConstruction page was shown because application needs to be installed, and both the AutoUpgrade and UseWizard AppSettings in web.config are false. Use /install/install.aspx?mode=install to install application. "); - } - - break; - case Globals.UpgradeStatus.Upgrade: - if (autoUpgrade || useWizard) - { - retValue = useWizard ? "~/Install/UpgradeWizard.aspx" : "~/Install/Install.aspx?mode=upgrade"; - } - else - { - CreateUnderConstructionPage(Server); - retValue = "~/Install/UnderConstruction.htm"; - Logger.Info("UnderConstruction page was shown because application needs to be upgraded, and both the AutoUpgrade and UseInstallWizard AppSettings in web.config are false. Use /install/install.aspx?mode=upgrade to upgrade application. "); - } - - break; - case Globals.UpgradeStatus.Error: - // here we need to check if the application is already installed - // or is in pre-install state. - // see http://support.dotnetnuke.com/project/DNN/2/item/26053 for scenarios - bool isInstalled = Globals.IsInstalled(); - - if (!isInstalled && (useWizard || autoUpgrade)) - { - // app has never been installed, and either Wizard or Autoupgrade is configured - CreateUnderConstructionPage(Server); - retValue = "~/Install/UnderConstruction.htm"; - Logger.Error("UnderConstruction page was shown because we cannot ascertain the application was ever installed, and there is no working database connection. Check database connectivity before continuing. "); - } - else - { - // 500 Error - Redirect to ErrorPage - if (HttpContext.Current != null) - { - if (!isInstalled) - { - Logger.Error("The connection to the database has failed, the application is not installed yet, and both AutoUpgrade and UseInstallWizard are not set in web.config, a 500 error page will be shown to visitors"); - } - else - { - Logger.Error("The connection to the database has failed, however, the application is already completely installed, a 500 error page will be shown to visitors"); - } - - string url = "~/ErrorPage.aspx?status=500&error=Site Unavailable&error2=Connection To The Database Failed"; - HttpContext.Current.Response.Clear(); - HttpContext.Current.Server.Transfer(url); - } - } - - break; - } - - return retValue; - } - - private static void CreateUnderConstructionPage(HttpServerUtility server) - { - // create an UnderConstruction page if it does not exist already - if (!File.Exists(server.MapPath("~/Install/UnderConstruction.htm"))) - { - if (File.Exists(server.MapPath("~/Install/UnderConstruction.template.htm"))) - { - File.Copy(server.MapPath("~/Install/UnderConstruction.template.htm"), server.MapPath("~/Install/UnderConstruction.htm")); - } - } - } - - private static Version GetDatabaseEngineVersion() - { - return DataProvider.Instance().GetDatabaseEngineVersion(); - } - - private static Version GetNETFrameworkVersion() - { - // Obtain the .NET Framework version, 9.4.0 and later requires .NET 4.7.2 or later - var version = Environment.Version.ToString(2); - - // If unknown version return as is. - if (version != "4.0") - { - return new Version(version); - } - - // Otherwise utilize release DWORD from registry to determine version - // Reference List: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies - var release = GetDotNet4ReleaseNumberFromRegistry(); - if (release >= 528040) - { - version = "4.8"; - } - else - { - version = "4.7.2"; - } - - return new Version(version); - } - - private static int GetDotNet4ReleaseNumberFromRegistry() - { - try - { - using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) - .OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) - { - if (ndpKey?.GetValue("Release") != null) - { - return (int)ndpKey.GetValue("Release"); - } - } - } - catch (Exception) - { - // ignore - } - - return -1; - } - - private static string InitializeApp(HttpApplication app, ref bool initialized) - { - var request = app.Request; - var redirect = Null.NullString; - - Logger.Trace("Request " + request.Url.LocalPath); - - // Don't process some of the AppStart methods if we are installing - if (!IsUpgradeOrInstallRequest(app.Request)) - { - // Check whether the current App Version is the same as the DB Version - redirect = CheckVersion(app); - if (string.IsNullOrEmpty(redirect) && !InstallBlocker.Instance.IsInstallInProgress()) - { - Logger.Info("Application Initializing"); - - // Set globals - Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; - Globals.OperatingSystemVersion = Environment.OSVersion.Version; - Globals.NETFrameworkVersion = GetNETFrameworkVersion(); - Globals.DatabaseEngineVersion = GetDatabaseEngineVersion(); - - // Try and Upgrade to Current Framewok - Upgrade.TryUpgradeNETFramework(); - Upgrade.CheckFipsCompilanceAssemblies(); - - // Log Server information - ServerController.UpdateServerActivity(new ServerInfo()); - - // Start Scheduler - StartScheduler(); - - // Log Application Start - LogStart(); - - // Process any messages in the EventQueue for the Application_Start event - EventQueueController.ProcessMessages("Application_Start"); - - ServicesRoutingManager.RegisterServiceRoutes(); - - ModuleInjectionManager.RegisterInjectionFilters(); - - ConnectionsManager.Instance.RegisterConnections(); - - // Set Flag so we can determine the first Page Request after Application Start - app.Context.Items.Add("FirstRequest", true); - - Logger.Info("Application Initialized"); - - initialized = true; - } - } - else - { - // NET Framework version is neeed by Upgrade - Globals.NETFrameworkVersion = GetNETFrameworkVersion(); - Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; - Globals.OperatingSystemVersion = Environment.OSVersion.Version; - } - - return redirect; - } - - private static bool IsUpgradeOrInstallRequest(HttpRequest request) - { - var url = request.Url.LocalPath.ToLowerInvariant(); - - return url.EndsWith("/install.aspx") - || url.Contains("/upgradewizard.aspx") - || url.Contains("/installwizard.aspx"); - } - /// ----------------------------------------------------------------------------- /// /// LogEnd logs the Application Start Event. @@ -358,7 +146,7 @@ public static void LogEnd() shutdownDetail = "Shutdown reason: " + shutdownReason; break; } - + var log = new LogInfo { BypassBuffering = true, @@ -368,7 +156,7 @@ public static void LogEnd() LogController.Instance.AddLog(log); // enhanced shutdown logging - var runtime = typeof(HttpRuntime).InvokeMember( + var runtime = typeof(HttpRuntime).InvokeMember( "_theRuntime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField, null, null, null) as HttpRuntime; @@ -379,12 +167,12 @@ public static void LogEnd() } else { - var shutDownMessage = runtime.GetType().InvokeMember( + var shutDownMessage = runtime.GetType().InvokeMember( "_shutDownMessage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; - var shutDownStack = runtime.GetType().InvokeMember( + var shutDownStack = runtime.GetType().InvokeMember( "_shutDownStack", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, runtime, null) as string; @@ -398,18 +186,18 @@ public static void LogEnd() { Exceptions.LogException(exc); } - + if (Globals.Status != Globals.UpgradeStatus.Install) { // purge log buffer LoggingProvider.Instance().PurgeLogBuffer(); } } - + /// ----------------------------------------------------------------------------- /// /// Tests whether this request should be processed in an HttpModule. - /// + /// /// /// ----------------------------------------------------------------------------- public static bool ProcessHttpModule(HttpRequest request, bool allowUnknownExtensions, bool checkOmitFromRewriteProcessing) @@ -474,7 +262,7 @@ public static void StartScheduler(bool resetAppStartElapseTime = false) { Globals.ResetAppStartElapseTime(); } - + var scheduler = SchedulingProvider.Instance(); scheduler.RunEventSchedule(EventName.APPLICATION_START); @@ -503,5 +291,217 @@ public static void StopScheduler() // stop scheduled jobs SchedulingProvider.Instance().Halt("Stopped by Application_End"); } + + private static string CheckVersion(HttpApplication app) + { + HttpServerUtility Server = app.Server; + + bool autoUpgrade = Config.GetSetting("AutoUpgrade") == null || bool.Parse(Config.GetSetting("AutoUpgrade")); + bool useWizard = Config.GetSetting("UseInstallWizard") == null || bool.Parse(Config.GetSetting("UseInstallWizard")); + + // Determine the Upgrade status and redirect as neccessary to InstallWizard.aspx + string retValue = Null.NullString; + switch (Globals.Status) + { + case Globals.UpgradeStatus.Install: + if (autoUpgrade || useWizard) + { + retValue = useWizard ? "~/Install/InstallWizard.aspx" : "~/Install/Install.aspx?mode=install"; + } + else + { + CreateUnderConstructionPage(Server); + retValue = "~/Install/UnderConstruction.htm"; + Logger.Info("UnderConstruction page was shown because application needs to be installed, and both the AutoUpgrade and UseWizard AppSettings in web.config are false. Use /install/install.aspx?mode=install to install application. "); + } + + break; + case Globals.UpgradeStatus.Upgrade: + if (autoUpgrade || useWizard) + { + retValue = useWizard ? "~/Install/UpgradeWizard.aspx" : "~/Install/Install.aspx?mode=upgrade"; + } + else + { + CreateUnderConstructionPage(Server); + retValue = "~/Install/UnderConstruction.htm"; + Logger.Info("UnderConstruction page was shown because application needs to be upgraded, and both the AutoUpgrade and UseInstallWizard AppSettings in web.config are false. Use /install/install.aspx?mode=upgrade to upgrade application. "); + } + + break; + case Globals.UpgradeStatus.Error: + // here we need to check if the application is already installed + // or is in pre-install state. + // see http://support.dotnetnuke.com/project/DNN/2/item/26053 for scenarios + bool isInstalled = Globals.IsInstalled(); + + if (!isInstalled && (useWizard || autoUpgrade)) + { + // app has never been installed, and either Wizard or Autoupgrade is configured + CreateUnderConstructionPage(Server); + retValue = "~/Install/UnderConstruction.htm"; + Logger.Error("UnderConstruction page was shown because we cannot ascertain the application was ever installed, and there is no working database connection. Check database connectivity before continuing. "); + } + else + { + // 500 Error - Redirect to ErrorPage + if (HttpContext.Current != null) + { + if (!isInstalled) + { + Logger.Error("The connection to the database has failed, the application is not installed yet, and both AutoUpgrade and UseInstallWizard are not set in web.config, a 500 error page will be shown to visitors"); + } + else + { + Logger.Error("The connection to the database has failed, however, the application is already completely installed, a 500 error page will be shown to visitors"); + } + + string url = "~/ErrorPage.aspx?status=500&error=Site Unavailable&error2=Connection To The Database Failed"; + HttpContext.Current.Response.Clear(); + HttpContext.Current.Server.Transfer(url); + } + } + + break; + } + + return retValue; + } + + private static void CreateUnderConstructionPage(HttpServerUtility server) + { + // create an UnderConstruction page if it does not exist already + if (!File.Exists(server.MapPath("~/Install/UnderConstruction.htm"))) + { + if (File.Exists(server.MapPath("~/Install/UnderConstruction.template.htm"))) + { + File.Copy(server.MapPath("~/Install/UnderConstruction.template.htm"), server.MapPath("~/Install/UnderConstruction.htm")); + } + } + } + + private static Version GetDatabaseEngineVersion() + { + return DataProvider.Instance().GetDatabaseEngineVersion(); + } + + private static Version GetNETFrameworkVersion() + { + // Obtain the .NET Framework version, 9.4.0 and later requires .NET 4.7.2 or later + var version = Environment.Version.ToString(2); + + // If unknown version return as is. + if (version != "4.0") + { + return new Version(version); + } + + // Otherwise utilize release DWORD from registry to determine version + // Reference List: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies + var release = GetDotNet4ReleaseNumberFromRegistry(); + if (release >= 528040) + { + version = "4.8"; + } + else + { + version = "4.7.2"; + } + + return new Version(version); + } + + private static int GetDotNet4ReleaseNumberFromRegistry() + { + try + { + using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32) + .OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\")) + { + if (ndpKey?.GetValue("Release") != null) + { + return (int)ndpKey.GetValue("Release"); + } + } + } + catch (Exception) + { + // ignore + } + + return -1; + } + + private static string InitializeApp(HttpApplication app, ref bool initialized) + { + var request = app.Request; + var redirect = Null.NullString; + + Logger.Trace("Request " + request.Url.LocalPath); + + // Don't process some of the AppStart methods if we are installing + if (!IsUpgradeOrInstallRequest(app.Request)) + { + // Check whether the current App Version is the same as the DB Version + redirect = CheckVersion(app); + if (string.IsNullOrEmpty(redirect) && !InstallBlocker.Instance.IsInstallInProgress()) + { + Logger.Info("Application Initializing"); + + // Set globals + Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; + Globals.OperatingSystemVersion = Environment.OSVersion.Version; + Globals.NETFrameworkVersion = GetNETFrameworkVersion(); + Globals.DatabaseEngineVersion = GetDatabaseEngineVersion(); + + // Try and Upgrade to Current Framewok + Upgrade.TryUpgradeNETFramework(); + Upgrade.CheckFipsCompilanceAssemblies(); + + // Log Server information + ServerController.UpdateServerActivity(new ServerInfo()); + + // Start Scheduler + StartScheduler(); + + // Log Application Start + LogStart(); + + // Process any messages in the EventQueue for the Application_Start event + EventQueueController.ProcessMessages("Application_Start"); + + ServicesRoutingManager.RegisterServiceRoutes(); + + ModuleInjectionManager.RegisterInjectionFilters(); + + ConnectionsManager.Instance.RegisterConnections(); + + // Set Flag so we can determine the first Page Request after Application Start + app.Context.Items.Add("FirstRequest", true); + + Logger.Info("Application Initialized"); + + initialized = true; + } + } + else + { + // NET Framework version is neeed by Upgrade + Globals.NETFrameworkVersion = GetNETFrameworkVersion(); + Globals.IISAppName = request.ServerVariables["APPL_MD_PATH"]; + Globals.OperatingSystemVersion = Environment.OSVersion.Version; + } + + return redirect; + } + + private static bool IsUpgradeOrInstallRequest(HttpRequest request) + { + var url = request.Url.LocalPath.ToLowerInvariant(); + + return url.EndsWith("/install.aspx") + || url.Contains("/upgradewizard.aspx") + || url.Contains("/installwizard.aspx"); + } } } diff --git a/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs b/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs index db0cd3bf2e6..bdb84e46b2a 100644 --- a/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs +++ b/DNN Platform/Library/Common/Internal/EventHandlersContainer.cs @@ -28,7 +28,7 @@ public EventHandlersContainer() { return; } - + ExtensionPointManager.ComposeParts(this); } catch (Exception ex) diff --git a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs index e2478453b3a..171d08f3f31 100644 --- a/DNN Platform/Library/Common/Internal/GlobalsImpl.cs +++ b/DNN Platform/Library/Common/Internal/GlobalsImpl.cs @@ -31,7 +31,7 @@ public string HostMapPath { get { return Globals.HostMapPath; } } - + protected INavigationManager NavigationManager { get; } public string GetSubFolderPath(string strFileNamePath, int portalId) @@ -89,13 +89,13 @@ public string GetDomainName(Uri requestedUri, bool parsePortNumber) { uri = uri.ToLowerInvariant().Replace(hostHeader.ToLowerInvariant(), string.Empty); } - + int queryIndex = uri.IndexOf("?", StringComparison.Ordinal); if (queryIndex > -1) { uri = uri.Substring(0, queryIndex); } - + string[] url = uri.Split('/'); for (queryIndex = 2; queryIndex <= url.GetUpperBound(0); queryIndex++) { @@ -127,18 +127,18 @@ public string GetDomainName(Uri requestedUri, bool parsePortNumber) break; } } - + // non of the exclusionary names found domainName.Append((!string.IsNullOrEmpty(domainName.ToString()) ? "/" : string.Empty) + url[queryIndex]); break; } - + if (needExit) { break; } } - + if (parsePortNumber) { if (domainName.ToString().IndexOf(":", StringComparison.Ordinal) != -1) @@ -149,7 +149,7 @@ public string GetDomainName(Uri requestedUri, bool parsePortNumber) } } } - + return domainName.ToString(); } diff --git a/DNN Platform/Library/Common/Lists/ListController.cs b/DNN Platform/Library/Common/Lists/ListController.cs index c048a43ea9d..24af3f3c4d5 100644 --- a/DNN Platform/Library/Common/Lists/ListController.cs +++ b/DNN Platform/Library/Common/Lists/ListController.cs @@ -21,8 +21,8 @@ namespace DotNetNuke.Common.Lists public class ListController { - public readonly string[] NonLocalizedLists = { "ContentTypes", "Processor", "DataType", "ProfanityFilter", "BannedPasswords" }; - + 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. @@ -33,7 +33,7 @@ public int AddListEntry(ListEntryInfo listEntry) { bool enableSortOrder = listEntry.SortOrder > 0; this.ClearListCache(listEntry.PortalID); - int entryId = DataProvider.Instance().AddListEntry( + int entryId = DataProvider.Instance().AddListEntry( listEntry.ListName, listEntry.Value, listEntry.TextNonLocalized, @@ -50,7 +50,7 @@ public int AddListEntry(ListEntryInfo listEntry) { 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)) @@ -62,7 +62,7 @@ public int AddListEntry(ListEntryInfo listEntry) 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; } @@ -71,102 +71,6 @@ public void DeleteList(string listName, string parentKey) { this.DeleteList(listName, parentKey, Null.NullInteger); } - - private void ClearListCache(int portalId) - { - DataCache.ClearListsCache(portalId); - } - - private void ClearEntriesCache(string listName, int portalId) - { - string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); - DataCache.RemoveCache(cacheKey); - } - - private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) - { - ListInfo list = null; - - // read datareader - bool canContinue = true; - if (CheckForOpenDataReader) - { - canContinue = false; - if (dr.Read()) - { - canContinue = true; - } - } - - if (canContinue) - { - list = new ListInfo(Convert.ToString(dr["ListName"])); - { - list.Level = Convert.ToInt32(dr["Level"]); - list.PortalID = Convert.ToInt32(dr["PortalID"]); - list.DefinitionID = Convert.ToInt32(dr["DefinitionID"]); - list.EntryCount = Convert.ToInt32(dr["EntryCount"]); - list.ParentID = Convert.ToInt32(dr["ParentID"]); - list.ParentKey = Convert.ToString(dr["ParentKey"]); - list.Parent = Convert.ToString(dr["Parent"]); - list.ParentList = Convert.ToString(dr["ParentList"]); - list.EnableSortOrder = Convert.ToInt32(dr["MaxSortOrder"]) > 0; - list.SystemList = Convert.ToInt32(dr["SystemList"]) > 0; - } - } - - return list; - } - - private Dictionary FillListInfoDictionary(IDataReader dr) - { - var dic = new Dictionary(); - try - { - while (dr.Read()) - { - // fill business object - ListInfo list = this.FillListInfo(dr, false); - if (!dic.ContainsKey(list.Key)) - { - dic.Add(list.Key, list); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - - return dic; - } - - private Dictionary GetListInfoDictionary(int portalId) - { - string cacheKey = string.Format(DataCache.ListsCacheKey, portalId); - return CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.ListsCacheTimeOut, - DataCache.ListsCachePriority), - c => this.FillListInfoDictionary(DataProvider.Instance().GetLists(portalId))); - } - - private IEnumerable GetListEntries(string listName, int portalId) - { - string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); - return CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.ListsCacheTimeOut, - DataCache.ListsCachePriority), - c => CBO.FillCollection(DataProvider.Instance().GetListEntriesByListName(listName, string.Empty, portalId))); - } public void DeleteList(string listName, string parentKey, int portalId) { @@ -189,7 +93,7 @@ public void DeleteList(ListInfo list, bool includeChildren) var lists = new SortedList(); lists.Add(list.Key, list); - + // add Children if (includeChildren) { @@ -201,7 +105,7 @@ public void DeleteList(ListInfo list, bool includeChildren) } } } - + // Delete items in reverse order so deeper descendants are removed before their parents for (int i = lists.Count - 1; i >= 0; i += -1) { @@ -280,14 +184,6 @@ 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; @@ -296,7 +192,7 @@ public ListInfo GetListInfo(string listName, string parentKey, int portalId) { key = parentKey + ":"; } - + key += listName; Dictionary dicLists = this.GetListInfoDictionary(portalId); if (!dicLists.TryGetValue(key, out list)) @@ -311,7 +207,7 @@ public ListInfo GetListInfo(string listName, string parentKey, int portalId) CBO.CloseDataReader(dr, true); } } - + return list; } @@ -342,7 +238,7 @@ public ListInfoCollection GetListInfoCollection(string listName, string parentKe lists.Add(list); } } - + return (ListInfoCollection)lists; } @@ -370,7 +266,7 @@ public void UpdateListEntry(ListEntryInfo listEntry) LocalizationProvider.Instance.SaveString(key, listEntry.TextNonLocalized, listEntry.ResourceFileRoot, Thread.CurrentThread.CurrentCulture.Name, PortalController.Instance.GetCurrentPortalSettings(), LocalizationProvider.CustomizedLocale.None, true, true); } - + EventLogController.Instance.AddLog(listEntry, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LISTENTRY_UPDATED); this.ClearListCache(listEntry.PortalID); this.ClearEntriesCache(listEntry.ListName, listEntry.PortalID); @@ -384,21 +280,21 @@ public void UpdateListSortOrder(int EntryID, bool MoveUp) this.ClearEntriesCache(entry.ListName, entry.PortalID); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string) instead. Scheduled removal in v10.0.0.")] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string) instead. Scheduled removal in v10.0.0.")] [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName) { return this.GetListEntryInfoCollection(listName, string.Empty, Null.NullInteger); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey) { return this.GetListEntryInfoCollection(listName, parentKey, Null.NullInteger); } - [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] + [Obsolete("Obsoleted in 6.0.1 use IEnumerable GetListEntryInfoXXX(string, string, int) instead. Scheduled removal in v10.0.0.")] [EditorBrowsable(EditorBrowsableState.Never)] public ListEntryInfoCollection GetListEntryInfoCollection(string listName, string parentKey, int portalId) { @@ -409,8 +305,112 @@ public ListEntryInfoCollection GetListEntryInfoCollection(string listName, strin { items.ToList().ForEach(x => collection.Add(x.Key, x)); } - + return collection; } + + private static Dictionary ListEntryInfoItemsToDictionary(IEnumerable items) + { + var dict = new Dictionary(); + items.ToList().ForEach(x => dict.Add(x.Key, x)); + + return dict; + } + + private void ClearListCache(int portalId) + { + DataCache.ClearListsCache(portalId); + } + + private void ClearEntriesCache(string listName, int portalId) + { + string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); + DataCache.RemoveCache(cacheKey); + } + + private ListInfo FillListInfo(IDataReader dr, bool CheckForOpenDataReader) + { + ListInfo list = null; + + // read datareader + bool canContinue = true; + if (CheckForOpenDataReader) + { + canContinue = false; + if (dr.Read()) + { + canContinue = true; + } + } + + if (canContinue) + { + list = new ListInfo(Convert.ToString(dr["ListName"])); + { + list.Level = Convert.ToInt32(dr["Level"]); + list.PortalID = Convert.ToInt32(dr["PortalID"]); + list.DefinitionID = Convert.ToInt32(dr["DefinitionID"]); + list.EntryCount = Convert.ToInt32(dr["EntryCount"]); + list.ParentID = Convert.ToInt32(dr["ParentID"]); + list.ParentKey = Convert.ToString(dr["ParentKey"]); + list.Parent = Convert.ToString(dr["Parent"]); + list.ParentList = Convert.ToString(dr["ParentList"]); + list.EnableSortOrder = Convert.ToInt32(dr["MaxSortOrder"]) > 0; + list.SystemList = Convert.ToInt32(dr["SystemList"]) > 0; + } + } + + return list; + } + + private Dictionary FillListInfoDictionary(IDataReader dr) + { + var dic = new Dictionary(); + try + { + while (dr.Read()) + { + // fill business object + ListInfo list = this.FillListInfo(dr, false); + if (!dic.ContainsKey(list.Key)) + { + dic.Add(list.Key, list); + } + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + + return dic; + } + + private Dictionary GetListInfoDictionary(int portalId) + { + string cacheKey = string.Format(DataCache.ListsCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ListsCacheTimeOut, + DataCache.ListsCachePriority), + c => this.FillListInfoDictionary(DataProvider.Instance().GetLists(portalId))); + } + + private IEnumerable GetListEntries(string listName, int portalId) + { + string cacheKey = string.Format(DataCache.ListEntriesCacheKey, portalId, listName); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.ListsCacheTimeOut, + DataCache.ListsCachePriority), + c => CBO.FillCollection(DataProvider.Instance().GetListEntriesByListName(listName, string.Empty, portalId))); + } } } diff --git a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs index fd4daa01bd2..bb463956b4b 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryCollection.cs @@ -33,7 +33,7 @@ public ListEntryInfo Item(int index) public ListEntryInfo Item(string key) { int index; - + // try { @@ -47,7 +47,7 @@ public ListEntryInfo Item(string key) Logger.Error(exc); return null; } - + index = Convert.ToInt32(this._keyIndexLookup[key.ToLowerInvariant()]); return (ListEntryInfo)this.List[index]; } diff --git a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs index 783151feb1a..ee6f1c7c7ba 100644 --- a/DNN Platform/Library/Common/Lists/ListEntryInfo.cs +++ b/DNN Platform/Library/Common/Lists/ListEntryInfo.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Common.Lists public class ListEntryInfo { private string _Text = Null.NullString; - + public ListEntryInfo() { this.ParentKey = Null.NullString; @@ -24,10 +24,6 @@ public ListEntryInfo() this.ListName = Null.NullString; } - public int EntryID { get; set; } - - public int PortalID { get; set; } - public string Key { get @@ -37,13 +33,11 @@ public string Key { _Key += "."; } - + return _Key + this.ListName + ":" + this.Value; } } - public string ListName { get; set; } - public string DisplayName { get @@ -52,8 +46,28 @@ public string DisplayName } } + /// + /// Gets the text value bypassing localization. + /// + /// + /// The text value of the list entry item as it was set originally. + /// + public string TextNonLocalized + { + get + { + return this._Text; + } + } + + public int EntryID { get; set; } + + public int PortalID { get; set; } + + public string ListName { get; set; } + public string Value { get; set; } - + /// /// 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 /// "App_GlobalResources/List_[ListName]". If not found the original (database) value is used. @@ -84,35 +98,21 @@ public string Text { // ignore } - - if (string.IsNullOrEmpty(res)) - { - res = this._Text; - } - + + if (string.IsNullOrEmpty(res)) + { + res = this._Text; + } + return res; } - + set { this._Text = value; } } - /// - /// Gets the text value bypassing localization. - /// - /// - /// The text value of the list entry item as it was set originally. - /// - public string TextNonLocalized - { - get - { - return this._Text; - } - } - public string Description { get; set; } public int ParentID { get; set; } diff --git a/DNN Platform/Library/Common/Lists/ListInfo.cs b/DNN Platform/Library/Common/Lists/ListInfo.cs index beebf4c9b15..9ef46b6016f 100644 --- a/DNN Platform/Library/Common/Lists/ListInfo.cs +++ b/DNN Platform/Library/Common/Lists/ListInfo.cs @@ -11,10 +11,10 @@ namespace DotNetNuke.Common.Lists [Serializable] public class ListInfo : BaseEntityInfo { - public ListInfo() - : this(string.Empty) - { - } + public ListInfo() + : this(string.Empty) + { + } public ListInfo(string Name) { @@ -29,8 +29,6 @@ public ListInfo(string Name) this.Name = Name; } - public int DefinitionID { get; set; } - public string DisplayName { get @@ -40,17 +38,11 @@ public string DisplayName { _DisplayName += ":"; } - + return _DisplayName + this.Name; } } - public bool EnableSortOrder { get; set; } - - public int EntryCount { get; set; } - - public bool IsPopulated { get; set; } - public string Key { get @@ -60,11 +52,19 @@ public string Key { _Key += ":"; } - + return _Key + this.Name; } } + public int DefinitionID { get; set; } + + public bool EnableSortOrder { get; set; } + + public int EntryCount { get; set; } + + public bool IsPopulated { get; set; } + public int Level { get; set; } public string Name { get; set; } diff --git a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs index cd3108ca966..7bae697374f 100644 --- a/DNN Platform/Library/Common/Lists/ListInfoCollection.cs +++ b/DNN Platform/Library/Common/Lists/ListInfoCollection.cs @@ -22,7 +22,7 @@ public ListInfo GetChildren(string ParentName) public void Add(string key, object value) { int index; - + // try { @@ -50,12 +50,6 @@ public object Item(int index) } } - internal new void Clear() - { - this.mKeyIndexLookup.Clear(); - base.Clear(); - } - public object Item(string key) { int index; @@ -72,7 +66,7 @@ public object Item(string key) Logger.Error(exc); return null; } - + index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); obj = this.List[index]; return obj; @@ -95,7 +89,7 @@ public object Item(string key, bool Cache) { Logger.Error(exc); } - + // key will be in format Country.US:Region if (!itemExists) { @@ -103,7 +97,7 @@ public object Item(string key, bool Cache) string listName = key.Substring(key.IndexOf(":") + 1); string parentKey = key.Replace(listName, string.Empty).TrimEnd(':'); ListInfo listInfo = ctlLists.GetListInfo(listName, parentKey); - + // the collection has been cache, so add this entry list into it if specified if (Cache) { @@ -116,7 +110,7 @@ public object Item(string key, bool Cache) index = Convert.ToInt32(this.mKeyIndexLookup[key.ToLowerInvariant()]); obj = this.List[index]; } - + return obj; } @@ -130,8 +124,14 @@ public ArrayList GetChild(string ParentKey) childList.Add(child); } } - + return childList; } + + internal new void Clear() + { + this.mKeyIndexLookup.Clear(); + base.Clear(); + } } } diff --git a/DNN Platform/Library/Common/NavigationManager.cs b/DNN Platform/Library/Common/NavigationManager.cs index f0257b2b86c..56f7cef1697 100644 --- a/DNN Platform/Library/Common/NavigationManager.cs +++ b/DNN Platform/Library/Common/NavigationManager.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Common internal class NavigationManager : INavigationManager { private readonly IPortalController _portalController; - + public NavigationManager(IPortalController portalController) { this._portalController = portalController; @@ -176,12 +176,12 @@ public string NavigateURL(int tabID, bool isSuperTab, IPortalSettings settings, { url += "&ctl=" + controlKey; } - + if (additionalParameters != null) { url = additionalParameters.Where(parameter => !string.IsNullOrEmpty(parameter)).Aggregate(url, (current, parameter) => current + ("&" + parameter)); } - + if (isSuperTab) { url += "&portalid=" + settings.PortalId; diff --git a/DNN Platform/Library/Common/Requires.cs b/DNN Platform/Library/Common/Requires.cs index dd0b3c7eca9..16032e80cfc 100644 --- a/DNN Platform/Library/Common/Requires.cs +++ b/DNN Platform/Library/Common/Requires.cs @@ -115,7 +115,7 @@ public static void PropertyNotNegative(T item, string propertyName) if (intValue < 0) { - throw new ArgumentOutOfRangeException( + throw new ArgumentOutOfRangeException( propertyName, Localization.GetExceptionMessage("PropertyCannotBeNegative", "The property '{1}' in object '{0}' cannot be negative.", typeof(T).Name, propertyName)); } @@ -132,7 +132,7 @@ public static void PropertyNotNegative(string argName, string argProperty, int p { if (propertyValue < 0) { - throw new ArgumentOutOfRangeException( + throw new ArgumentOutOfRangeException( argName, Localization.GetExceptionMessage("PropertyCannotBeNegative", "The property '{1}' in object '{0}' cannot be negative.", argName, argProperty)); } @@ -155,8 +155,8 @@ public static void PropertyNotNull(string argName, string argValue) /// The object to test. /// Name of the property. /// - public static void PropertyNotNull(T item, string propertyName) - where T : class + public static void PropertyNotNull(T item, string propertyName) + where T : class { // Check first if the item is null NotNull(item); @@ -204,7 +204,7 @@ public static void PropertyNotNullOrEmpty(string argName, string argProperty, st { if (string.IsNullOrEmpty(propertyValue)) { - throw new ArgumentException( + throw new ArgumentException( argName, Localization.GetExceptionMessage("PropertyCannotBeNullOrEmpty", "The property '{1}' in object '{0}' cannot be null or empty.", argName, argProperty)); } @@ -219,8 +219,8 @@ public static void PropertyNotNullOrEmpty(string argName, string argProperty, st /// The property value. /// The test value. /// - public static void PropertyNotEqualTo(string argName, string argProperty, TValue propertyValue, TValue testValue) - where TValue : IEquatable + public static void PropertyNotEqualTo(string argName, string argProperty, TValue propertyValue, TValue testValue) + where TValue : IEquatable { if (propertyValue.Equals(testValue)) { diff --git a/DNN Platform/Library/Common/SerializableKeyValuePair.cs b/DNN Platform/Library/Common/SerializableKeyValuePair.cs index 754be62587c..8b33b4abbd2 100644 --- a/DNN Platform/Library/Common/SerializableKeyValuePair.cs +++ b/DNN Platform/Library/Common/SerializableKeyValuePair.cs @@ -17,7 +17,7 @@ public SerializableKeyValuePair(TKey key, TValue value) this.Key = key; this.Value = value; } - + [DataMember(Name = "key")] public TKey Key { get; set; } diff --git a/DNN Platform/Library/Common/Utilities/CBO.cs b/DNN Platform/Library/Common/Utilities/CBO.cs index 94f93369189..1fb2c1e9001 100644 --- a/DNN Platform/Library/Common/Utilities/CBO.cs +++ b/DNN Platform/Library/Common/Utilities/CBO.cs @@ -27,16 +27,16 @@ namespace DotNetNuke.Common.Utilities /// The CBO class generates objects. /// public partial class CBO : ServiceLocator, ICBO - { + { private const string defaultPrimaryKey = "ItemID"; - private const string objectMapCacheKey = "ObjectMap_"; - + private const string objectMapCacheKey = "ObjectMap_"; + /// ----------------------------------------------------------------------------- /// /// CloneObject clones an object. /// - /// The Object to Clone. + /// The Object to Clone. /// /// ----------------------------------------------------------------------------- public static object CloneObject(object objObject) @@ -45,7 +45,7 @@ public static object CloneObject(object objObject) { 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) @@ -63,7 +63,7 @@ public static object CloneObject(object objObject) { objProperty.SetValue(objNewObject, objPropertyClone.Clone(), null); } - + // Check if Property is IEnumerable var enumerable = objProperty.GetValue(objObject, null) as IEnumerable; if (enumerable != null) @@ -76,7 +76,7 @@ public static object CloneObject(object objObject) list.Add(CloneObject(obj)); } } - + var dic = objProperty.GetValue(objNewObject, null) as IDictionary; if (dic != null) { @@ -88,7 +88,7 @@ public static object CloneObject(object objObject) } } } - + return objNewObject; } catch (Exception exc) @@ -96,973 +96,972 @@ public static object CloneObject(object objObject) Exceptions.LogException(exc); return null; } - } - + } + public static void CloseDataReader(IDataReader dr, bool closeReader) { // close datareader if (dr != null && closeReader) { - using (dr) - { - dr.Close(); - } + using (dr) + { + dr.Close(); + } } - } - - List ICBO.FillCollection(IDataReader dr) + } + + /// ----------------------------------------------------------------------------- + /// + /// CreateObject creates a new object of Type TObject. + /// + /// The type of object to create. + /// A flag that indicates whether to initialise the + /// object. + /// + /// ----------------------------------------------------------------------------- + public static TObject CreateObject(bool initialise) { - return (List)FillListFromReader(dr, new List(), true); + return (TObject)CreateObjectInternal(typeof(TObject), initialise); } - TObject ICBO.FillObject(IDataReader dr) + public static TObject DeserializeObject(string fileName) { - return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); + return DeserializeObject(XmlReader.Create(new FileStream(fileName, FileMode.Open, FileAccess.Read))); } - - protected override Func GetFactory() + + public static TObject DeserializeObject(XmlDocument document) { - return () => new CBO(); - } - - private static object CreateObjectInternal(Type objType, bool initialise) + return DeserializeObject(XmlReader.Create(new StringReader(document.OuterXml))); + } + + public static TObject DeserializeObject(Stream stream) { - object objObject = Activator.CreateInstance(objType); + return DeserializeObject(XmlReader.Create(stream)); + } - if (initialise) - { - InitializeObject(objObject); - } - - return objObject; + public static TObject DeserializeObject(TextReader reader) + { + return DeserializeObject(XmlReader.Create(reader)); } - private static object CreateObjectFromReader(Type objType, IDataReader dr, bool closeReader) + public static TObject DeserializeObject(XmlReader reader) { - object objObject = null; - bool isSuccess = Null.NullBoolean; - bool canRead = true; + // First Create the Object + var objObject = CreateObject(true); - if (closeReader) - { - canRead = false; - - // read datareader - if (dr.Read()) - { - canRead = true; - } - } - - try + // Try to cast the Object as IXmlSerializable + var xmlSerializableObject = objObject as IXmlSerializable; + if (xmlSerializableObject == null) { - if (canRead) - { - // Create the Object - objObject = CreateObjectInternal(objType, false); - - // hydrate the custom business object - FillObjectFromReader(objObject, dr); - } - - isSuccess = true; + // Use XmlSerializer + var serializer = new XmlSerializer(objObject.GetType()); + objObject = (TObject)serializer.Deserialize(reader); } - finally + else { - // Ensure DataReader is closed - if (!isSuccess) - { - closeReader = true; - } - - CloseDataReader(dr, closeReader); + // Use XmlReader + xmlSerializableObject.ReadXml(reader); } - + return objObject; } - private static IDictionary FillDictionaryFromReader(string keyField, IDataReader dr, - IDictionary - objDictionary, - bool closeReader) + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a Collection of objects from a DataReader. + /// + /// The Data Reader. + /// The type of the Object. + /// + /// ----------------------------------------------------------------------------- + public static ArrayList FillCollection(IDataReader dr, Type objType) { - TValue objObject; - TKey keyValue = default(TKey); - bool isSuccess = Null.NullBoolean; + return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), true); + } + + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a Collection of objects from a DataReader. + /// + /// The Data Reader. + /// The type of the Object. + /// Flag that indicates whether the Data Reader should be closed. + /// + /// ----------------------------------------------------------------------------- + public static ArrayList FillCollection(IDataReader dr, Type objType, bool closeReader) + { + return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), closeReader); + } + + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a Collection of objects from a DataReader. + /// + /// The Data Reader. + /// The type of the Object. + /// An IList to fill. + /// + /// ----------------------------------------------------------------------------- + public static IList FillCollection(IDataReader dr, Type objType, ref IList objToFill) + { + return FillListFromReader(objType, dr, objToFill, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a Collection of objects from a DataReader. + /// + /// The type of object. + /// The Data Reader. + /// + /// ----------------------------------------------------------------------------- + public static List FillCollection(IDataReader dr) + { + return (List)FillListFromReader(dr, new List(), true); + } + + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a Collection of objects from a DataReader. + /// + /// The type of object. + /// The List to fill. + /// The Data Reader. + /// + /// ----------------------------------------------------------------------------- + public static IList FillCollection(IDataReader dr, ref IList objToFill) + { + return FillListFromReader(dr, objToFill, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// FillCollection fills a List of objects from a DataReader. + /// + /// The type of the Object. + /// The List to fill. + /// The Data Reader. + /// A flag that indicates whether the DataReader should be closed. + /// + /// ----------------------------------------------------------------------------- + public static IList FillCollection(IDataReader dr, IList objToFill, bool closeReader) + { + return FillListFromReader(dr, objToFill, closeReader); + } + /// ----------------------------------------------------------------------------- + /// + /// Generic version of FillCollection fills a List custom business object of a specified type + /// from the supplied DataReader. + /// + /// The IDataReader to use to fill the object. + /// The type of the Object. + /// The total No of records. + /// A List of custom business objects. + /// + /// ----------------------------------------------------------------------------- + public static ArrayList FillCollection(IDataReader dr, ref Type objType, ref int totalRecords) + { + var objFillCollection = (ArrayList)FillListFromReader(objType, dr, new ArrayList(), false); try { - // iterate datareader - while (dr.Read()) + if (dr.NextResult()) { - // Create the Object - objObject = (TValue)CreateObjectFromReader(typeof(TValue), dr, false); - if (keyField == "KeyID" && objObject is IHydratable) - { - // Get the value of the key field from the KeyID - keyValue = (TKey)Null.SetNull(((IHydratable)objObject).KeyID, keyValue); - } - else - { - // Get the value of the key field from the DataReader - if (typeof(TKey).Name == "Int32" && dr[keyField].GetType().Name == "Decimal") - { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof(TKey)); - } - else if (typeof(TKey).Name.Equals("string", StringComparison.OrdinalIgnoreCase) && - dr[keyField].GetType().Name.Equals("dbnull", StringComparison.OrdinalIgnoreCase)) - { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); - } - else - { - keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); - } - } - - // add to dictionary - if (objObject != null) - { - objDictionary[keyValue] = objObject; - } + // Get the total no of records from the second result + totalRecords = Globals.GetTotalRecords(ref dr); } - - isSuccess = true; + } + catch (Exception exc) + { + Exceptions.LogException(exc); } finally { // Ensure DataReader is closed - if (!isSuccess) - { - closeReader = true; - } - - CloseDataReader(dr, closeReader); + CloseDataReader(dr, true); } - // Return the dictionary - return objDictionary; + return objFillCollection; } - private static IList FillListFromReader(Type objType, IDataReader dr, IList objList, bool closeReader) - { - object objObject; - bool isSuccess = Null.NullBoolean; + /// ----------------------------------------------------------------------------- + /// + /// Generic version of FillCollection fills a List custom business object of a specified type + /// from the supplied DataReader. + /// + /// The type of the business object. + /// The IDataReader to use to fill the object. + /// + /// A List of custom business objects. + /// + /// ----------------------------------------------------------------------------- + public static List FillCollection(IDataReader dr, ref int totalRecords) + { + IList objFillCollection = FillCollection(dr, new List(), false); try { - // iterate datareader - while (dr.Read()) + if (dr.NextResult()) { - // Create the Object - objObject = CreateObjectFromReader(objType, dr, false); - - // add to collection - objList.Add(objObject); + // Get the total no of records from the second result + totalRecords = Globals.GetTotalRecords(ref dr); } - - isSuccess = true; + } + catch (Exception exc) + { + Exceptions.LogException(exc); } finally { // Ensure DataReader is closed - if (!isSuccess) - { - closeReader = true; - } - - CloseDataReader(dr, closeReader); + CloseDataReader(dr, true); } - - return objList; + + return (List)objFillCollection; } - private static IList FillListFromReader(IDataReader dr, IList objList, bool closeReader) + /// + /// FillDictionary fills a Dictionary of objects from a DataReader. + /// + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Data Reader. + /// + public static Dictionary FillDictionary(string keyField, IDataReader dr) { - TItem objObject; - bool isSuccess = Null.NullBoolean; - try - { - // iterate datareader - while (dr.Read()) - { - // Create the Object - objObject = (TItem)CreateObjectFromReader(typeof(TItem), dr, false); - - // add to collection - objList.Add(objObject); - } - - isSuccess = true; - } - finally - { - // Ensure DataReader is closed - if (!isSuccess) - { - closeReader = true; - } - - CloseDataReader(dr, closeReader); - } - - return objList; + return + (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), true); } - private static void FillObjectFromReader(object objObject, IDataReader dr) + /// + /// FillDictionary fills a Dictionary of objects from a DataReader. + /// + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Data Reader. + /// A flag indicating whether to close the reader. + /// + public static Dictionary FillDictionary(string keyField, IDataReader dr, bool closeReader) { - try - { - // Determine if object is IHydratable - if (objObject is IHydratable) - { - // Use IHydratable's Fill - var objHydratable = objObject as IHydratable; - if (objHydratable != null) - { - objHydratable.Fill(dr); - } - } - else - { - // Use Reflection - HydrateObject(objObject, dr); - } - } - catch (IndexOutOfRangeException iex) - { - // Call to GetOrdinal is being made with a bad column name - if (Host.ThrowCBOExceptions) - { - throw new ObjectHydrationException("Error Reading DataReader", iex, objObject.GetType(), dr); - } - else - { - Exceptions.LogException(iex); - } - } + return (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), closeReader); } - private static void HydrateObject(object hydratedObject, IDataReader dr) + /// ----------------------------------------------------------------------------- + /// + /// FillDictionary fills a Dictionary of objects from a DataReader. + /// + /// The key for the Dictionary. + /// The value for the Dictionary Item. + /// The key field used for the Key. + /// The Dictionary to fill. + /// The Data Reader. + /// + /// ----------------------------------------------------------------------------- + public static Dictionary FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary) { - PropertyInfo objPropertyInfo = null; - Type propType = null; - object coloumnValue; - Type objDataType; - int intIndex; - - // get cached object mapping for type - ObjectMappingInfo objMappingInfo = GetObjectMapping(hydratedObject.GetType()); - if (hydratedObject is BaseEntityInfo && !(hydratedObject is ScheduleItem)) - { - // Call the base classes fill method to populate base class properties - ((BaseEntityInfo)hydratedObject).FillBaseProperties(dr); - } - - // fill object with values from datareader - for (intIndex = 0; intIndex <= dr.FieldCount - 1; intIndex++) - { - // If the Column matches a Property in the Object Map's PropertyInfo Dictionary - if (objMappingInfo.Properties.TryGetValue(dr.GetName(intIndex).ToUpperInvariant(), out objPropertyInfo)) - { - // Get its type - propType = objPropertyInfo.PropertyType; - - // If property can be set - if (objPropertyInfo.CanWrite) - { - // Get the Data Value from the data reader - coloumnValue = dr.GetValue(intIndex); - - // Get the Data Value's type - objDataType = coloumnValue.GetType(); - if (coloumnValue == null || coloumnValue == DBNull.Value) - { - // set property value to Null - objPropertyInfo.SetValue(hydratedObject, Null.SetNull(objPropertyInfo), null); - } - else if (propType.Equals(objDataType)) - { - // Property and data objects are the same type - objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); - } - else - { - // business object info class member data type does not match datareader member data type - // need to handle enumeration conversions differently than other base types - if (propType.BaseType.Equals(typeof(Enum))) - { - // check if value is numeric and if not convert to integer ( supports databases like Oracle ) - if (Globals.NumberMatchRegex.IsMatch(coloumnValue.ToString())) - { - objPropertyInfo.SetValue( - hydratedObject, - Enum.ToObject(propType, Convert.ToInt32(coloumnValue)), - null); - } - else - { - objPropertyInfo.SetValue(hydratedObject, Enum.ToObject(propType, coloumnValue), null); - } - } - else if (propType == typeof(Guid)) - { - // guid is not a datatype common across all databases ( ie. Oracle ) - objPropertyInfo.SetValue( - hydratedObject, - Convert.ChangeType(new Guid(coloumnValue.ToString()), propType), - null); - } - else if (propType == typeof(Version)) - { - objPropertyInfo.SetValue(hydratedObject, new Version(coloumnValue.ToString()), null); - } - else if (coloumnValue is IConvertible) - { - objPropertyInfo.SetValue(hydratedObject, ChangeType(coloumnValue, propType), null); - } - else - { - // try explicit conversion - objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); - } - } - } - } - } + return (Dictionary)FillDictionaryFromReader(keyField, dr, objDictionary, true); } - 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); - } - - return Convert.ChangeType(obj, type); + /// ----------------------------------------------------------------------------- + /// + /// FillObject fills an object from a DataReader. + /// + /// The type of the object. + /// The Data Reader. + /// + /// ----------------------------------------------------------------------------- + public static TObject FillObject(IDataReader dr) + { + return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); } - private static object GetDefault(Type type) - { - if (type.IsValueType) - { - return Activator.CreateInstance(type); - } - - return null; - } - - private static string GetColumnName(PropertyInfo objProperty) + /// ----------------------------------------------------------------------------- + /// + /// FillObject fills an object from a DataReader. + /// + /// The type of the object. + /// The Data Reader. + /// A flag that indicates the reader should be closed. + /// + /// ----------------------------------------------------------------------------- + public static TObject FillObject(IDataReader dr, bool closeReader) { - string columnName = objProperty.Name; - return columnName; + return (TObject)CreateObjectFromReader(typeof(TObject), dr, closeReader); } - private static ObjectMappingInfo GetObjectMapping(Type objType) + public static IQueryable FillQueryable(IDataReader dr) { - string cacheKey = objectMapCacheKey + objType.FullName; - var objMap = (ObjectMappingInfo)DataCache.GetCache(cacheKey); - if (objMap == null) - { - // Create an ObjectMappingInfo instance - objMap = new ObjectMappingInfo(); - objMap.ObjectType = objType.FullName; - - // Reflect on class to create Object Map - objMap.PrimaryKey = GetPrimaryKey(objType); - objMap.TableName = GetTableName(objType); - - // Iterate through the objects properties and add each one to the ObjectMappingInfo's Properties Dictionary - foreach (PropertyInfo objProperty in objType.GetProperties()) - { - objMap.Properties.Add(objProperty.Name.ToUpperInvariant(), objProperty); - objMap.ColumnNames.Add(objProperty.Name.ToUpperInvariant(), GetColumnName(objProperty)); - } - - // Persist to Cache - DataCache.SetCache(cacheKey, objMap); - } + return FillListFromReader(dr, new List(), true).AsQueryable(); + } - // Return Object Map - return objMap; + /// ----------------------------------------------------------------------------- + /// + /// FillSortedList fills a SortedList of objects from a DataReader. + /// + /// The key for the SortedList. + /// The value for the SortedList Item. + /// The key field used for the Key. + /// The Data Reader. + /// + /// ----------------------------------------------------------------------------- + public static SortedList FillSortedList(string keyField, IDataReader dr) + { + return + (SortedList)FillDictionaryFromReader(keyField, dr, new SortedList(), true); } - private static string GetPrimaryKey(Type objType) + public static void DeserializeSettings(IDictionary dictionary, XmlNode rootNode, string elementName) { - string primaryKey = defaultPrimaryKey; - return primaryKey; + string sKey = null; + string sValue = null; + + foreach (XmlNode settingNode in rootNode.SelectNodes(elementName)) + { + sKey = XmlUtils.GetNodeValue(settingNode.CreateNavigator(), "settingname"); + sValue = XmlUtils.GetNodeValue(settingNode.CreateNavigator(), "settingvalue"); + + dictionary[sKey] = sValue; + } } - private static string GetTableName(Type objType) + /// + /// Iterates items in a IDictionary object and generates XML nodes. + /// + /// The IDictionary to iterate. + /// The XML document the node should be added to. + /// Path at which to serialize settings. + /// The name of the new element created. + /// + /// + public static void SerializeSettings(IDictionary dictionary, XmlDocument document, string targetPath, string elementName) { - string tableName = string.Empty; - - // If no attrubute then use Type Name - if (string.IsNullOrEmpty(tableName)) + string sOuterElementName = elementName + "s"; + string sInnerElementName = elementName; + XmlNode nodeSetting = default(XmlNode); + XmlNode nodeSettings = default(XmlNode); + XmlNode nodeSettingName = default(XmlNode); + XmlNode nodeSettingValue = default(XmlNode); + + XmlNode targetNode = document.SelectSingleNode(targetPath); + + if (targetNode != null) { - tableName = objType.Name; - if (tableName.EndsWith("Info")) + nodeSettings = targetNode.AppendChild(document.CreateElement(sOuterElementName)); + foreach (object sKey in dictionary.Keys) { - // Remove Info ending - tableName.Replace("Info", string.Empty); + nodeSetting = nodeSettings.AppendChild(document.CreateElement(sInnerElementName)); + + nodeSettingName = nodeSetting.AppendChild(document.CreateElement("settingname")); + nodeSettingName.InnerText = sKey.ToString(); + + nodeSettingValue = nodeSetting.AppendChild(document.CreateElement("settingvalue")); + nodeSettingValue.InnerText = dictionary[sKey].ToString(); } } - - // Check if there is an object qualifier - if (!string.IsNullOrEmpty(Config.GetSetting("ObjectQualifier"))) + else { - tableName = Config.GetSetting("ObjectQualifier") + tableName; + throw new ArgumentException("Invalid Target Path"); } - - return tableName; - } + } - TObject ICBO.GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) - { - return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); - } - /// ----------------------------------------------------------------------------- /// - /// CreateObject creates a new object of Type TObject. + /// GetCachedObject gets an object from the Cache. /// - /// The type of object to create. - /// A flag that indicates whether to initialise the - /// object. + /// The type of th object to fetch. + /// A CacheItemArgs object that provides parameters to manage the + /// cache AND to fetch the item if the cache has expired. + /// A CacheItemExpiredCallback delegate that is used to repopulate + /// the cache if the item has expired. /// /// ----------------------------------------------------------------------------- - public static TObject CreateObject(bool initialise) - { - return (TObject)CreateObjectInternal(typeof(TObject), initialise); - } - - public static TObject DeserializeObject(string fileName) - { - return DeserializeObject(XmlReader.Create(new FileStream(fileName, FileMode.Open, FileAccess.Read))); - } - - public static TObject DeserializeObject(XmlDocument document) - { - return DeserializeObject(XmlReader.Create(new StringReader(document.OuterXml))); - } - - public static TObject DeserializeObject(Stream stream) + public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) { - return DeserializeObject(XmlReader.Create(stream)); + return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired); } - public static TObject DeserializeObject(TextReader reader) + public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) { - return DeserializeObject(XmlReader.Create(reader)); + return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); } - public static TObject DeserializeObject(XmlReader reader) - { - // First Create the Object - var objObject = CreateObject(true); - - // Try to cast the Object as IXmlSerializable - var xmlSerializableObject = objObject as IXmlSerializable; - if (xmlSerializableObject == null) - { - // Use XmlSerializer - var serializer = new XmlSerializer(objObject.GetType()); - objObject = (TObject)serializer.Deserialize(reader); - } - else - { - // Use XmlReader - xmlSerializableObject.ReadXml(reader); - } - - return objObject; - } - /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader. + /// GetProperties gets a Dictionary of the Properties for an object. + /// + /// The type of the object. + /// + /// ----------------------------------------------------------------------------- + public static Dictionary GetProperties() + { + return GetObjectMapping(typeof(TObject)).Properties; + } + + /// ----------------------------------------------------------------------------- + /// + /// GetProperties gets a Dictionary of the Properties for an object. /// - /// The Data Reader. - /// The type of the Object. + /// The type of the object. /// /// ----------------------------------------------------------------------------- - public static ArrayList FillCollection(IDataReader dr, Type objType) + public static Dictionary GetProperties(Type objType) { - return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), true); + return GetObjectMapping(objType).Properties; } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader. + /// InitializeObject initialises all the properties of an object to their + /// Null Values. /// - /// The Data Reader. - /// The type of the Object. - /// Flag that indicates whether the Data Reader should be closed. - /// + /// The object to Initialise. /// ----------------------------------------------------------------------------- - public static ArrayList FillCollection(IDataReader dr, Type objType, bool closeReader) + public static void InitializeObject(object objObject) { - return (ArrayList)FillListFromReader(objType, dr, new ArrayList(), closeReader); + // initialize properties + foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objObject.GetType()).Properties.Values) + { + if (objPropertyInfo.CanWrite) + { + objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null); + } + } } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader. + /// InitializeObject initialises all the properties of an object to their + /// Null Values. /// - /// The Data Reader. - /// The type of the Object. - /// An IList to fill. + /// The object to Initialise. + /// The type of the object. /// /// ----------------------------------------------------------------------------- - public static IList FillCollection(IDataReader dr, Type objType, ref IList objToFill) + public static object InitializeObject(object objObject, Type objType) { - return FillListFromReader(objType, dr, objToFill, true); + // initialize properties + foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objType).Properties.Values) + { + if (objPropertyInfo.CanWrite) + { + objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null); + } + } + + return objObject; } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader. + /// SerializeObject serializes an Object. /// - /// The type of object. - /// The Data Reader. - /// + /// The object to Initialise. + /// A filename for the resulting serialized xml. /// ----------------------------------------------------------------------------- - public static List FillCollection(IDataReader dr) + public static void SerializeObject(object objObject, string fileName) { - return (List)FillListFromReader(dr, new List(), true); + using ( + XmlWriter writer = XmlWriter.Create(fileName, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + SerializeObject(objObject, writer); + writer.Flush(); + } } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a Collection of objects from a DataReader. + /// SerializeObject serializes an Object. /// - /// The type of object. - /// The List to fill. - /// The Data Reader. - /// + /// The object to Initialise. + /// An XmlDocument to serialize to. /// ----------------------------------------------------------------------------- - public static IList FillCollection(IDataReader dr, ref IList objToFill) + public static void SerializeObject(object objObject, XmlDocument document) { - return FillListFromReader(dr, objToFill, true); + var sb = new StringBuilder(); + using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Document))) + { + // Serialize the object + SerializeObject(objObject, writer); + + // Load XmlDocument + document.LoadXml(sb.ToString()); + } } /// ----------------------------------------------------------------------------- /// - /// FillCollection fills a List of objects from a DataReader. + /// SerializeObject serializes an Object. /// - /// The type of the Object. - /// The List to fill. - /// The Data Reader. - /// A flag that indicates whether the DataReader should be closed. - /// + /// The object to Initialise. + /// A Stream to serialize to. /// ----------------------------------------------------------------------------- - public static IList FillCollection(IDataReader dr, IList objToFill, bool closeReader) + public static void SerializeObject(object objObject, Stream stream) { - return FillListFromReader(dr, objToFill, closeReader); + using (XmlWriter writer = XmlWriter.Create(stream, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + SerializeObject(objObject, writer); + writer.Flush(); + } } /// ----------------------------------------------------------------------------- /// - /// Generic version of FillCollection fills a List custom business object of a specified type - /// from the supplied DataReader. + /// SerializeObject serializes an Object. /// - /// The IDataReader to use to fill the object. - /// The type of the Object. - /// The total No of records. - /// A List of custom business objects. - /// + /// The object to Initialise. + /// A TextWriter to serialize to. /// ----------------------------------------------------------------------------- - public static ArrayList FillCollection(IDataReader dr, ref Type objType, ref int totalRecords) + public static void SerializeObject(object objObject, TextWriter textWriter) + { + using ( + XmlWriter writer = XmlWriter.Create(textWriter, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + { + SerializeObject(objObject, writer); + writer.Flush(); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// SerializeObject serializes an Object. + /// + /// The object to Initialise. + /// An XmlWriter to serialize to. + /// ----------------------------------------------------------------------------- + public static void SerializeObject(object objObject, XmlWriter writer) + { + // Try to cast the Object as IXmlSerializable + var xmlSerializableObject = objObject as IXmlSerializable; + if (xmlSerializableObject == null) + { + // Use XmlSerializer + var serializer = new XmlSerializer(objObject.GetType()); + serializer.Serialize(writer, objObject); + } + else + { + // Use XmlWriter + xmlSerializableObject.WriteXml(writer); + } + } + + protected override Func GetFactory() + { + return () => new CBO(); + } + + private static object CreateObjectInternal(Type objType, bool initialise) + { + object objObject = Activator.CreateInstance(objType); + + if (initialise) + { + InitializeObject(objObject); + } + + return objObject; + } + + private static object CreateObjectFromReader(Type objType, IDataReader dr, bool closeReader) + { + object objObject = null; + bool isSuccess = Null.NullBoolean; + bool canRead = true; + + if (closeReader) + { + canRead = false; + + // read datareader + if (dr.Read()) + { + canRead = true; + } + } + + try + { + if (canRead) + { + // Create the Object + objObject = CreateObjectInternal(objType, false); + + // hydrate the custom business object + FillObjectFromReader(objObject, dr); + } + + isSuccess = true; + } + finally + { + // Ensure DataReader is closed + if (!isSuccess) + { + closeReader = true; + } + + CloseDataReader(dr, closeReader); + } + + return objObject; + } + + private static IDictionary FillDictionaryFromReader(string keyField, + IDataReader dr, + IDictionary objDictionary, + bool closeReader) + { + TValue objObject; + TKey keyValue = default(TKey); + bool isSuccess = Null.NullBoolean; + + try + { + // iterate datareader + while (dr.Read()) + { + // Create the Object + objObject = (TValue)CreateObjectFromReader(typeof(TValue), dr, false); + if (keyField == "KeyID" && objObject is IHydratable) + { + // Get the value of the key field from the KeyID + keyValue = (TKey)Null.SetNull(((IHydratable)objObject).KeyID, keyValue); + } + else + { + // Get the value of the key field from the DataReader + if (typeof(TKey).Name == "Int32" && dr[keyField].GetType().Name == "Decimal") + { + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], keyValue), typeof(TKey)); + } + else if (typeof(TKey).Name.Equals("string", StringComparison.OrdinalIgnoreCase) && + dr[keyField].GetType().Name.Equals("dbnull", StringComparison.OrdinalIgnoreCase)) + { + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); + } + else + { + keyValue = (TKey)Convert.ChangeType(Null.SetNull(dr[keyField], string.Empty), typeof(TKey)); + } + } + + // add to dictionary + if (objObject != null) + { + objDictionary[keyValue] = objObject; + } + } + + isSuccess = true; + } + finally + { + // Ensure DataReader is closed + if (!isSuccess) + { + closeReader = true; + } + + CloseDataReader(dr, closeReader); + } + + // Return the dictionary + return objDictionary; + } + + private static IList FillListFromReader(Type objType, IDataReader dr, IList objList, bool closeReader) { - var objFillCollection = (ArrayList)FillListFromReader(objType, dr, new ArrayList(), false); + object objObject; + bool isSuccess = Null.NullBoolean; try { - if (dr.NextResult()) + // iterate datareader + while (dr.Read()) { - // Get the total no of records from the second result - totalRecords = Globals.GetTotalRecords(ref dr); + // Create the Object + objObject = CreateObjectFromReader(objType, dr, false); + + // add to collection + objList.Add(objObject); } - } - catch (Exception exc) - { - Exceptions.LogException(exc); + + isSuccess = true; } finally { // Ensure DataReader is closed - CloseDataReader(dr, true); + if (!isSuccess) + { + closeReader = true; + } + + CloseDataReader(dr, closeReader); } - - return objFillCollection; + + return objList; } - /// ----------------------------------------------------------------------------- - /// - /// Generic version of FillCollection fills a List custom business object of a specified type - /// from the supplied DataReader. - /// - /// The type of the business object. - /// The IDataReader to use to fill the object. - /// - /// A List of custom business objects. - /// - /// ----------------------------------------------------------------------------- - public static List FillCollection(IDataReader dr, ref int totalRecords) + private static IList FillListFromReader(IDataReader dr, IList objList, bool closeReader) { - IList objFillCollection = FillCollection(dr, new List(), false); + TItem objObject; + bool isSuccess = Null.NullBoolean; try { - if (dr.NextResult()) + // iterate datareader + while (dr.Read()) { - // Get the total no of records from the second result - totalRecords = Globals.GetTotalRecords(ref dr); + // Create the Object + objObject = (TItem)CreateObjectFromReader(typeof(TItem), dr, false); + + // add to collection + objList.Add(objObject); } - } - catch (Exception exc) - { - Exceptions.LogException(exc); + + isSuccess = true; } finally { // Ensure DataReader is closed - CloseDataReader(dr, true); + if (!isSuccess) + { + closeReader = true; + } + + CloseDataReader(dr, closeReader); } - - return (List)objFillCollection; - } - - /// - /// FillDictionary fills a Dictionary of objects from a DataReader. - /// - /// The key for the Dictionary. - /// The value for the Dictionary Item. - /// The key field used for the Key. - /// The Data Reader. - /// - public static Dictionary FillDictionary(string keyField, IDataReader dr) - { - return - (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), true); - } - /// - /// FillDictionary fills a Dictionary of objects from a DataReader. - /// - /// The key for the Dictionary. - /// The value for the Dictionary Item. - /// The key field used for the Key. - /// The Data Reader. - /// A flag indicating whether to close the reader. - /// - public static Dictionary FillDictionary(string keyField, IDataReader dr, bool closeReader) - { - return (Dictionary)FillDictionaryFromReader(keyField, dr, new Dictionary(), closeReader); + return objList; } - /// ----------------------------------------------------------------------------- - /// - /// FillDictionary fills a Dictionary of objects from a DataReader. - /// - /// The key for the Dictionary. - /// The value for the Dictionary Item. - /// The key field used for the Key. - /// The Dictionary to fill. - /// The Data Reader. - /// - /// ----------------------------------------------------------------------------- - public static Dictionary FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary) - { - return (Dictionary)FillDictionaryFromReader(keyField, dr, objDictionary, true); - } - - /// ----------------------------------------------------------------------------- - /// - /// FillObject fills an object from a DataReader. - /// - /// The type of the object. - /// The Data Reader. - /// - /// ----------------------------------------------------------------------------- - public static TObject FillObject(IDataReader dr) + private static void FillObjectFromReader(object objObject, IDataReader dr) { - return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); + try + { + // Determine if object is IHydratable + if (objObject is IHydratable) + { + // Use IHydratable's Fill + var objHydratable = objObject as IHydratable; + if (objHydratable != null) + { + objHydratable.Fill(dr); + } + } + else + { + // Use Reflection + HydrateObject(objObject, dr); + } + } + catch (IndexOutOfRangeException iex) + { + // Call to GetOrdinal is being made with a bad column name + if (Host.ThrowCBOExceptions) + { + throw new ObjectHydrationException("Error Reading DataReader", iex, objObject.GetType(), dr); + } + else + { + Exceptions.LogException(iex); + } + } } - /// ----------------------------------------------------------------------------- - /// - /// FillObject fills an object from a DataReader. - /// - /// The type of the object. - /// The Data Reader. - /// A flag that indicates the reader should be closed. - /// - /// ----------------------------------------------------------------------------- - public static TObject FillObject(IDataReader dr, bool closeReader) - { - return (TObject)CreateObjectFromReader(typeof(TObject), dr, closeReader); - } - - public static IQueryable FillQueryable(IDataReader dr) + private static void HydrateObject(object hydratedObject, IDataReader dr) { - return FillListFromReader(dr, new List(), true).AsQueryable(); - } + PropertyInfo objPropertyInfo = null; + Type propType = null; + object coloumnValue; + Type objDataType; + int intIndex; - /// ----------------------------------------------------------------------------- - /// - /// FillSortedList fills a SortedList of objects from a DataReader. - /// - /// The key for the SortedList. - /// The value for the SortedList Item. - /// The key field used for the Key. - /// The Data Reader. - /// - /// ----------------------------------------------------------------------------- - public static SortedList FillSortedList(string keyField, IDataReader dr) - { - return - (SortedList)FillDictionaryFromReader(keyField, dr, new SortedList(), true); + // get cached object mapping for type + ObjectMappingInfo objMappingInfo = GetObjectMapping(hydratedObject.GetType()); + if (hydratedObject is BaseEntityInfo && !(hydratedObject is ScheduleItem)) + { + // Call the base classes fill method to populate base class properties + ((BaseEntityInfo)hydratedObject).FillBaseProperties(dr); + } + + // fill object with values from datareader + for (intIndex = 0; intIndex <= dr.FieldCount - 1; intIndex++) + { + // If the Column matches a Property in the Object Map's PropertyInfo Dictionary + if (objMappingInfo.Properties.TryGetValue(dr.GetName(intIndex).ToUpperInvariant(), out objPropertyInfo)) + { + // Get its type + propType = objPropertyInfo.PropertyType; + + // If property can be set + if (objPropertyInfo.CanWrite) + { + // Get the Data Value from the data reader + coloumnValue = dr.GetValue(intIndex); + + // Get the Data Value's type + objDataType = coloumnValue.GetType(); + if (coloumnValue == null || coloumnValue == DBNull.Value) + { + // set property value to Null + objPropertyInfo.SetValue(hydratedObject, Null.SetNull(objPropertyInfo), null); + } + else if (propType.Equals(objDataType)) + { + // Property and data objects are the same type + objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); + } + else + { + // business object info class member data type does not match datareader member data type + // need to handle enumeration conversions differently than other base types + if (propType.BaseType.Equals(typeof(Enum))) + { + // check if value is numeric and if not convert to integer ( supports databases like Oracle ) + if (Globals.NumberMatchRegex.IsMatch(coloumnValue.ToString())) + { + objPropertyInfo.SetValue( + hydratedObject, + Enum.ToObject(propType, Convert.ToInt32(coloumnValue)), + null); + } + else + { + objPropertyInfo.SetValue(hydratedObject, Enum.ToObject(propType, coloumnValue), null); + } + } + else if (propType == typeof(Guid)) + { + // guid is not a datatype common across all databases ( ie. Oracle ) + objPropertyInfo.SetValue( + hydratedObject, + Convert.ChangeType(new Guid(coloumnValue.ToString()), propType), + null); + } + else if (propType == typeof(Version)) + { + objPropertyInfo.SetValue(hydratedObject, new Version(coloumnValue.ToString()), null); + } + else if (coloumnValue is IConvertible) + { + objPropertyInfo.SetValue(hydratedObject, ChangeType(coloumnValue, propType), null); + } + else + { + // try explicit conversion + objPropertyInfo.SetValue(hydratedObject, coloumnValue, null); + } + } + } + } + } } - public static void DeserializeSettings(IDictionary dictionary, XmlNode rootNode, string elementName) + private static object ChangeType(object obj, Type type) { - string sKey = null; - string sValue = null; + Type u = Nullable.GetUnderlyingType(type); - foreach (XmlNode settingNode in rootNode.SelectNodes(elementName)) + if (u != null) { - sKey = XmlUtils.GetNodeValue(settingNode.CreateNavigator(), "settingname"); - sValue = XmlUtils.GetNodeValue(settingNode.CreateNavigator(), "settingvalue"); + if (obj == null) + { + return GetDefault(type); + } - dictionary[sKey] = sValue; + return Convert.ChangeType(obj, u); } + + return Convert.ChangeType(obj, type); } - /// - /// Iterates items in a IDictionary object and generates XML nodes. - /// - /// The IDictionary to iterate. - /// The XML document the node should be added to. - /// Path at which to serialize settings. - /// The name of the new element created. - /// - /// - public static void SerializeSettings(IDictionary dictionary, XmlDocument document, string targetPath, - string elementName) + private static object GetDefault(Type type) { - string sOuterElementName = elementName + "s"; - string sInnerElementName = elementName; - XmlNode nodeSetting = default(XmlNode); - XmlNode nodeSettings = default(XmlNode); - XmlNode nodeSettingName = default(XmlNode); - XmlNode nodeSettingValue = default(XmlNode); - - XmlNode targetNode = document.SelectSingleNode(targetPath); - - if (targetNode != null) - { - nodeSettings = targetNode.AppendChild(document.CreateElement(sOuterElementName)); - foreach (object sKey in dictionary.Keys) - { - nodeSetting = nodeSettings.AppendChild(document.CreateElement(sInnerElementName)); - - nodeSettingName = nodeSetting.AppendChild(document.CreateElement("settingname")); - nodeSettingName.InnerText = sKey.ToString(); - - nodeSettingValue = nodeSetting.AppendChild(document.CreateElement("settingvalue")); - nodeSettingValue.InnerText = dictionary[sKey].ToString(); - } - } - else + if (type.IsValueType) { - throw new ArgumentException("Invalid Target Path"); + return Activator.CreateInstance(type); } - } - - /// ----------------------------------------------------------------------------- - /// - /// GetCachedObject gets an object from the Cache. - /// - /// The type of th object to fetch. - /// A CacheItemArgs object that provides parameters to manage the - /// cache AND to fetch the item if the cache has expired. - /// A CacheItemExpiredCallback delegate that is used to repopulate - /// the cache if the item has expired. - /// - /// ----------------------------------------------------------------------------- - public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) - { - return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired); + + return null; } - public static TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) - { - return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetProperties gets a Dictionary of the Properties for an object. - /// - /// The type of the object. - /// - /// ----------------------------------------------------------------------------- - public static Dictionary GetProperties() + private static string GetColumnName(PropertyInfo objProperty) { - return GetObjectMapping(typeof(TObject)).Properties; + string columnName = objProperty.Name; + return columnName; } - /// ----------------------------------------------------------------------------- - /// - /// GetProperties gets a Dictionary of the Properties for an object. - /// - /// The type of the object. - /// - /// ----------------------------------------------------------------------------- - public static Dictionary GetProperties(Type objType) - { - return GetObjectMapping(objType).Properties; - } - - /// ----------------------------------------------------------------------------- - /// - /// InitializeObject initialises all the properties of an object to their - /// Null Values. - /// - /// The object to Initialise. - /// ----------------------------------------------------------------------------- - public static void InitializeObject(object objObject) + private static ObjectMappingInfo GetObjectMapping(Type objType) { - // initialize properties - foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objObject.GetType()).Properties.Values) + string cacheKey = objectMapCacheKey + objType.FullName; + var objMap = (ObjectMappingInfo)DataCache.GetCache(cacheKey); + if (objMap == null) { - if (objPropertyInfo.CanWrite) + // Create an ObjectMappingInfo instance + objMap = new ObjectMappingInfo(); + objMap.ObjectType = objType.FullName; + + // Reflect on class to create Object Map + objMap.PrimaryKey = GetPrimaryKey(objType); + objMap.TableName = GetTableName(objType); + + // Iterate through the objects properties and add each one to the ObjectMappingInfo's Properties Dictionary + foreach (PropertyInfo objProperty in objType.GetProperties()) { - objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null); + objMap.Properties.Add(objProperty.Name.ToUpperInvariant(), objProperty); + objMap.ColumnNames.Add(objProperty.Name.ToUpperInvariant(), GetColumnName(objProperty)); } + + // Persist to Cache + DataCache.SetCache(cacheKey, objMap); } + + // Return Object Map + return objMap; } - /// ----------------------------------------------------------------------------- - /// - /// InitializeObject initialises all the properties of an object to their - /// Null Values. - /// - /// The object to Initialise. - /// The type of the object. - /// - /// ----------------------------------------------------------------------------- - public static object InitializeObject(object objObject, Type objType) + private static string GetPrimaryKey(Type objType) { - // initialize properties - foreach (PropertyInfo objPropertyInfo in GetObjectMapping(objType).Properties.Values) + string primaryKey = defaultPrimaryKey; + return primaryKey; + } + + private static string GetTableName(Type objType) + { + string tableName = string.Empty; + + // If no attrubute then use Type Name + if (string.IsNullOrEmpty(tableName)) { - if (objPropertyInfo.CanWrite) + tableName = objType.Name; + if (tableName.EndsWith("Info")) { - objPropertyInfo.SetValue(objObject, Null.SetNull(objPropertyInfo), null); + // Remove Info ending + tableName.Replace("Info", string.Empty); } } - - return objObject; - } - - /// ----------------------------------------------------------------------------- - /// - /// SerializeObject serializes an Object. - /// - /// The object to Initialise. - /// A filename for the resulting serialized xml. - /// ----------------------------------------------------------------------------- - public static void SerializeObject(object objObject, string fileName) - { - using ( - XmlWriter writer = XmlWriter.Create(fileName, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - SerializeObject(objObject, writer); - writer.Flush(); - } - } - /// ----------------------------------------------------------------------------- - /// - /// SerializeObject serializes an Object. - /// - /// The object to Initialise. - /// An XmlDocument to serialize to. - /// ----------------------------------------------------------------------------- - public static void SerializeObject(object objObject, XmlDocument document) - { - var sb = new StringBuilder(); - using (var writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Document))) + // Check if there is an object qualifier + if (!string.IsNullOrEmpty(Config.GetSetting("ObjectQualifier"))) { - // Serialize the object - SerializeObject(objObject, writer); - - // Load XmlDocument - document.LoadXml(sb.ToString()); + tableName = Config.GetSetting("ObjectQualifier") + tableName; } + + return tableName; } - /// ----------------------------------------------------------------------------- - /// - /// SerializeObject serializes an Object. - /// - /// The object to Initialise. - /// A Stream to serialize to. - /// ----------------------------------------------------------------------------- - public static void SerializeObject(object objObject, Stream stream) + List ICBO.FillCollection(IDataReader dr) { - using (XmlWriter writer = XmlWriter.Create(stream, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - SerializeObject(objObject, writer); - writer.Flush(); - } + return (List)FillListFromReader(dr, new List(), true); } - /// ----------------------------------------------------------------------------- - /// - /// SerializeObject serializes an Object. - /// - /// The object to Initialise. - /// A TextWriter to serialize to. - /// ----------------------------------------------------------------------------- - public static void SerializeObject(object objObject, TextWriter textWriter) + TObject ICBO.FillObject(IDataReader dr) { - using ( - XmlWriter writer = XmlWriter.Create(textWriter, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - SerializeObject(objObject, writer); - writer.Flush(); - } + return (TObject)CreateObjectFromReader(typeof(TObject), dr, true); } - /// ----------------------------------------------------------------------------- - /// - /// SerializeObject serializes an Object. - /// - /// The object to Initialise. - /// An XmlWriter to serialize to. - /// ----------------------------------------------------------------------------- - public static void SerializeObject(object objObject, XmlWriter writer) + TObject ICBO.GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary) { - // Try to cast the Object as IXmlSerializable - var xmlSerializableObject = objObject as IXmlSerializable; - if (xmlSerializableObject == null) - { - // Use XmlSerializer - var serializer = new XmlSerializer(objObject.GetType()); - serializer.Serialize(writer, objObject); - } - else - { - // Use XmlWriter - xmlSerializableObject.WriteXml(writer); - } - } + return DataCache.GetCachedData(cacheItemArgs, cacheItemExpired, saveInDictionary); + } } } diff --git a/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs b/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs index fa70065a2dd..6a88c5eda1e 100644 --- a/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs +++ b/DNN Platform/Library/Common/Utilities/CacheItemArgs.cs @@ -20,10 +20,10 @@ namespace DotNetNuke.Common.Utilities /// ----------------------------------------------------------------------------- public class CacheItemArgs { - private ArrayList _paramList; - + private ArrayList _paramList; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CacheItemArgs Object. /// @@ -32,10 +32,10 @@ public class CacheItemArgs public CacheItemArgs(string key) : this(key, 20, CacheItemPriority.Default, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CacheItemArgs Object. /// @@ -45,10 +45,10 @@ public CacheItemArgs(string key) public CacheItemArgs(string key, int timeout) : this(key, timeout, CacheItemPriority.Default, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CacheItemArgs Object. /// @@ -58,10 +58,10 @@ public CacheItemArgs(string key, int timeout) public CacheItemArgs(string key, CacheItemPriority priority) : this(key, 20, priority, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CacheItemArgs Object. /// @@ -72,10 +72,10 @@ public CacheItemArgs(string key, CacheItemPriority priority) public CacheItemArgs(string key, int timeout, CacheItemPriority priority) : this(key, timeout, priority, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CacheItemArgs Object. /// @@ -92,6 +92,33 @@ public CacheItemArgs(string key, int timeout, CacheItemPriority priority, params this.Params = parameters; } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Cache Item's Parameter List. + /// + /// ----------------------------------------------------------------------------- + public ArrayList ParamList + { + get + { + if (this._paramList == null) + { + this._paramList = new ArrayList(); + + // add additional params to this list if its not null + if (this.Params != null) + { + foreach (object param in this.Params) + { + this._paramList.Add(param); + } + } + } + + return this._paramList; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Cache Item's CacheItemRemovedCallback delegate. @@ -129,33 +156,6 @@ public CacheItemArgs(string key, int timeout, CacheItemPriority priority, params /// ----------------------------------------------------------------------------- public int CacheTimeOut { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Cache Item's Parameter List. - /// - /// ----------------------------------------------------------------------------- - public ArrayList ParamList - { - get - { - if (this._paramList == null) - { - this._paramList = new ArrayList(); - - // add additional params to this list if its not null - if (this.Params != null) - { - foreach (object param in this.Params) - { - this._paramList.Add(param); - } - } - } - - return this._paramList; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the Cache Item's Parameter Array. diff --git a/DNN Platform/Library/Common/Utilities/Calendar.cs b/DNN Platform/Library/Common/Utilities/Calendar.cs index 21a1078c628..b26e124c025 100644 --- a/DNN Platform/Library/Common/Utilities/Calendar.cs +++ b/DNN Platform/Library/Common/Utilities/Calendar.cs @@ -26,7 +26,7 @@ public static string InvokePopupCal(TextBox Field) { // Define character array to trim from language strings char[] TrimChars = { ',', ' ' }; - + // Get culture array of month names and convert to string for // passing to the popup calendar var monthBuilder = new StringBuilder(); @@ -34,9 +34,9 @@ public static string InvokePopupCal(TextBox Field) { monthBuilder.AppendFormat("{0},", Month); } - + var MonthNameString = monthBuilder.ToString().TrimEnd(TrimChars); - + // Get culture array of day names and convert to string for // passing to the popup calendar var dayBuilder = new StringBuilder(); @@ -44,16 +44,16 @@ public static string InvokePopupCal(TextBox Field) { dayBuilder.AppendFormat("{0},", Day); } - + var DayNameString = dayBuilder.ToString().TrimEnd(TrimChars); - + // Get the short date pattern for the culture string FormatString = DateTimeFormatInfo.CurrentInfo.ShortDatePattern; if (!Field.Page.ClientScript.IsClientScriptIncludeRegistered("PopupCalendar.js")) { ScriptManager.RegisterClientScriptInclude(Field.Page, Field.Page.GetType(), "PopupCalendar.js", ClientAPI.ScriptPath + "PopupCalendar.js"); } - + string strToday = ClientAPI.GetSafeJSString(Localization.GetString("Today")); string strClose = ClientAPI.GetSafeJSString(Localization.GetString("Close")); string strCalendar = ClientAPI.GetSafeJSString(Localization.GetString("Calendar")); diff --git a/DNN Platform/Library/Common/Utilities/Config.cs b/DNN Platform/Library/Common/Utilities/Config.cs index 26235644079..37c7b11c392 100644 --- a/DNN Platform/Library/Common/Utilities/Config.cs +++ b/DNN Platform/Library/Common/Utilities/Config.cs @@ -26,27 +26,27 @@ namespace DotNetNuke.Common.Utilities /// ----------------------------------------------------------------------------- public class Config { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Config)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Config)); + public enum ConfigFileType { DotNetNuke, - + // compatible with glbDotNetNukeConfig SiteAnalytics, Compression, SiteUrls, SolutionsExplorer, - } - + } + public enum FcnMode { Default, Disabled, NotSet, Single, - } - + } + /// /// Adds a new AppSetting to Web.Config. The update parameter allows you to define if, /// when the key already exists, this need to be updated or not. @@ -63,7 +63,7 @@ public static XmlDocument AddAppSetting(XmlDocument xmlDoc, string key, string v if (xmlAppSettings != null) { XmlElement xmlElement; - + // get the node based on key XmlNode xmlNode = xmlAppSettings.SelectSingleNode("//add[@key='" + key + "']"); if (update && xmlNode != null) @@ -81,7 +81,7 @@ public static XmlDocument AddAppSetting(XmlDocument xmlDoc, string key, string v xmlAppSettings.AppendChild(xmlElement); } } - + // return the xml doc return xmlDoc; } @@ -107,7 +107,7 @@ public static void AddCodeSubDirectory(string name) // Try location node xmlCompilation = xmlConfig.SelectSingleNode("configuration/location/system.web/compilation"); } - + // Get the CodeSubDirectories Node if (xmlCompilation != null) { @@ -136,14 +136,14 @@ public static void AddCodeSubDirectory(string name) xmlSubDirectories.AppendChild(xmlSubDirectory); } } - + Save(xmlConfig); } public static void BackupConfig() { string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); - + // save the current config files try { @@ -151,7 +151,7 @@ public static void BackupConfig() { Directory.CreateDirectory(Globals.ApplicationMapPath + backupFolder); } - + if (File.Exists(Globals.ApplicationMapPath + "\\web.config")) { File.Copy(Globals.ApplicationMapPath + "\\web.config", Globals.ApplicationMapPath + backupFolder + "web_old.config", true); @@ -186,7 +186,7 @@ public static string GetConnectionString() public static string GetConnectionString(string name) { string connectionString = string.Empty; - + // First check if connection string is specified in (ASP.NET 2.0 / DNN v4.x) if (!string.IsNullOrEmpty(name)) { @@ -194,7 +194,7 @@ public static string GetConnectionString(string name) // This will be for new v4.x installs or upgrades from v4.x connectionString = WebConfigurationManager.ConnectionStrings[name].ConnectionString; } - + if (string.IsNullOrEmpty(connectionString)) { if (!string.IsNullOrEmpty(name)) @@ -204,7 +204,7 @@ public static string GetConnectionString(string name) connectionString = GetSetting(name); } } - + return connectionString; } @@ -291,7 +291,7 @@ public static long GetRequestFilterSize() var maxAllowedContentLength = XmlUtils.GetAttributeValueAsLong(httpNode.CreateNavigator(), "maxAllowedContentLength", 30000000); return maxAllowedContentLength / 1024 / 1024; } - + return defaultRequestFilter; } @@ -302,9 +302,9 @@ public static long GetRequestFilterSize() /// ----------------------------------------------------------------------------- public static void SetMaxUploadSize(long newSize) { - if (newSize < 12582912) - { - newSize = 12582912; + if (newSize < 12582912) + { + newSize = 12582912; } // 12 Mb minimum var configNav = Load(); @@ -353,19 +353,14 @@ public static string GetDataBaseOwner() { databaseOwner += "."; } - - return databaseOwner; - } - private static bool Iis7AndAbove() - { - return Environment.OSVersion.Version.Major >= 6; + return databaseOwner; } public static Provider GetDefaultProvider(string type) { ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(type); - + // Read the configuration specific information for this provider return (Provider)providerConfiguration.Providers[providerConfiguration.DefaultProvider]; } @@ -420,18 +415,18 @@ public static string GetObjectQualifer() { objectQualifier += "_"; } - + return objectQualifier; } public static int GetAuthCookieTimeout() { XPathNavigator configNav = Load().CreateNavigator(); - + // Select the location node XPathNavigator locationNav = configNav.SelectSingleNode("configuration/location"); XPathNavigator formsNav; - + // Test for the existence of the location node if it exists then include that in the nodes of the XPath Query if (locationNav == null) { @@ -441,7 +436,7 @@ public static int GetAuthCookieTimeout() { formsNav = configNav.SelectSingleNode("configuration/location/system.web/authentication/forms"); } - + return (formsNav != null) ? XmlUtils.GetAttributeValueAsInteger(formsNav, "timeout", 30) : 30; } @@ -466,7 +461,7 @@ public static int GetPersistentCookieTimeout() public static Provider GetProvider(string type, string name) { ProviderConfiguration providerConfiguration = ProviderConfiguration.GetProviderConfiguration(type); - + // Read the configuration specific information for this provider return (Provider)providerConfiguration.Providers[name]; } @@ -503,7 +498,7 @@ public static XmlDocument Load() public static string GetCustomErrorMode() { XPathNavigator configNav = Load().CreateNavigator(); - + // Select the location node var customErrorsNav = configNav.SelectSingleNode("//configuration/system.web/customErrors|//configuration/location/system.web/customErrors"); @@ -512,7 +507,7 @@ public static string GetCustomErrorMode() { customErrorMode = "RemoteOnly"; } - + return (customErrorsNav != null) ? customErrorMode : "RemoteOnly"; } @@ -521,7 +516,7 @@ public static XmlDocument Load(string filename) // open the config file var xmlDoc = new XmlDocument { XmlResolver = null }; xmlDoc.Load(Globals.ApplicationMapPath + "\\" + filename); - + // test for namespace added by Web Admin Tool if (!string.IsNullOrEmpty(xmlDoc.DocumentElement.GetAttribute("xmlns"))) { @@ -529,14 +524,14 @@ public static XmlDocument Load(string filename) string strDoc = xmlDoc.InnerXml.Replace("xmlns=\"http://schemas.microsoft.com/.NetConfiguration/v2.0\"", string.Empty); xmlDoc.LoadXml(strDoc); } - + return xmlDoc; } public static void RemoveCodeSubDirectory(string name) { XmlDocument xmlConfig = Load(); - + // Select the location node XmlNode xmlCompilation = xmlConfig.SelectSingleNode("configuration/system.web/compilation"); if (xmlCompilation == null) @@ -544,7 +539,7 @@ public static void RemoveCodeSubDirectory(string name) // Try location node xmlCompilation = xmlConfig.SelectSingleNode("configuration/location/system.web/compilation"); } - + // Get the CodeSubDirectories Node XmlNode xmlSubDirectories = xmlCompilation.SelectSingleNode("codeSubDirectories"); if (xmlSubDirectories == null) @@ -587,7 +582,7 @@ public static string Save(XmlDocument xmlDoc, string filename) { // save current file attributes objFileAttributes = File.GetAttributes(strFilePath); - + // change to normal ( in case it is flagged as read-only ) File.SetAttributes(strFilePath, FileAttributes.Normal); } @@ -608,7 +603,7 @@ public static string Save(XmlDocument xmlDoc, string filename) writer.Flush(); writer.Close(); } - + break; } catch (IOException exc) @@ -785,7 +780,7 @@ public static XmlDocument UpdateValidationKey(XmlDocument xmlConfig) string validationKey = objSecurity.CreateKey(20); XmlUtils.UpdateAttribute(xmlMachineKey, "validationKey", validationKey); } - + return xmlConfig; } @@ -843,7 +838,7 @@ public static string UpdateInstallVersion(Version version) // we need to add the InstallVersion string backupFolder = string.Concat(Globals.glbConfigFolder, "Backup_", DateTime.Now.ToString("yyyyMMddHHmm"), "\\"); var xmlConfig = new XmlDocument { XmlResolver = null }; - + // save the current config files BackupConfig(); try @@ -899,10 +894,15 @@ public static string AddFCNMode(FcnMode fcnMode) // in case of error installation shouldn't be stopped, log into log4net Logger.Error(ex); } - + return string.Empty; } + private static bool Iis7AndAbove() + { + return Environment.OSVersion.Version.Major >= 6; + } + private static string EnumToFileName(ConfigFileType file) { switch (file) diff --git a/DNN Platform/Library/Common/Utilities/DataCache.cs b/DNN Platform/Library/Common/Utilities/DataCache.cs index c0ce514ecd0..d6bf115449c 100644 --- a/DNN Platform/Library/Common/Utilities/DataCache.cs +++ b/DNN Platform/Library/Common/Utilities/DataCache.cs @@ -41,8 +41,6 @@ public class 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; @@ -303,12 +301,12 @@ public class DataCache 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}"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataCache)); + private static readonly ReaderWriterLockSlim dictionaryLock = new ReaderWriterLockSlim(); private static readonly Dictionary lockDictionary = new Dictionary(); @@ -316,6 +314,8 @@ public class DataCache private static readonly TimeSpan _5seconds = new TimeSpan(0, 0, 5); + private static string _CachePersistenceEnabled = string.Empty; + public static bool CachePersistenceEnabled { get @@ -324,7 +324,7 @@ public static bool CachePersistenceEnabled { _CachePersistenceEnabled = Config.GetSetting("EnableCachePersistence") ?? "false"; } - + return bool.Parse(_CachePersistenceEnabled); } } @@ -348,51 +348,6 @@ public static void ClearCache(string cachePrefix) CachingProvider.Instance().Clear("Prefix", GetDnnCacheKey(cachePrefix)); } - internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) - { - // if the item was removed from the cache, log the key and reason to the event log - try - { - if (Globals.Status == Globals.UpgradeStatus.None) - { - var log = new LogInfo(); - switch (removedReason) - { - case CacheItemRemovedReason.Removed: - log.LogTypeKey = EventLogController.EventLogType.CACHE_REMOVED.ToString(); - break; - case CacheItemRemovedReason.Expired: - log.LogTypeKey = EventLogController.EventLogType.CACHE_EXPIRED.ToString(); - break; - case CacheItemRemovedReason.Underused: - log.LogTypeKey = EventLogController.EventLogType.CACHE_UNDERUSED.ToString(); - break; - case CacheItemRemovedReason.DependencyChanged: - log.LogTypeKey = EventLogController.EventLogType.CACHE_DEPENDENCYCHANGED.ToString(); - break; - } - - log.LogProperties.Add(new LogDetailInfo(key, removedReason.ToString())); - LogController.Instance.AddLog(log); - } - } - catch (Exception exc) - { - // Swallow exception - Logger.Error(exc); - } - } - - private static string GetDnnCacheKey(string CacheKey) - { - return CachingProvider.GetCacheKey(CacheKey); - } - - private static string CleanCacheKey(string cacheKey) - { - return CachingProvider.CleanCacheKey(cacheKey); - } - public static void ClearFolderCache(int PortalId) { CachingProvider.Instance().Clear("Folder", PortalId.ToString()); @@ -459,7 +414,7 @@ public static void ClearDesktopModulePermissionsCache() public static void ClearFolderPermissionsCache(int PortalId) { - PermissionProvider.ResetCacheDependency( + PermissionProvider.ResetCacheDependency( PortalId, () => RemoveCache(string.Format(FolderPermissionCacheKey, PortalId))); } @@ -513,7 +468,7 @@ public static TObject GetCache(string CacheKey) { return default(TObject); } - + return (TObject)objObject; } @@ -522,6 +477,94 @@ public static object GetCache(string CacheKey) return CachingProvider.Instance().GetItem(GetDnnCacheKey(CacheKey)); } + public static void RemoveCache(string CacheKey) + { + CachingProvider.Instance().Remove(GetDnnCacheKey(CacheKey)); + } + + public static void RemoveFromPrivateDictionary(string DnnCacheKey) + { + using (dictionaryCache.GetWriteLock()) + { + dictionaryCache.Remove(CleanCacheKey(DnnCacheKey)); + } + } + + public static void SetCache(string CacheKey, object objObject) + { + SetCache(CacheKey, objObject, (DNNCacheDependency)null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); + } + + public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency) + { + SetCache(CacheKey, objObject, objDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); + } + + public static void SetCache(string CacheKey, object objObject, DateTime AbsoluteExpiration) + { + SetCache(CacheKey, objObject, (DNNCacheDependency)null, AbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); + } + + public static void SetCache(string CacheKey, object objObject, TimeSpan SlidingExpiration) + { + SetCache(CacheKey, objObject, (DNNCacheDependency)null, Cache.NoAbsoluteExpiration, SlidingExpiration, CacheItemPriority.Normal, null); + } + + public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration) + { + SetCache(CacheKey, objObject, objDependency, AbsoluteExpiration, SlidingExpiration, CacheItemPriority.Normal, null); + } + + public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority, + CacheItemRemovedCallback OnRemoveCallback) + { + if (objObject != null) + { + // if no OnRemoveCallback value is specified, use the default method + if (OnRemoveCallback == null) + { + OnRemoveCallback = ItemRemovedCallback; + } + + CachingProvider.Instance().Insert(GetDnnCacheKey(CacheKey), objObject, objDependency, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback); + } + } + + internal static void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) + { + // if the item was removed from the cache, log the key and reason to the event log + try + { + if (Globals.Status == Globals.UpgradeStatus.None) + { + var log = new LogInfo(); + switch (removedReason) + { + case CacheItemRemovedReason.Removed: + log.LogTypeKey = EventLogController.EventLogType.CACHE_REMOVED.ToString(); + break; + case CacheItemRemovedReason.Expired: + log.LogTypeKey = EventLogController.EventLogType.CACHE_EXPIRED.ToString(); + break; + case CacheItemRemovedReason.Underused: + log.LogTypeKey = EventLogController.EventLogType.CACHE_UNDERUSED.ToString(); + break; + case CacheItemRemovedReason.DependencyChanged: + log.LogTypeKey = EventLogController.EventLogType.CACHE_DEPENDENCYCHANGED.ToString(); + break; + } + + log.LogProperties.Add(new LogDetailInfo(key, removedReason.ToString())); + LogController.Instance.AddLog(log); + } + } + catch (Exception exc) + { + // Swallow exception + Logger.Error(exc); + } + } + internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool storeInDictionary) { object objObject = storeInDictionary @@ -533,10 +576,20 @@ internal static TObject GetCachedData(CacheItemArgs cacheItemArgs, Cach { return default(TObject); } - + return (TObject)objObject; } + private static string GetDnnCacheKey(string CacheKey) + { + return CachingProvider.GetCacheKey(CacheKey); + } + + private static string CleanCacheKey(string cacheKey) + { + return CachingProvider.CleanCacheKey(cacheKey); + } + private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired) { object objObject = GetCache(cacheItemArgs.CacheKey); @@ -574,7 +627,7 @@ private static object GetCachedDataFromRuntimeCache(CacheItemArgs cacheItemArgs, if (objObject != null && timeOut > 0) { // save the object in the cache - SetCache( + SetCache( cacheItemArgs.CacheKey, objObject, cacheItemArgs.CacheDependency, @@ -658,7 +711,7 @@ private static object GetUniqueLockObject(string key) dictionaryLock.ExitReadLock(); } } - + if (@lock == null) { if (dictionaryLock.TryEnterWriteLock(_5seconds)) @@ -671,7 +724,7 @@ private static object GetUniqueLockObject(string key) // Create new lock lockDictionary[key] = new object(); } - + // Retrieve lock @lock = lockDictionary[key]; } @@ -681,17 +734,17 @@ private static object GetUniqueLockObject(string key) } } } - + return @lock; } private static void RemoveUniqueLockObject(string key) { - if (!dictionaryLock.TryEnterWriteLock(_5seconds)) - { - return; - } - + if (!dictionaryLock.TryEnterWriteLock(_5seconds)) + { + return; + } + try { // check dictionary @@ -706,58 +759,5 @@ private static void RemoveUniqueLockObject(string key) dictionaryLock.ExitWriteLock(); } } - - public static void RemoveCache(string CacheKey) - { - CachingProvider.Instance().Remove(GetDnnCacheKey(CacheKey)); - } - - public static void RemoveFromPrivateDictionary(string DnnCacheKey) - { - using (dictionaryCache.GetWriteLock()) - { - dictionaryCache.Remove(CleanCacheKey(DnnCacheKey)); - } - } - - public static void SetCache(string CacheKey, object objObject) - { - SetCache(CacheKey, objObject, (DNNCacheDependency)null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); - } - - public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency) - { - SetCache(CacheKey, objObject, objDependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); - } - - public static void SetCache(string CacheKey, object objObject, DateTime AbsoluteExpiration) - { - SetCache(CacheKey, objObject, (DNNCacheDependency)null, AbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); - } - - public static void SetCache(string CacheKey, object objObject, TimeSpan SlidingExpiration) - { - SetCache(CacheKey, objObject, (DNNCacheDependency)null, Cache.NoAbsoluteExpiration, SlidingExpiration, CacheItemPriority.Normal, null); - } - - public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration) - { - SetCache(CacheKey, objObject, objDependency, AbsoluteExpiration, SlidingExpiration, CacheItemPriority.Normal, null); - } - - public static void SetCache(string CacheKey, object objObject, DNNCacheDependency objDependency, DateTime AbsoluteExpiration, TimeSpan SlidingExpiration, CacheItemPriority Priority, - CacheItemRemovedCallback OnRemoveCallback) - { - if (objObject != null) - { - // if no OnRemoveCallback value is specified, use the default method - if (OnRemoveCallback == null) - { - OnRemoveCallback = ItemRemovedCallback; - } - - CachingProvider.Instance().Insert(GetDnnCacheKey(CacheKey), objObject, objDependency, AbsoluteExpiration, SlidingExpiration, Priority, OnRemoveCallback); - } - } } } diff --git a/DNN Platform/Library/Common/Utilities/DateUtils.cs b/DNN Platform/Library/Common/Utilities/DateUtils.cs index 5ac236f9e66..535415140ea 100644 --- a/DNN Platform/Library/Common/Utilities/DateUtils.cs +++ b/DNN Platform/Library/Common/Utilities/DateUtils.cs @@ -89,7 +89,7 @@ public static DateTime GetDatabaseLocalTime() return DateTime.Now + _driftLocal; } - + /// /// Returns a string with the pretty printed amount of time since the specified date. /// diff --git a/DNN Platform/Library/Common/Utilities/EnumExtensions.cs b/DNN Platform/Library/Common/Utilities/EnumExtensions.cs index bfea083e577..0990e1036c6 100644 --- a/DNN Platform/Library/Common/Utilities/EnumExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/EnumExtensions.cs @@ -26,7 +26,7 @@ public static List> ToKeyValuePairs(this Enum enumType { pairs.Add(new KeyValuePair((int)values.GetValue(i), names[i])); } - + return pairs; } } diff --git a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs index 8f9a8f273c5..059e81cfa60 100644 --- a/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs +++ b/DNN Platform/Library/Common/Utilities/FileExtensionWhitelist.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.Common.Utilities public class FileExtensionWhitelist { - private readonly List _extensions; - - /// + private readonly List _extensions; + + /// /// Initializes a new instance of the class. /// /// a comma seperated list of file extensions with no '.'. diff --git a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs index c87526d905d..caa80180818 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemPermissionVerifier.cs @@ -27,7 +27,7 @@ public FileSystemPermissionVerifier(string basePath) this._basePath = basePath; } - public FileSystemPermissionVerifier(string basePath, int retryTimes) + public FileSystemPermissionVerifier(string basePath, int retryTimes) : this(basePath) { this._retryTimes = retryTimes; diff --git a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs index a92dad9ba10..e5a7a890949 100644 --- a/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs +++ b/DNN Platform/Library/Common/Utilities/FileSystemUtils.cs @@ -33,8 +33,8 @@ namespace DotNetNuke.Common.Utilities public class FileSystemUtils { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSystemUtils)); + /// ----------------------------------------------------------------------------- /// /// Adds a File to a Zip File. @@ -54,7 +54,7 @@ public static void AddToZip(ref ZipOutputStream ZipFile, string filePath, string var len = fs.Read(buffer, 0, buffer.Length); if (len != fs.Length) { - Logger.ErrorFormat( + 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); } @@ -92,139 +92,10 @@ public static void CopyFile(string sourceFileName, string 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; - var fileManager = FileManager.Instance; - - try - { - var file = fileManager.AddFile(folder, fileName, fileContent, overwrite, checkPermissions, contentType); - if (unzip && file.Extension == "zip") - { - fileManager.UnzipFile(file, folder); - } - } - catch (PermissionsNotMetException) - { - strMessage += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); - } - catch (NoSpaceAvailableException) - { - strMessage += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); - } - catch (InvalidFileExtensionException) - { - strMessage += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - } - catch (Exception ex) - { - Logger.Error(ex); - strMessage += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); - } - - return strMessage; - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the filename for a file path. - /// - /// The full name of the file. - /// ----------------------------------------------------------------------------- - private static string GetFileName(string filePath) - { - return Path.GetFileName(filePath).Replace(Globals.glbProtectedExtension, string.Empty); - } - - private static int GetFolderPortalID(PortalSettings settings) - { - return (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; - } - - private static void RemoveOrphanedFiles(FolderInfo folder, int PortalId) - { - if (folder.FolderMappingID != FolderMappingController.Instance.GetFolderMapping(PortalId, "Database").FolderMappingID) - { - foreach (FileInfo objFile in FolderManager.Instance.GetFiles(folder)) - { - RemoveOrphanedFile(objFile, PortalId); - } - } - } - - private static void RemoveOrphanedFile(FileInfo objFile, int PortalId) - { - FileManager.Instance.DeleteFile(objFile); + File.Copy(sourceFileName, destFileName, true); } - /// ----------------------------------------------------------------------------- - /// - /// Writes a Stream to the appropriate File Storage. - /// - /// The Id of the File. - /// The Input Stream. - /// - /// - /// ----------------------------------------------------------------------------- - private static void WriteStream(HttpResponse objResponse, Stream objStream) - { - // Buffer to read 10K bytes in chunk: - var bytBuffer = new byte[10000]; - - // Length of the file: - int intLength; - - // Total bytes to read: - long lngDataToRead; - try - { - // Total bytes to read: - lngDataToRead = objStream.Length; - - // Read the bytes. - while (lngDataToRead > 0) - { - // Verify that the client is connected. - if (objResponse.IsClientConnected) - { - // Read the data in buffer - intLength = objStream.Read(bytBuffer, 0, 10000); - - // Write the data to the current output stream. - objResponse.OutputStream.Write(bytBuffer, 0, intLength); - - // Flush the data to the HTML output. - objResponse.Flush(); - - lngDataToRead = lngDataToRead - intLength; - } - else - { - lngDataToRead = -1; - } - } - } - catch (Exception ex) - { - Logger.Error(ex); - objResponse.Write("Error : " + ex.Message); - } - finally - { - if (objStream != null) - { - objStream.Close(); - objStream.Dispose(); - } - } - } - /// ----------------------------------------------------------------------------- /// /// Deletes file in areas with a high degree of concurrent file access (i.e. caching, logging) @@ -244,7 +115,7 @@ public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, { return true; } - + bool fileDeleted = false; int i = 0; while (fileDeleted != true) @@ -253,7 +124,7 @@ public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, { break; } - + i = i + 1; try { @@ -261,7 +132,7 @@ public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, { File.Delete(fileName); } - + fileDeleted = true; // we don't care if it didn't exist...the operation didn't fail, that's what we care about } catch (Exception exc) @@ -269,13 +140,13 @@ public static bool DeleteFileWithWait(string fileName, short waitInMilliseconds, Logger.Error(exc); fileDeleted = false; } - + if (fileDeleted == false) { Thread.Sleep(waitInMilliseconds); } } - + return fileDeleted; } @@ -312,7 +183,7 @@ public static string ReadFile(string filePath) reader.Dispose(); } } - + return fileContent; } @@ -331,7 +202,7 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) { Directory.Create(Path.Combine(destPath, relativeDir), true); } - + if (!zipEntry.IsDirectory && (!string.IsNullOrEmpty(localFileName))) { var fileNamePath = FixPath(Path.Combine(destPath, localFileName)); @@ -342,7 +213,7 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) File.SetAttributes(fileNamePath, FileAttributes.Normal); File.Delete(fileNamePath); } - + FileStream objFileStream = null; try { @@ -371,7 +242,7 @@ public static void UnzipResources(ZipInputStream zipStream, string destPath) Logger.Error(ex); } } - + zipEntry = zipStream.GetNextEntry(); } } @@ -438,7 +309,7 @@ public static string DeleteFiles(Array arrPaths) } } } - + return strExceptions; } @@ -457,7 +328,7 @@ public static void DeleteFilesRecursive(string strRoot, string filter) DeleteFilesRecursive(strFolder, filter); } } - + foreach (string strFile in Directory.EnumerateFilePaths(strRoot).Where(f => f.Contains(filter))) { try @@ -477,7 +348,7 @@ public static void DeleteFolderRecursive(string strRoot) { strRoot = FixPath(strRoot); if (string.IsNullOrEmpty(strRoot) || !Directory.Exists(strRoot)) - { + { Logger.Info(strRoot + " does not exist. "); return; } @@ -521,5 +392,134 @@ public static string FixPath(string input) return input.Trim().Replace("/", "\\"); } + + private static string CreateFile(IFolderInfo folder, string fileName, string contentType, Stream fileContent, bool unzip, bool overwrite, bool checkPermissions) + { + var strMessage = string.Empty; + var fileManager = FileManager.Instance; + + try + { + var file = fileManager.AddFile(folder, fileName, fileContent, overwrite, checkPermissions, contentType); + if (unzip && file.Extension == "zip") + { + fileManager.UnzipFile(file, folder); + } + } + catch (PermissionsNotMetException) + { + strMessage += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); + } + catch (NoSpaceAvailableException) + { + strMessage += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + } + catch (InvalidFileExtensionException) + { + strMessage += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + } + catch (Exception ex) + { + Logger.Error(ex); + + strMessage += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); + } + + return strMessage; + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the filename for a file path. + /// + /// The full name of the file. + /// ----------------------------------------------------------------------------- + private static string GetFileName(string filePath) + { + return Path.GetFileName(filePath).Replace(Globals.glbProtectedExtension, string.Empty); + } + + private static int GetFolderPortalID(PortalSettings settings) + { + return (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; + } + + private static void RemoveOrphanedFiles(FolderInfo folder, int PortalId) + { + if (folder.FolderMappingID != FolderMappingController.Instance.GetFolderMapping(PortalId, "Database").FolderMappingID) + { + foreach (FileInfo objFile in FolderManager.Instance.GetFiles(folder)) + { + RemoveOrphanedFile(objFile, PortalId); + } + } + } + + private static void RemoveOrphanedFile(FileInfo objFile, int PortalId) + { + FileManager.Instance.DeleteFile(objFile); + } + + /// ----------------------------------------------------------------------------- + /// + /// Writes a Stream to the appropriate File Storage. + /// + /// The Id of the File. + /// The Input Stream. + /// + /// + /// ----------------------------------------------------------------------------- + private static void WriteStream(HttpResponse objResponse, Stream objStream) + { + // Buffer to read 10K bytes in chunk: + var bytBuffer = new byte[10000]; + + // Length of the file: + int intLength; + + // Total bytes to read: + long lngDataToRead; + try + { + // Total bytes to read: + lngDataToRead = objStream.Length; + + // Read the bytes. + while (lngDataToRead > 0) + { + // Verify that the client is connected. + if (objResponse.IsClientConnected) + { + // Read the data in buffer + intLength = objStream.Read(bytBuffer, 0, 10000); + + // Write the data to the current output stream. + objResponse.OutputStream.Write(bytBuffer, 0, intLength); + + // Flush the data to the HTML output. + objResponse.Flush(); + + lngDataToRead = lngDataToRead - intLength; + } + else + { + lngDataToRead = -1; + } + } + } + catch (Exception ex) + { + Logger.Error(ex); + objResponse.Write("Error : " + ex.Message); + } + finally + { + if (objStream != null) + { + objStream.Close(); + objStream.Dispose(); + } + } + } } } diff --git a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs index 66214a1ea8e..82bbd6f817a 100644 --- a/DNN Platform/Library/Common/Utilities/HtmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/HtmlUtils.cs @@ -27,7 +27,7 @@ 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); @@ -76,7 +76,7 @@ public static string Clean(string HTML, bool RemovePunctuation) if (RemovePunctuation) { HTML = StripPunctuation(HTML, true); - + // When RemovePunctuation is false, HtmlDecode() would have already had removed these // Finally remove extra whitespace HTML = StripWhiteSpace(HTML, true); @@ -120,7 +120,7 @@ public static string CleanWithTagInfo(string html, string tagsFilter, bool remov return html; } - + /// ----------------------------------------------------------------------------- /// /// Formats an Email address. @@ -155,12 +155,12 @@ public static string FormatEmail(string Email, bool cloak) formatEmail = Email; } } - + if (cloak) { formatEmail = Globals.CloakText(formatEmail); } - + return formatEmail; } @@ -178,7 +178,7 @@ public static string FormatText(string HTML, bool RetainSpace) { return ReplaceHtmlNewLinesRegex.Replace(HTML, Environment.NewLine); } - + /// ----------------------------------------------------------------------------- /// /// Formats String as Html by replacing linefeeds by.
    @@ -224,7 +224,7 @@ public static string ConvertToText(string strHtml) // Replace all variants of
    by Linefeeds strText = FormatText(strText, false); } - + return strText; } @@ -253,7 +253,7 @@ public static string FormatWebsite(object Website) } } } - + return formatWebsite; } @@ -292,7 +292,7 @@ public static string Shorten(string txt, int length, string suffix) public static string StripEntities(string HTML, bool RetainSpace) { var repString = RetainSpace ? " " : string.Empty; - + // Replace Entities by replacement String and return mofified string return EntityRegEx.Replace(HTML, repString); } @@ -332,7 +332,7 @@ public static string RemoveInlineStyle(string HTML) { return RemoveInlineStylesRegEx.Replace(HTML, string.Empty); } - + /// ----------------------------------------------------------------------------- /// /// StripTags removes the HTML Tags from the content. @@ -347,7 +347,7 @@ public static string StripTags(string HTML, bool RetainSpace) { return StripTagsRegex.Replace(HTML, RetainSpace ? " " : string.Empty); } - + /// ----------------------------------------------------------------------------- /// /// StripUnspecifiedTags removes the HTML tags from the content -- leaving behind the info @@ -386,7 +386,7 @@ public static string StripUnspecifiedTags(string html, string specifiedTags, boo return result.ToString(); } - + /// ----------------------------------------------------------------------------- /// /// StripPunctuation removes the Punctuation from the content. @@ -413,16 +413,16 @@ public static string StripPunctuation(string HTML, bool RetainSpace) { retHTML = BeforeRegEx.Replace(retHTML, repString); } - + while (AfterRegEx.IsMatch(retHTML)) { retHTML = AfterRegEx.Replace(retHTML, repString); } - + // Return modified string after trimming leading and ending quotation marks return retHTML.Trim('"'); } - + /// ----------------------------------------------------------------------------- /// /// StripWhiteSpace removes the WhiteSpace from the content. @@ -435,11 +435,11 @@ public static string StripPunctuation(string HTML, bool RetainSpace) /// ----------------------------------------------------------------------------- public static string StripWhiteSpace(string HTML, bool RetainSpace) { - if (string.IsNullOrWhiteSpace(HTML)) - { - return Null.NullString; - } - + if (string.IsNullOrWhiteSpace(HTML)) + { + return Null.NullString; + } + return StripWhiteSpaceRegex.Replace(HTML, RetainSpace ? " " : string.Empty); } @@ -455,11 +455,11 @@ public static string StripWhiteSpace(string HTML, bool RetainSpace) /// ----------------------------------------------------------------------------- public static string StripNonWord(string HTML, bool RetainSpace) { - if (string.IsNullOrWhiteSpace(HTML)) - { - return HTML; - } - + if (string.IsNullOrWhiteSpace(HTML)) + { + return HTML; + } + string RepString = RetainSpace ? " " : string.Empty; return StripNonWordRegex.Replace(HTML, RepString); } @@ -543,12 +543,12 @@ public static void WriteFeedback(HttpResponse response, int indent, string messa { strMessage += timeElapsed.ToString().Substring(0, timeElapsed.ToString().LastIndexOf(".", StringComparison.Ordinal) + 4) + " -"; } - + for (int i = 0; i <= indent; i++) { strMessage += " "; } - + strMessage += message; response.Write(strMessage); response.Flush(); @@ -614,13 +614,13 @@ public static void WriteHeader(HttpResponse response, string mode) File.Copy(HttpContext.Current.Server.MapPath("~/Install/Install.template.htm"), HttpContext.Current.Server.MapPath("~/Install/Install.htm")); } } - + // read install page and insert into response stream if (File.Exists(HttpContext.Current.Server.MapPath("~/Install/Install.htm"))) { response.Write(FileSystemUtils.ReadFile(HttpContext.Current.Server.MapPath("~/Install/Install.htm"))); } - + switch (mode) { case "install": @@ -651,7 +651,7 @@ public static void WriteHeader(HttpResponse response, string mode) response.Write("

    " + mode + "

    "); break; } - + response.Flush(); } diff --git a/DNN Platform/Library/Common/Utilities/ICBO.cs b/DNN Platform/Library/Common/Utilities/ICBO.cs index 043ded5ea9a..c9515b59e39 100644 --- a/DNN Platform/Library/Common/Utilities/ICBO.cs +++ b/DNN Platform/Library/Common/Utilities/ICBO.cs @@ -9,11 +9,11 @@ namespace DotNetNuke.Common.Utilities public interface ICBO { - List FillCollection(IDataReader dr) - where TObject : new(); + List FillCollection(IDataReader dr) + where TObject : new(); - TObject FillObject(IDataReader dr) - where TObject : new(); + TObject FillObject(IDataReader dr) + where TObject : new(); // SortedList FillSortedList(string keyField, IDataReader dr); TObject GetCachedObject(CacheItemArgs cacheItemArgs, CacheItemExpiredCallback cacheItemExpired, bool saveInDictionary); diff --git a/DNN Platform/Library/Common/Utilities/IPathUtils.cs b/DNN Platform/Library/Common/Utilities/IPathUtils.cs index 1d4928ddac3..eb670c887ab 100644 --- a/DNN Platform/Library/Common/Utilities/IPathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/IPathUtils.cs @@ -26,19 +26,19 @@ public interface IPathUtils /// /// Gets the physical path for the specified relative path. - /// + ///
    /// string GetPhysicalPath(int portalID, string relativePath); /// /// Gets the relative path for the specified physical path. - /// + ///
    /// string GetRelativePath(int portalID, string physicalPath); /// /// Gets the physical root folder path for the specified portal. - /// + ///
    /// string GetRootFolderMapPath(int portalID); diff --git a/DNN Platform/Library/Common/Utilities/ImageUtils.cs b/DNN Platform/Library/Common/Utilities/ImageUtils.cs index c6b346988c2..a1ce1d40eb3 100644 --- a/DNN Platform/Library/Common/Utilities/ImageUtils.cs +++ b/DNN Platform/Library/Common/Utilities/ImageUtils.cs @@ -148,7 +148,7 @@ public static string CreateImage(string sFile, int intHeight, int intWidth) FileWrapper.Instance.SetAttributes(tmp, FileAttributes.Normal); FileWrapper.Instance.Delete(tmp); } - + return sFile; } @@ -178,16 +178,16 @@ public static Stream CreateImage(Stream stream, int intHeight, int intWidth, str imgWidth = original.Width; } - if (imgWidth < 1) - { - imgWidth = 1; - } - - if (imgHeight < 1) - { - imgHeight = 1; - } - + if (imgWidth < 1) + { + imgWidth = 1; + } + + if (imgHeight < 1) + { + imgHeight = 1; + } + imgSize = new Size(imgWidth, imgHeight); using (var newImg = new Bitmap(imgWidth, imgHeight, format)) @@ -256,7 +256,7 @@ public static string CreateJPG(string sFile, Bitmap img, int compressionLevel) { File.Delete(sFile); } - + try { img.Save(sFile, myImageCodecInfo, myEncoderParameters); @@ -265,7 +265,7 @@ public static string CreateJPG(string sFile, Bitmap img, int compressionLevel) { // suppress unexpected exceptions } - + img.Dispose(); bmpOutput.Dispose(); return sFile; @@ -342,7 +342,7 @@ public static ImageCodecInfo GetEncoderInfo(string myMimeType) return encoders[i]; } } - + return null; } catch diff --git a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs index d2cf665ac6e..ecc6dfa481f 100644 --- a/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs +++ b/DNN Platform/Library/Common/Utilities/JavaScriptObjectDictionary.cs @@ -27,7 +27,7 @@ public static string ToJavaScriptArrayString(IEnumerable methods) { return "null"; } - + var builder = new StringBuilder(); builder.Append('['); var isFirstPair = true; @@ -70,11 +70,11 @@ public static string ToJavaScriptArrayString(IEnumerable methods) { builder.Append(','); } - + var methodValue = string.IsNullOrEmpty(method) ? "null" : method; builder.Append(methodValue); } - + builder.Append(']'); return builder.ToString(); } @@ -94,13 +94,32 @@ public string ToJsonString() return ToJsonString(this); } + public string ToJavaScriptArrayString() + { + return ToJavaScriptArrayString(this); + } + + public IEnumerator> GetEnumerator() + { + var enumerator = this.Dictionary.GetEnumerator(); + while (enumerator.MoveNext()) + { + yield return new KeyValuePair(enumerator.Key.ToString(), enumerator.Value.ToString()); + } + } + + public override string ToString() + { + return this._dictionary == null ? string.Empty : this._dictionary.ToString(); + } + private static string ToJsonString(IEnumerable> methods) { if (methods == null) { return "null"; } - + var builder = new StringBuilder(); builder.Append('{'); var isFirstPair = true; @@ -114,7 +133,7 @@ private static string ToJsonString(IEnumerable> met { builder.Append(','); } - + builder.Append('"'); builder.Append(HttpUtility.JavaScriptStringEncode(keyValuePair.Key)); builder.Append('"'); @@ -122,35 +141,16 @@ private static string ToJsonString(IEnumerable> met var methodValue = string.IsNullOrEmpty(keyValuePair.Value) ? "null" : keyValuePair.Value; builder.Append(methodValue); } - + builder.Append('}'); return builder.ToString(); } - public string ToJavaScriptArrayString() - { - return ToJavaScriptArrayString(this); - } - - public IEnumerator> GetEnumerator() - { - var enumerator = this.Dictionary.GetEnumerator(); - while (enumerator.MoveNext()) - { - yield return new KeyValuePair(enumerator.Key.ToString(), enumerator.Value.ToString()); - } - } - IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumeratorPrivate(); } - 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 d1467856504..9ffcee077f6 100644 --- a/DNN Platform/Library/Common/Utilities/JsonExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/JsonExtensions.cs @@ -34,12 +34,6 @@ 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. @@ -77,5 +71,11 @@ public static TType FromJson(this string json) var result = ser.Deserialize(json); return result; } + + private static JavaScriptSerializer SerializerFactory() + { + // Allow large JSON strings to be serialized and deserialized. + return new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; + } } } diff --git a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs index b4fca6b7458..5e3fd6d05af 100644 --- a/DNN Platform/Library/Common/Utilities/NetworkUtils.cs +++ b/DNN Platform/Library/Common/Utilities/NetworkUtils.cs @@ -42,13 +42,13 @@ public static string GetAddress(string Host, AddressType AddressFormat) addrFamily = AddressFamily.InterNetworkV6; break; } - + IPHostEntry IPE = Dns.GetHostEntry(Host); if (Host != IPE.HostName) { IPE = Dns.GetHostEntry(IPE.HostName); } - + foreach (IPAddress IPA in IPE.AddressList) { if (IPA.AddressFamily == addrFamily) @@ -56,10 +56,10 @@ public static string GetAddress(string Host, AddressType AddressFormat) return IPA.ToString(); } } - + return string.Empty; } - + /// /// Convert IP address to long integer. /// @@ -69,16 +69,16 @@ public static long IPtoLong(IPAddress ip) { // convert IP to number byte[] addressBytes = ip.GetAddressBytes(); - + // get the octets long addr = 0; - + // accumulator for address for (int x = 0; x <= 3; x++) { addr = addr | (Convert.ToInt64(addressBytes[x]) << ((3 - x) * 8)); } - + return addr; } @@ -91,13 +91,13 @@ public static string LongToIp(long ip) { // convert number back to IP var ipByte = new byte[4]; - + // 4 octets string addr = string.Empty; - + // accumulator for address long mask8 = MaskFromCidr(8); - + // create eight bit mask // get the octets @@ -106,10 +106,10 @@ public static string LongToIp(long ip) ipByte[x] = Convert.ToByte((ip & mask8) >> ((3 - x) * 8)); mask8 = mask8 >> 8; addr += ipByte[x].ToString() + "."; - + // add current octet to string } - + return addr.TrimEnd('.'); } @@ -138,15 +138,15 @@ public static string FormatAsCidr(string startIP, string subnetMask) for (int x = 31; x >= 0; x += -1) { - if ((maskL & oneBit) == oneBit) - { - cidr += 1; - } - else - { - break; - } - + if ((maskL & oneBit) == oneBit) + { + cidr += 1; + } + else + { + break; + } + oneBit = oneBit >> 1; } @@ -194,16 +194,6 @@ 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. /// @@ -220,7 +210,7 @@ public static uint IP2Int(string ipNumber) ip += Convert.ToUInt32(elements[2]) << 8; ip += Convert.ToUInt32(elements[3]); } - + return ip; } @@ -242,15 +232,15 @@ public static bool IsIPInRange(string currentIP, string startIP, string subnetma } // handle case where we are matching on a single IP - if (string.IsNullOrEmpty(subnetmask)) - { - if (currentIP == startIP) - { - return true; - } - } - - // handle case where we have to build a CIDR, convert to an IP range and compare + if (string.IsNullOrEmpty(subnetmask)) + { + if (currentIP == startIP) + { + return true; + } + } + + // handle case where we have to build a CIDR, convert to an IP range and compare string cidr = FormatAsCidr(startIP, subnetmask); uint fromIP, toIP; Network2IpRange(cidr, out fromIP, out toIP); @@ -266,7 +256,7 @@ public static bool IsIPInRange(string currentIP, string startIP, string subnetma // catch case where IP cannot be resolved such as when debugger is attached return false; } - + return false; } @@ -287,5 +277,15 @@ public static string GetClientIpAddress(HttpRequest request) return ipAddress; } + + /// + /// 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; + } } } diff --git a/DNN Platform/Library/Common/Utilities/Null.cs b/DNN Platform/Library/Common/Utilities/Null.cs index 32c952fdf3b..3fd6d1a26ba 100644 --- a/DNN Platform/Library/Common/Utilities/Null.cs +++ b/DNN Platform/Library/Common/Utilities/Null.cs @@ -143,7 +143,7 @@ public static object SetNull(object objValue, object objField) { returnValue = objValue; } - + return returnValue; } @@ -198,10 +198,10 @@ public static object SetNull(PropertyInfo objPropertyInfo) { returnValue = null; } - + break; } - + return returnValue; } @@ -236,7 +236,7 @@ public static Guid SetNullGuid(object objValue) { return new Guid(objValue.ToString()); } - + return Guid.Empty; } @@ -326,7 +326,7 @@ public static object GetNull(object objField, object objDBNull) returnValue = objDBNull; } } - + return returnValue; } @@ -386,7 +386,7 @@ public static bool IsNull(object objField) { isNull = true; } - + return isNull; } } diff --git a/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs b/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs index e8a48c76ff7..d74361052b9 100644 --- a/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs +++ b/DNN Platform/Library/Common/Utilities/ObjectMappingInfo.cs @@ -31,10 +31,10 @@ public class ObjectMappingInfo private int _CacheTimeOutMultiplier; private string _ObjectType; private string _PrimaryKey; - private string _TableName; - + private string _TableName; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new ObjectMappingInfo Object. /// @@ -60,11 +60,37 @@ public string CacheKey { _CacheKey += this.CacheByProperty + "_"; } - + return _CacheKey; } } + /// ----------------------------------------------------------------------------- + /// + /// Gets columnNames gets a dictionary of Database Column Names for the Object. + /// + /// ----------------------------------------------------------------------------- + public Dictionary ColumnNames + { + get + { + return this._ColumnNames; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets properties gets a dictionary of Properties for the Object. + /// + /// ----------------------------------------------------------------------------- + public Dictionary Properties + { + get + { + return this._Properties; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets cacheByProperty gets and sets the property that is used to cache collections @@ -79,7 +105,7 @@ public string CacheByProperty { return this._CacheByProperty; } - + set { this._CacheByProperty = value; @@ -100,26 +126,13 @@ public int CacheTimeOutMultiplier { return this._CacheTimeOutMultiplier; } - + set { this._CacheTimeOutMultiplier = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets columnNames gets a dictionary of Database Column Names for the Object. - /// - /// ----------------------------------------------------------------------------- - public Dictionary ColumnNames - { - get - { - return this._ColumnNames; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets objectType gets and sets the type of the object. @@ -131,7 +144,7 @@ public string ObjectType { return this._ObjectType; } - + set { this._ObjectType = value; @@ -150,26 +163,13 @@ public string PrimaryKey { return this._PrimaryKey; } - + set { this._PrimaryKey = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets properties gets a dictionary of Properties for the Object. - /// - /// ----------------------------------------------------------------------------- - public Dictionary Properties - { - get - { - return this._Properties; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets tableName gets and sets the name of the database table that is used to @@ -182,7 +182,7 @@ public string TableName { return this._TableName; } - + set { this._TableName = value; diff --git a/DNN Platform/Library/Common/Utilities/PathUtils.cs b/DNN Platform/Library/Common/Utilities/PathUtils.cs index f7ae64f0b32..89604de5846 100644 --- a/DNN Platform/Library/Common/Utilities/PathUtils.cs +++ b/DNN Platform/Library/Common/Utilities/PathUtils.cs @@ -17,18 +17,18 @@ namespace DotNetNuke.Common.Utilities public class PathUtils : ComponentBase, IPathUtils { - private static readonly Regex FolderPathRx = new Regex("^0\\\\", RegexOptions.Compiled); - + private static readonly Regex FolderPathRx = new Regex("^0\\\\", RegexOptions.Compiled); + internal PathUtils() { - } - + } + public enum UserFolderElement { Root = 0, SubFolder = 1, - } - + } + /// /// Adds backslash to the specified source. /// @@ -60,7 +60,7 @@ public virtual string FormatFolderPath(string folderPath) /// /// Gets the physical path for the specified relative path. - /// + /// /// public virtual string GetPhysicalPath(int portalID, string relativePath) { @@ -81,7 +81,7 @@ public virtual string GetPhysicalPath(int portalID, string relativePath) /// /// Gets the relative path for the specified physical path. - /// + /// /// public virtual string GetRelativePath(int portalID, string physicalPath) { @@ -117,7 +117,7 @@ public virtual string GetRelativePath(int portalID, string physicalPath) /// /// Gets the physical root folder path for the specified portal. - /// + /// /// public virtual string GetRootFolderMapPath(int portalID) { @@ -201,35 +201,6 @@ 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. /// @@ -265,8 +236,37 @@ public virtual string StripFolderPath(string originalPath) } return originalPath.StartsWith("0") ? originalPath.Substring(1) : originalPath; - } - + } + + 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("\\", "/")); + } + private static string GetHostMapPath() { return Globals.HostMapPath; @@ -276,6 +276,6 @@ private static string GetPortalMapPath(int portalId) { var portalInfo = PortalController.Instance.GetPortal(portalId); return portalInfo.HomeDirectoryMapPath; - } + } } } diff --git a/DNN Platform/Library/Common/Utilities/RegexUtils.cs b/DNN Platform/Library/Common/Utilities/RegexUtils.cs index d959686910d..241fbd00050 100644 --- a/DNN Platform/Library/Common/Utilities/RegexUtils.cs +++ b/DNN Platform/Library/Common/Utilities/RegexUtils.cs @@ -14,7 +14,7 @@ public class RegexUtils { /// /// Creates and caches a Regex object for later use and retrieves it in a later call if it is cacehd. - /// + /// /// public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexOptions.None, int timeoutSeconds = 2) { @@ -32,15 +32,15 @@ public static Regex GetCachedRegex(string pattern, RegexOptions options = RegexO key = string.Join(":", "REGEX_ITEM", options.ToString("X"), key.GetHashCode().ToString("X")); // limit timeout between 1 and 10 seconds - if (timeoutSeconds < 1) - { - timeoutSeconds = 1; - } - else if (timeoutSeconds > 10) - { - timeoutSeconds = 10; - } - + if (timeoutSeconds < 1) + { + timeoutSeconds = 1; + } + else if (timeoutSeconds > 10) + { + timeoutSeconds = 10; + } + var cache = CachingProvider.Instance(); var regex = cache.GetItem(key) as Regex; if (regex == null) diff --git a/DNN Platform/Library/Common/Utilities/RetryableAction.cs b/DNN Platform/Library/Common/Utilities/RetryableAction.cs index 9b233cf7b3b..10274964400 100644 --- a/DNN Platform/Library/Common/Utilities/RetryableAction.cs +++ b/DNN Platform/Library/Common/Utilities/RetryableAction.cs @@ -17,16 +17,11 @@ public class RetryableAction { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(RetryableAction)); - static RetryableAction() + public RetryableAction(Action action, string description, int maxRetries, TimeSpan delay) + : this(action, description, maxRetries, delay, 1) { - 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) @@ -41,11 +36,16 @@ public RetryableAction(Action action, string description, int maxRetries, TimeSp this.DelayMultiplier = delayMultiplier; } + static RetryableAction() + { + SleepAction = GoToSleep; + } + /// /// 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. /// @@ -94,11 +94,11 @@ public void TryIt() try { this.Action(); - if (Logger.IsTraceEnabled) - { - Logger.TraceFormat("Action succeeded - {0}", this.Description); - } - + if (Logger.IsTraceEnabled) + { + Logger.TraceFormat("Action succeeded - {0}", this.Description); + } + return; } catch (Exception) @@ -109,11 +109,11 @@ public void TryIt() throw; } - if (Logger.IsTraceEnabled) - { - Logger.TraceFormat("Retrying action {0} - {1}", retrysRemaining, this.Description); - } - + if (Logger.IsTraceEnabled) + { + Logger.TraceFormat("Retrying action {0} - {1}", retrysRemaining, this.Description); + } + SleepAction.Invoke(currentDelay); const double epsilon = 0.0001; @@ -122,9 +122,9 @@ public void TryIt() currentDelay = (int)(currentDelay * this.DelayMultiplier); } } - + retrysRemaining--; - } + } while (true); } diff --git a/DNN Platform/Library/Common/Utilities/SessionVariable.cs b/DNN Platform/Library/Common/Utilities/SessionVariable.cs index ccf4c57a7d4..5c68200a1e2 100644 --- a/DNN Platform/Library/Common/Utilities/SessionVariable.cs +++ b/DNN Platform/Library/Common/Utilities/SessionVariable.cs @@ -13,27 +13,27 @@ namespace DotNetNuke.Common.Utilities /// /// The type of the value to be stored. public class SessionVariable : StateVariable - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new HttpContext.Session item variable. /// /// /// The key to use for storing the value in the items. /// - public SessionVariable(string key) + public SessionVariable(string key) : base(key) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new HttpContext.Session item variable with a initializer. /// /// The key to use for storing the value in the HttpContext.Current.Session. /// A function that is called in order to create a default value per HttpContext.Current.Session. /// - public SessionVariable(string key, Func initializer) + public SessionVariable(string key, Func initializer) : base(key, initializer) { } @@ -47,13 +47,13 @@ private static HttpSessionState CurrentItems { throw new InvalidOperationException("No HttpContext is not available."); } - + var items = current.Session; if (items == null) { throw new InvalidOperationException("No Session State available on current HttpContext."); } - + return items; } } @@ -64,7 +64,7 @@ protected override object this[string key] { return CurrentItems[key]; } - + set { CurrentItems[key] = value; diff --git a/DNN Platform/Library/Common/Utilities/SqlUtils.cs b/DNN Platform/Library/Common/Utilities/SqlUtils.cs index 89f351d369d..2ebc1c62eef 100644 --- a/DNN Platform/Library/Common/Utilities/SqlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/SqlUtils.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Common.Utilities /// /// ----------------------------------------------------------------------------- public class SqlUtils - { + { /// /// function to translate sql exceptions to readable messages. /// It also captures cases where sql server is not available and guards against @@ -54,7 +54,7 @@ public static string TranslateSQLException(SqlException exc) errorMessages.Append("Index #: " + i + "
    " + "Source: " + sqlError.Source + "
    " + "Class: " + sqlError.Class + "
    " + "Number: " + sqlError.Number + "
    " + "Procedure: " + sqlError.Procedure + "
    " + "Message: " + filteredMessage + "
    "); } - + return errorMessages.ToString(); } } diff --git a/DNN Platform/Library/Common/Utilities/StateVariable.cs b/DNN Platform/Library/Common/Utilities/StateVariable.cs index 8293595fddc..c5ac4671c3b 100644 --- a/DNN Platform/Library/Common/Utilities/StateVariable.cs +++ b/DNN Platform/Library/Common/Utilities/StateVariable.cs @@ -14,9 +14,9 @@ namespace DotNetNuke.Common.Utilities public abstract class StateVariable { private readonly string _key; - private readonly Func _initializer; - - /// + private readonly Func _initializer; + + /// /// Initializes a new instance of the class. /// Initializes a new item variable. /// @@ -29,25 +29,25 @@ protected StateVariable(string key) { throw new ArgumentNullException("key"); } - + this._key = key + this.GetType().FullName; - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new item variable with a initializer. /// /// The key to use for storing the value in the dictionary. /// A function that is called in order to create a default value per dictionary. /// - protected StateVariable(string key, Func initializer) + protected StateVariable(string key, Func initializer) : this(key) { if (initializer == null) { throw new ArgumentNullException("initializer"); } - + this._initializer = initializer; } @@ -63,45 +63,45 @@ public bool HasValue } /// - /// Gets or sets or gets the value in the current items. + /// Gets the value in the current items or if none is available default(T). /// - /// - /// If you try to get a value while none is set use for safe access. - /// - public T Value + public T ValueOrDefault { get { var returnedValue = this.GetInitializedInternalValue(); if (returnedValue == null) { - throw new InvalidOperationException("There is no value for the '" + this._key + "' key."); + return default(T); } - + return (T)returnedValue; } - - set - { - this[this._key] = value; - } } /// - /// Gets the value in the current items or if none is available default(T). + /// Gets or sets or gets the value in the current items. /// - public T ValueOrDefault + /// + /// If you try to get a value while none is set use for safe access. + /// + public T Value { get { var returnedValue = this.GetInitializedInternalValue(); if (returnedValue == null) { - return default(T); + throw new InvalidOperationException("There is no value for the '" + this._key + "' key."); } - + return (T)returnedValue; } + + set + { + this[this._key] = value; + } } /// @@ -113,6 +113,14 @@ public T ValueOrDefault /// protected abstract object this[string key] { get; set; } + /// + /// Clears the value in the current items. + /// + public void Clear() + { + this.Remove(this._key); + } + /// /// Removes the value in associated dictionary according. /// @@ -128,16 +136,8 @@ private object GetInitializedInternalValue() value = this._initializer(); this[this._key] = value; } - - return value; - } - /// - /// Clears the value in the current items. - /// - public void Clear() - { - this.Remove(this._key); + return value; } } } diff --git a/DNN Platform/Library/Common/Utilities/StringExtensions.cs b/DNN Platform/Library/Common/Utilities/StringExtensions.cs index c6ed72e4040..3fec06b3dfe 100644 --- a/DNN Platform/Library/Common/Utilities/StringExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/StringExtensions.cs @@ -10,7 +10,7 @@ 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 @@ -24,12 +24,12 @@ public static string Append(this string stringValue, string stringToLink, string { return stringToLink; } - + if (string.IsNullOrEmpty(stringToLink)) { return stringValue; } - + return stringValue + delimiter + stringToLink; } @@ -63,7 +63,7 @@ public static string ReplaceIgnoreCase(this string source, string oldValue, stri { return source; } - + return Regex.Replace(source, Regex.Escape(oldValue), newValue, RegexOptions.IgnoreCase); } } diff --git a/DNN Platform/Library/Common/Utilities/UrlController.cs b/DNN Platform/Library/Common/Utilities/UrlController.cs index 1d1d61517f3..0fafb728ff1 100644 --- a/DNN Platform/Library/Common/Utilities/UrlController.cs +++ b/DNN Platform/Library/Common/Utilities/UrlController.cs @@ -47,7 +47,7 @@ public void UpdateUrl(int PortalID, string Url, string UrlType, int Clicks, Date DataProvider.Instance().AddUrl(PortalID, Url.Replace(@"\", @"/")); } } - + UrlTrackingInfo objURLTracking = this.GetUrlTracking(PortalID, Url, ModuleID); if (objURLTracking == null) { @@ -80,7 +80,7 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID Url = "FileID=" + file.FileId; } - + UrlTrackingInfo objUrlTracking = this.GetUrlTracking(PortalID, Url, ModuleId); if (objUrlTracking != null) { @@ -93,7 +93,7 @@ public void UpdateUrlTracking(int PortalID, string Url, int ModuleId, int UserID { UserID = UserController.Instance.GetCurrentUserInfo().UserID; } - + DataProvider.Instance().AddUrlLog(objUrlTracking.UrlTrackingID, UserID); } } @@ -108,7 +108,7 @@ public ArrayList GetUrlLog(int PortalID, string Url, int ModuleId, DateTime Star { arrUrlLog = CBO.FillCollection(DataProvider.Instance().GetUrlLog(objUrlTracking.UrlTrackingID, StartDate, EndDate), typeof(UrlLogInfo)); } - + return arrUrlLog; } } diff --git a/DNN Platform/Library/Common/Utilities/UrlUtils.cs b/DNN Platform/Library/Common/Utilities/UrlUtils.cs index 48d117df5a8..6ecc08b1c32 100644 --- a/DNN Platform/Library/Common/Utilities/UrlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/UrlUtils.cs @@ -25,16 +25,16 @@ public class UrlUtils public static string Combine(string baseUrl, string relativeUrl) { - if (baseUrl.Length == 0) - { - return relativeUrl; - } - - if (relativeUrl.Length == 0) - { - return baseUrl; - } - + if (baseUrl.Length == 0) + { + return relativeUrl; + } + + if (relativeUrl.Length == 0) + { + return baseUrl; + } + return string.Format("{0}/{1}", baseUrl.TrimEnd(new[] { '/', '\\' }), relativeUrl.TrimStart(new[] { '/', '\\' })); } @@ -53,7 +53,7 @@ public static string DecryptParameter(string value) public static string DecryptParameter(string value, string encryptionKey) { var objSecurity = PortalSecurity.Instance; - + // [DNN-8257] - Can't do URLEncode/URLDecode as it introduces issues on decryption (with / = %2f), so we use a modifed Base64 var toDecrypt = new StringBuilder(value); toDecrypt.Replace("_", "/"); @@ -102,7 +102,7 @@ public static string GetParameterValue(string pair) { return nameValues[1]; } - + return string.Empty; } @@ -112,7 +112,7 @@ public static string GetParameterValue(string pair) /// we don't ever want a tabid, a ctl and a language parameter in the qs /// either, the portalid param is not allowed when the tab is a supertab /// (because NavigateUrl adds the portalId param to the qs). - /// + /// /// public static string[] GetQSParamsForNavigateURL() { @@ -145,16 +145,16 @@ public static string[] GetQSParamsForNavigateURL() { returnValue += "&"; } - + returnValue += keys[i] + "=" + values[j]; } } - + break; } } } - + // return the new querystring as a string array return returnValue.Split('&'); } @@ -187,11 +187,11 @@ public static bool IsSslOffloadEnabled(HttpRequest request) string ssloffload = request.Headers[ssloffloadheader]; if (!string.IsNullOrEmpty(ssloffload) && (string.IsNullOrWhiteSpace(ssloffloadValue) || ssloffloadValue == ssloffload)) - { + { return true; } } - + return false; } @@ -221,9 +221,9 @@ public static string PopUpUrl(string url, Control control, PortalSettings portal { url = url.Replace("http://", "https://"); } - + var popUpUrl = url; - + // ensure delimiters are not used if (!popUpUrl.Contains("dnnModal.show")) { @@ -264,11 +264,11 @@ public static string PopUpUrl(string url, Control control, PortalSettings portal } // Removes the javascript txt for onClick scripts - if (onClickEvent && popUpUrl.StartsWith("javascript:")) - { - popUpUrl = popUpUrl.Replace("javascript:", string.Empty); - } - + if (onClickEvent && popUpUrl.StartsWith("javascript:")) + { + popUpUrl = popUpUrl.Replace("javascript:", string.Empty); + } + return popUpUrl; } @@ -278,11 +278,11 @@ public static string ClosePopUp(bool refresh, string url, bool onClickEvent) closePopUpStr = "javascript:" + string.Format(closePopUpStr, refresh.ToString().ToLowerInvariant(), "'" + url + "'"); // Removes the javascript txt for onClick scripts) - if (onClickEvent && closePopUpStr.StartsWith("javascript:")) - { - closePopUpStr = closePopUpStr.Replace("javascript:", string.Empty); - } - + if (onClickEvent && closePopUpStr.StartsWith("javascript:")) + { + closePopUpStr = closePopUpStr.Replace("javascript:", string.Empty); + } + return closePopUpStr; } @@ -369,7 +369,7 @@ public static string ValidReturnUrl(string url) { var urlWithNoProtocol = url.Substring(2); var portalSettings = PortalSettings.Current; - + // note: this can redirict from parent to childe and vice versa if (!urlWithNoProtocol.StartsWith(portalSettings.PortalAlias.HTTPAlias + "/", StringComparison.InvariantCultureIgnoreCase)) { diff --git a/DNN Platform/Library/Common/Utilities/XmlExtensions.cs b/DNN Platform/Library/Common/Utilities/XmlExtensions.cs index 9619c41e3ba..d6a94182161 100644 --- a/DNN Platform/Library/Common/Utilities/XmlExtensions.cs +++ b/DNN Platform/Library/Common/Utilities/XmlExtensions.cs @@ -53,7 +53,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e { newElement.InnerText = elementValue; } - + node.AppendChild(newElement); return newElement; } @@ -82,7 +82,7 @@ public static XmlNode AddElement(this XmlNode node, string elementName, string e { newElement.InnerText = elementValue; } - + node.AppendChild(newElement); return newElement; } diff --git a/DNN Platform/Library/Common/Utilities/XmlUtils.cs b/DNN Platform/Library/Common/Utilities/XmlUtils.cs index 5836ed3247e..c33e1d54383 100644 --- a/DNN Platform/Library/Common/Utilities/XmlUtils.cs +++ b/DNN Platform/Library/Common/Utilities/XmlUtils.cs @@ -30,7 +30,7 @@ namespace DotNetNuke.Common.Utilities public class XmlUtils { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(XmlUtils)); - + public static void AppendElement(ref XmlDocument objDoc, XmlNode objNode, string attName, string attValue, bool includeIfEmpty) { AppendElement(ref objDoc, objNode, attName, attValue, includeIfEmpty, false); @@ -42,7 +42,7 @@ public static void AppendElement(ref XmlDocument objDoc, XmlNode objNode, string { return; } - + if (cdata) { objNode.AppendChild(CreateCDataElement(objDoc, attName, attValue)); @@ -90,28 +90,28 @@ public static object Deserialize(Stream objStream, Type type) obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } - + var moduleDic = obj as Dictionary; if (moduleDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } - + var tabPermDic = obj as Dictionary; if (tabPermDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } - + var modPermDic = obj as Dictionary; if (modPermDic != null) { obj = DeSerializeDictionary(objStream, "dictionary"); return obj; } - + var serializer = new XmlSerializer(type); using (TextReader tr = new StreamReader(objStream)) { @@ -148,7 +148,7 @@ public static Dictionary DeSerializeDictionary(Stream objSt // in the Hashtable objDictionary.Add(key, (TValue)xser.Deserialize(reader)); } - + return objDictionary; } @@ -213,7 +213,7 @@ public static bool GetAttributeValueAsBoolean(XPathNavigator navigator, string a { boolValue = Convert.ToBoolean(strValue); } - + return boolValue; } @@ -225,7 +225,7 @@ public static int GetAttributeValueAsInteger(XPathNavigator navigator, string at { intValue = Convert.ToInt32(strValue); } - + return intValue; } @@ -272,7 +272,7 @@ public static string GetNodeValue(XPathNavigator navigator, string path, string return strValue; } - + /// ----------------------------------------------------------------------------- /// /// Gets the value of node. @@ -311,7 +311,7 @@ public static string GetNodeValue(XmlNode objNode, string nodeName, string defau strValue = defaultValue; } } - + return strValue; } @@ -354,7 +354,7 @@ public static bool GetNodeValueBoolean(XmlNode objNode, string nodeName, bool de bValue = Convert.ToBoolean(strValue); } } - + return bValue; } @@ -416,7 +416,7 @@ public static DateTime GetNodeValueDate(XmlNode objNode, string nodeName, DateTi } } } - + return dateValue; } @@ -487,7 +487,7 @@ public static int GetNodeValueInt(XmlNode node, string nodeName, int defaultValu intValue = Convert.ToInt32(strValue); } } - + return intValue; } @@ -561,7 +561,7 @@ public static float GetNodeValueSingle(XmlNode node, string nodeName, float defa sValue = Convert.ToSingle(strValue, CultureInfo.InvariantCulture); } } - + return sValue; } @@ -594,8 +594,8 @@ public static float GetNodeValueSingle(XPathNavigator navigator, string path, fl } return Convert.ToSingle(strValue, CultureInfo.InvariantCulture); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlWriterSettings object. @@ -644,7 +644,7 @@ public static string SerializeDictionary(IDictionary source, string rootName) xmlItem.AppendChild(xmlDoc.ImportNode(xmlObject.DocumentElement, true)); xmlRoot.AppendChild(xmlItem); } - + // Return the OuterXml of the profile strString = xmlDoc.OuterXml; } @@ -652,7 +652,7 @@ public static string SerializeDictionary(IDictionary source, string rootName) { strString = string.Empty; } - + return strString; } @@ -675,7 +675,7 @@ public static void SerializeHashtable(Hashtable hashtable, XmlDocument xmlDocume nodeSettingValue.InnerText = hashtable[key].ToString(); } } - + public static void UpdateAttribute(XmlNode node, string attName, string attValue) { if (node != null) @@ -717,7 +717,7 @@ public static string RemoveInvalidXmlCharacters(string content) newString.Append(ch); } } - + return newString.ToString(); } @@ -725,7 +725,7 @@ public static void XSLTransform(XmlDocument doc, ref StreamWriter writer, string { var xslt = new XslCompiledTransform(); xslt.Load(xsltUrl); - + // Transform the file. xslt.Transform(doc, null, writer); } @@ -753,7 +753,7 @@ public static string Serialize(object obj) xmlObject = xmlDocEl.OuterXml; } - + return xmlObject; } @@ -777,7 +777,7 @@ public static string XPathLiteral(string value) { return "\"" + value + "\""; } - + if (!value.Contains("'")) { return "'" + value + "'"; @@ -800,28 +800,28 @@ public static string XPathLiteral(string value) { sb.Append(", "); } - + sb.Append("\""); sb.Append(substrings[i]); sb.Append("\""); needComma = true; } - + if (i < substrings.Length - 1) { if (needComma) { sb.Append(", "); } - + sb.Append("'\"'"); } } - + sb.Append(")"); return sb.ToString(); } - + [Obsolete("This method is obsolete. Use .Net XmlDocument.Load instead. Scheduled removal in v11.0.0.")] public static XmlDocument GetXMLContent(string contentUrl) { diff --git a/DNN Platform/Library/Common/XmlValidatorBase.cs b/DNN Platform/Library/Common/XmlValidatorBase.cs index 59240292440..b0c1a0b3aae 100644 --- a/DNN Platform/Library/Common/XmlValidatorBase.cs +++ b/DNN Platform/Library/Common/XmlValidatorBase.cs @@ -23,6 +23,17 @@ public XmlValidatorBase() this._schemaSet = new XmlSchemaSet(); } + /// + /// Gets the schema set. + /// + public XmlSchemaSet SchemaSet + { + get + { + return this._schemaSet; + } + } + /// /// Gets or sets the errors. /// @@ -35,24 +46,13 @@ public ArrayList Errors { return this._errs; } - + set { this._errs = value; } } - /// - /// Gets the schema set. - /// - public XmlSchemaSet SchemaSet - { - get - { - return this._schemaSet; - } - } - /// /// Determines whether this instance is valid. /// @@ -70,16 +70,16 @@ public bool IsValid() var settings = new XmlReaderSettings(); settings.Schemas = this._schemaSet; settings.ValidationType = ValidationType.Schema; - + // Set the validation event handler. settings.ValidationEventHandler += this.ValidationCallBack; XmlReader vreader = XmlReader.Create(this._reader, settings); - + // Read and validate the XML data. while (vreader.Read()) { } - + vreader.Close(); return this._errs.Count == 0; } @@ -100,16 +100,6 @@ 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. /// @@ -124,5 +114,15 @@ public virtual bool Validate(string filename) }; 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); + } } } diff --git a/DNN Platform/Library/ComponentModel/AbstractContainer.cs b/DNN Platform/Library/ComponentModel/AbstractContainer.cs index 3d19b7e3509..01f2f433485 100644 --- a/DNN Platform/Library/ComponentModel/AbstractContainer.cs +++ b/DNN Platform/Library/ComponentModel/AbstractContainer.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.ComponentModel using System.Collections; public abstract class AbstractContainer : IContainer - { + { public abstract string Name { get; } public abstract object GetComponent(string name); @@ -72,38 +72,38 @@ public virtual void RegisterComponent(Type componentType) this.RegisterComponent(componentType.FullName, componentType, componentType, ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent() - where TComponent : class + public virtual void RegisterComponent() + where TComponent : class { this.RegisterComponent(typeof(TComponent)); } - public virtual void RegisterComponent(string name) - where TComponent : class + public virtual void RegisterComponent(string name) + where TComponent : class { this.RegisterComponent(name, typeof(TComponent), typeof(TComponent), ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) - where TComponent : class + public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class { this.RegisterComponent(name, typeof(TComponent), typeof(TComponent), lifestyle); } - public virtual void RegisterComponent() - where TComponent : class + public virtual void RegisterComponent() + where TComponent : class { this.RegisterComponent(typeof(TContract), typeof(TComponent)); } - public virtual void RegisterComponent(string name) - where TComponent : class + public virtual void RegisterComponent(string name) + where TComponent : class { this.RegisterComponent(name, typeof(TContract), typeof(TComponent), ComponentLifeStyleType.Singleton); } - public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) - where TComponent : class + public virtual void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class { this.RegisterComponent(name, typeof(TContract), typeof(TComponent), lifestyle); } @@ -135,8 +135,8 @@ public void RegisterComponentInstance(object instance) public void RegisterComponentInstance(string name, object instance) { this.RegisterComponentInstance(name, typeof(TContract), instance); - } - + } + public virtual IDictionary GetCustomDependencies() { return this.GetComponentSettings(typeof(TComponent).FullName); diff --git a/DNN Platform/Library/ComponentModel/ComponentBase.cs b/DNN Platform/Library/ComponentModel/ComponentBase.cs index 9f94b556c4b..66bdf11fdfb 100644 --- a/DNN Platform/Library/ComponentModel/ComponentBase.cs +++ b/DNN Platform/Library/ComponentModel/ComponentBase.cs @@ -15,11 +15,11 @@ public static TContract Instance { get { - if (_useTestable && _testableInstance != null) - { - return _testableInstance; - } - + if (_useTestable && _testableInstance != null) + { + return _testableInstance; + } + var component = ComponentFactory.GetComponent(); if (component == null) diff --git a/DNN Platform/Library/ComponentModel/ComponentFactory.cs b/DNN Platform/Library/ComponentModel/ComponentFactory.cs index a4c54fe992f..073cd349db2 100644 --- a/DNN Platform/Library/ComponentModel/ComponentFactory.cs +++ b/DNN Platform/Library/ComponentModel/ComponentFactory.cs @@ -17,7 +17,7 @@ public static void InstallComponents(params IComponentInstaller[] installers) { throw new ArgumentNullException("installers"); } - + VerifyContainer(); foreach (IComponentInstaller installer in installers) { @@ -25,7 +25,7 @@ public static void InstallComponents(params IComponentInstaller[] installers) { throw new ArgumentNullException("installers"); } - + installer.InstallComponents(Container); } } @@ -42,14 +42,6 @@ public static TContract GetComponent() return Container.GetComponent(); } - private static void VerifyContainer() - { - if (Container == null) - { - Container = new SimpleContainer(); - } - } - public static object GetComponent(Type contractType) { VerifyContainer(); @@ -88,7 +80,7 @@ public static Dictionary GetComponents() { components[componentName] = GetComponent(componentName); } - + return components; } @@ -110,15 +102,15 @@ public static IDictionary GetComponentSettings() return Container.GetComponentSettings(); } - public static void RegisterComponent() - where TComponent : class + public static void RegisterComponent() + where TComponent : class { VerifyContainer(); Container.RegisterComponent(); } - public static void RegisterComponent() - where TComponent : class + public static void RegisterComponent() + where TComponent : class { VerifyContainer(); Container.RegisterComponent(); @@ -136,15 +128,15 @@ public static void RegisterComponent(Type contractType, Type componentType) Container.RegisterComponent(contractType, componentType); } - public static void RegisterComponent(string name) - where TComponent : class + public static void RegisterComponent(string name) + where TComponent : class { VerifyContainer(); Container.RegisterComponent(name); } - public static void RegisterComponent(string name) - where TComponent : class + public static void RegisterComponent(string name) + where TComponent : class { VerifyContainer(); Container.RegisterComponent(name); @@ -203,5 +195,13 @@ public static void RegisterComponentSettings(IDictionary dependencie VerifyContainer(); Container.RegisterComponentSettings(dependencies); } + + private static void VerifyContainer() + { + if (Container == null) + { + Container = new SimpleContainer(); + } + } } } diff --git a/DNN Platform/Library/ComponentModel/ComponentType.cs b/DNN Platform/Library/ComponentModel/ComponentType.cs index c47dcd74588..105c260a259 100644 --- a/DNN Platform/Library/ComponentModel/ComponentType.cs +++ b/DNN Platform/Library/ComponentModel/ComponentType.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.ComponentModel internal class ComponentType { private readonly Type _BaseType; - private readonly ComponentBuilderCollection _ComponentBuilders = new ComponentBuilderCollection(); - - /// + private readonly ComponentBuilderCollection _ComponentBuilders = new ComponentBuilderCollection(); + + /// /// Initializes a new instance of the class. /// /// The base type of Components of this ComponentType. diff --git a/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs b/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs index 9ef892488d6..920b95ebe49 100644 --- a/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs +++ b/DNN Platform/Library/ComponentModel/ComponentTypeCollection.cs @@ -8,6 +8,5 @@ namespace DotNetNuke.ComponentModel using DotNetNuke.Collections.Internal; internal class ComponentTypeCollection : SharedDictionary - { - } + {} } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs index ae18526393c..9fb2a12deab 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/CacheableAttribute.cs @@ -7,8 +7,8 @@ namespace DotNetNuke.ComponentModel.DataAnnotations using System.Web.Caching; public class CacheableAttribute : Attribute - { - /// + { + /// /// Initializes a new instance of the class. /// Construct a new CacheableAttribute. /// @@ -16,30 +16,30 @@ public CacheableAttribute() { this.CachePriority = CacheItemPriority.Default; this.CacheTimeOut = 20; - } - - /// + } + + /// /// Initializes a new instance of the class. /// Construct a new CacheableAttribute. /// /// The cacheKey to use. - public CacheableAttribute(string cacheKey) - : this(cacheKey, CacheItemPriority.Default, 20) - { - } - - /// + public CacheableAttribute(string cacheKey) + : this(cacheKey, CacheItemPriority.Default, 20) + { + } + + /// /// Initializes a new instance of the class. /// Construct a new CacheableAttribute. /// /// The cacheKey to use. /// The priority of the cached item. - public CacheableAttribute(string cacheKey, CacheItemPriority priority) - : this(cacheKey, priority, 20) - { - } - - /// + public CacheableAttribute(string cacheKey, CacheItemPriority priority) + : this(cacheKey, priority, 20) + { + } + + /// /// Initializes a new instance of the class. /// Construct a new CacheableAttribute. /// diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs index 59461499559..41a185250ea 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/DeclareColumnsAttribute.cs @@ -7,6 +7,5 @@ namespace DotNetNuke.ComponentModel.DataAnnotations using System; public class DeclareColumnsAttribute : Attribute - { - } + {} } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs index 90926d830b7..907b127eb2d 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IgnoreColumnAttribute.cs @@ -7,6 +7,5 @@ namespace DotNetNuke.ComponentModel.DataAnnotations using System; public class IgnoreColumnAttribute : Attribute - { - } + {} } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs index fb43075ead4..161f981caab 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/IncludeColumnAttribute.cs @@ -7,6 +7,5 @@ namespace DotNetNuke.ComponentModel.DataAnnotations using System; public class IncludeColumnAttribute : Attribute - { - } + {} } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs index 6e09a197ce0..78352271b4f 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/PrimaryKeyAttribute.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.ComponentModel.DataAnnotations public class PrimaryKeyAttribute : Attribute { - public PrimaryKeyAttribute(string columnName) + public PrimaryKeyAttribute(string columnName) : this(columnName, columnName) { } @@ -20,9 +20,9 @@ public PrimaryKeyAttribute(string columnName, string propertyName) } public bool AutoIncrement { get; set; } - + public string ColumnName { get; set; } - + public string PropertyName { get; set; } } } diff --git a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs index f14e03820b3..9fee73e3c21 100644 --- a/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs +++ b/DNN Platform/Library/ComponentModel/DataAnnotations/ReadOnlyColumnAttribute.cs @@ -7,6 +7,5 @@ namespace DotNetNuke.ComponentModel.DataAnnotations using System; public class ReadOnlyColumnAttribute : Attribute - { - } + {} } diff --git a/DNN Platform/Library/ComponentModel/IContainer.cs b/DNN Platform/Library/ComponentModel/IContainer.cs index a1cb3719315..a236f59f5f4 100644 --- a/DNN Platform/Library/ComponentModel/IContainer.cs +++ b/DNN Platform/Library/ComponentModel/IContainer.cs @@ -10,23 +10,23 @@ public interface IContainer { string Name { get; } - void RegisterComponent() - where TComponent : class; + void RegisterComponent() + where TComponent : class; - void RegisterComponent(string name) - where TComponent : class; + void RegisterComponent(string name) + where TComponent : class; - void RegisterComponent(string name, ComponentLifeStyleType lifestyle) - where TComponent : class; + void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class; - void RegisterComponent() - where TComponent : class; + void RegisterComponent() + where TComponent : class; - void RegisterComponent(string name) - where TComponent : class; + void RegisterComponent(string name) + where TComponent : class; - void RegisterComponent(string name, ComponentLifeStyleType lifestyle) - where TComponent : class; + void RegisterComponent(string name, ComponentLifeStyleType lifestyle) + where TComponent : class; void RegisterComponent(Type componentType); diff --git a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs index d913a4a446c..6a78b0f1ce3 100644 --- a/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/InstanceComponentBuilder.cs @@ -7,9 +7,9 @@ namespace DotNetNuke.ComponentModel internal class InstanceComponentBuilder : IComponentBuilder { private readonly object _Instance; - private readonly string _Name; - - /// + private readonly string _Name; + + /// /// Initializes a new instance of the class. /// /// @@ -18,7 +18,7 @@ public InstanceComponentBuilder(string name, object instance) { this._Name = name; this._Instance = instance; - } + } public string Name { @@ -26,8 +26,8 @@ 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 adc1d5abc12..0cc66411f75 100644 --- a/DNN Platform/Library/ComponentModel/ProviderInstaller.cs +++ b/DNN Platform/Library/ComponentModel/ProviderInstaller.cs @@ -40,12 +40,12 @@ public ProviderInstaller(string providerType, Type providerInterface, ComponentL this._ComponentLifeStyle = lifeStyle; this._ProviderType = providerType; this._ProviderInterface = providerInterface; - } - + } + public void InstallComponents(IContainer container) { ProviderConfiguration config = ProviderConfiguration.GetProviderConfiguration(this._ProviderType); - + // Register the default provider first (so it is the first component registered for its service interface if (config != null) { @@ -61,8 +61,8 @@ public void InstallComponents(IContainer container) } } } - } - + } + private void InstallProvider(IContainer container, Provider provider) { if (provider != null) @@ -72,7 +72,7 @@ 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) { @@ -97,7 +97,7 @@ private void InstallProvider(IContainer container, Provider provider) { settingsDict.Add(key, provider.Attributes.Get(key)); } - + // Register the settings as dependencies container.RegisterComponentSettings(type.FullName, settingsDict); } diff --git a/DNN Platform/Library/ComponentModel/SimpleContainer.cs b/DNN Platform/Library/ComponentModel/SimpleContainer.cs index 60b72ec9809..6dd49861e3a 100644 --- a/DNN Platform/Library/ComponentModel/SimpleContainer.cs +++ b/DNN Platform/Library/ComponentModel/SimpleContainer.cs @@ -18,25 +18,25 @@ public class SimpleContainer : AbstractContainer private readonly ComponentTypeCollection _componentTypes = new ComponentTypeCollection(); - private readonly SharedDictionary _registeredComponents = new SharedDictionary(); - - /// + private readonly SharedDictionary _registeredComponents = new SharedDictionary(); + + /// /// Initializes a new instance of the class. /// - public SimpleContainer() + public SimpleContainer() : this(string.Format("Container_{0}", Guid.NewGuid())) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// /// public SimpleContainer(string name) { this._name = name; - } - + } + public override string Name { get @@ -51,7 +51,7 @@ public override void RegisterComponent(string name, Type type) { this._registeredComponents[type] = name; } - } + } public override object GetComponent(string name) { @@ -59,91 +59,6 @@ public override object GetComponent(string name) return this.GetComponent(builder); } - - private void AddBuilder(Type contractType, IComponentBuilder builder) - { - ComponentType componentType = this.GetComponentType(contractType); - if (componentType != null) - { - ComponentBuilderCollection builders = componentType.ComponentBuilders; - - using (builders.GetWriteLock()) - { - builders.AddBuilder(builder, true); - } - - using (this._componentBuilders.GetWriteLock()) - { - this._componentBuilders.AddBuilder(builder, false); - } - } - } - - private void AddComponentType(Type contractType) - { - ComponentType componentType = this.GetComponentType(contractType); - - if (componentType == null) - { - componentType = new ComponentType(contractType); - - using (this._componentTypes.GetWriteLock()) - { - this._componentTypes[componentType.BaseType] = componentType; - } - } - } - - private object GetComponent(IComponentBuilder builder) - { - object component; - if (builder == null) - { - component = null; - } - else - { - component = builder.BuildComponent(); - } - - return component; - } - - private IComponentBuilder GetComponentBuilder(string name) - { - IComponentBuilder builder; - - using (this._componentBuilders.GetReadLock()) - { - this._componentBuilders.TryGetValue(name, out builder); - } - - return builder; - } - - private IComponentBuilder GetDefaultComponentBuilder(ComponentType componentType) - { - IComponentBuilder builder; - - using (componentType.ComponentBuilders.GetReadLock()) - { - builder = componentType.ComponentBuilders.DefaultBuilder; - } - - return builder; - } - - private ComponentType GetComponentType(Type contractType) - { - ComponentType componentType; - - using (this._componentTypes.GetReadLock()) - { - this._componentTypes.TryGetValue(contractType, out componentType); - } - - return componentType; - } public override object GetComponent(Type contractType) { @@ -181,7 +96,7 @@ public override object GetComponent(string name, Type contractType) component = this.GetComponent(builder); } - + return component; } @@ -199,7 +114,7 @@ public override string[] GetComponentList(Type contractType) } } } - + return components.ToArray(); } @@ -210,7 +125,7 @@ public override IDictionary GetComponentSettings(string name) { settings = this._componentDependencies[name]; } - + return settings; } @@ -228,7 +143,7 @@ public override void RegisterComponent(string name, Type contractType, Type type builder = new SingletonComponentBuilder(name, type); break; } - + this.AddBuilder(contractType, builder); this.RegisterComponent(name, type); @@ -250,5 +165,90 @@ public override void RegisterComponentSettings(string name, IDictionary dependen this._componentDependencies[name] = dependencies; } } + + private void AddBuilder(Type contractType, IComponentBuilder builder) + { + ComponentType componentType = this.GetComponentType(contractType); + if (componentType != null) + { + ComponentBuilderCollection builders = componentType.ComponentBuilders; + + using (builders.GetWriteLock()) + { + builders.AddBuilder(builder, true); + } + + using (this._componentBuilders.GetWriteLock()) + { + this._componentBuilders.AddBuilder(builder, false); + } + } + } + + private void AddComponentType(Type contractType) + { + ComponentType componentType = this.GetComponentType(contractType); + + if (componentType == null) + { + componentType = new ComponentType(contractType); + + using (this._componentTypes.GetWriteLock()) + { + this._componentTypes[componentType.BaseType] = componentType; + } + } + } + + private object GetComponent(IComponentBuilder builder) + { + object component; + if (builder == null) + { + component = null; + } + else + { + component = builder.BuildComponent(); + } + + return component; + } + + private IComponentBuilder GetComponentBuilder(string name) + { + IComponentBuilder builder; + + using (this._componentBuilders.GetReadLock()) + { + this._componentBuilders.TryGetValue(name, out builder); + } + + return builder; + } + + private IComponentBuilder GetDefaultComponentBuilder(ComponentType componentType) + { + IComponentBuilder builder; + + using (componentType.ComponentBuilders.GetReadLock()) + { + builder = componentType.ComponentBuilders.DefaultBuilder; + } + + return builder; + } + + private ComponentType GetComponentType(Type contractType) + { + ComponentType componentType; + + using (this._componentTypes.GetReadLock()) + { + this._componentTypes.TryGetValue(contractType, out componentType); + } + + return componentType; + } } } diff --git a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs index 64eb7b592c6..5a047c28a34 100644 --- a/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/SingletonComponentBuilder.cs @@ -11,9 +11,9 @@ internal class SingletonComponentBuilder : IComponentBuilder { private readonly string _Name; private readonly Type _Type; - private object _Instance; - - /// + private object _Instance; + + /// /// Initializes a new instance of the class. /// /// The name of the component. @@ -22,7 +22,7 @@ public SingletonComponentBuilder(string name, Type type) { this._Name = name; this._Type = type; - } + } public string Name { @@ -30,18 +30,18 @@ public string Name { return this._Name; } - } - + } + public object BuildComponent() { if (this._Instance == null) { this.CreateInstance(); } - + return this._Instance; } - + private void CreateInstance() { this._Instance = Reflection.CreateObject(this._Type); diff --git a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs index e58f9b229d4..99e1e6490d7 100644 --- a/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs +++ b/DNN Platform/Library/ComponentModel/TransientComponentBuilder.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.ComponentModel internal class TransientComponentBuilder : IComponentBuilder { private readonly string _Name; - private readonly Type _Type; - - /// + private readonly Type _Type; + + /// /// Initializes a new instance of the class. /// /// The name of the component. @@ -21,7 +21,7 @@ public TransientComponentBuilder(string name, Type type) { this._Name = name; this._Type = type; - } + } public string Name { @@ -29,8 +29,8 @@ public string Name { return this._Name; } - } - + } + public object BuildComponent() { return Reflection.CreateObject(this._Type); diff --git a/DNN Platform/Library/Data/ControllerBase.cs b/DNN Platform/Library/Data/ControllerBase.cs index 9596af4fc83..c369b4c964a 100644 --- a/DNN Platform/Library/Data/ControllerBase.cs +++ b/DNN Platform/Library/Data/ControllerBase.cs @@ -16,9 +16,9 @@ public abstract class ControllerBase : ServiceLocator { protected readonly IDataContext DataContext; - protected ControllerBase() - { - } + protected ControllerBase() + { + } protected ControllerBase(IDataContext dataContext) { diff --git a/DNN Platform/Library/Data/DataProvider.cs b/DNN Platform/Library/Data/DataProvider.cs index 6c1dfbe5b1d..ca63077fe36 100644 --- a/DNN Platform/Library/Data/DataProvider.cs +++ b/DNN Platform/Library/Data/DataProvider.cs @@ -30,10 +30,10 @@ namespace DotNetNuke.Data public abstract class DataProvider { - private const int DuplicateKey = 2601; - + private const int DuplicateKey = 2601; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DataProvider)); - + public virtual string ConnectionString { get @@ -45,7 +45,7 @@ public virtual string ConnectionString // Use connection string specified in provider connectionString = this.Settings["connectionString"]; } - + return connectionString; } } @@ -59,7 +59,7 @@ public virtual string DatabaseOwner { databaseOwner += "."; } - + return databaseOwner; } } @@ -68,11 +68,6 @@ public string DefaultProviderName { get { return Instance().ProviderName; } } - - public static DataProvider Instance() - { - return ComponentFactory.GetComponent(); - } public abstract bool IsConnectionValid { get; } @@ -85,7 +80,7 @@ public virtual string ObjectQualifier { objectQualifier += "_"; } - + return objectQualifier; } } @@ -110,74 +105,53 @@ public virtual string UpgradeConnectionString ? this.Settings["upgradeConnectionString"] : this.ConnectionString; } - } - - 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 - // or maximum value of December 31, 9999 - if (dateToFix <= SqlDateTime.MinValue.Value) - { - dateToFix = SqlDateTime.MinValue.Value.AddDays(1); - } - else if (dateToFix >= SqlDateTime.MaxValue.Value) - { - dateToFix = SqlDateTime.MaxValue.Value.AddDays(-1); - } - - return dateToFix; } - private object GetRoleNull(int RoleID) + public static DataProvider Instance() { - if (RoleID.ToString(CultureInfo.InvariantCulture) == Globals.glbRoleNothing) - { - return DBNull.Value; - } - - return RoleID; - } + return ComponentFactory.GetComponent(); + } + + 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); - + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec); - + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); - + public abstract void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary commandParameters); public abstract IDataReader ExecuteReader(string procedureName, params object[] commandParameters); - + public abstract IDataReader ExecuteReader(int timeoutSec, string procedureName, params object[] commandParameters); public abstract T ExecuteScalar(string procedureName, params object[] commandParameters); - + public abstract T ExecuteScalar(int timeoutSec, string procedureName, params object[] commandParameters); public abstract IDataReader ExecuteSQL(string sql); - - public abstract IDataReader ExecuteSQL(string sql, int timeoutSec); - + + public abstract IDataReader ExecuteSQL(string sql, int timeoutSec); + public abstract string ExecuteScript(string script); - + public abstract string ExecuteScript(string script, int timeoutSec); public abstract string ExecuteScript(string connectionString, string sql); - + public abstract string ExecuteScript(string connectionString, string sql, int timeoutSec); public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql); - + public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec); public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, out string errorMessage); - - public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage); - + + public abstract IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage); + public virtual void CommitTransaction(DbTransaction transaction) { try @@ -214,13 +188,13 @@ public virtual void RollbackTransaction(DbTransaction transaction) transaction.Connection.Close(); } } - } - + } + public virtual object GetNull(object Field) { return Null.GetNull(Field, DBNull.Value); - } - + } + public virtual IDataReader FindDatabaseVersion(int Major, int Minor, int Build) { return this.ExecuteReader("FindDatabaseVersion", Major, Minor, Build); @@ -242,7 +216,7 @@ public virtual Version GetDatabaseEngineVersion() { CBO.CloseDataReader(dr, true); } - + return new Version(version); } @@ -280,7 +254,7 @@ public virtual string GetProviderPath() // ReSharper disable AssignNullToNotNullAttribute if (Directory.Exists(path)) - + // ReSharper restore AssignNullToNotNullAttribute { if (!this.IsConnectionValid) @@ -298,47 +272,8 @@ public virtual string GetProviderPath() { path = "ERROR: providerPath folder value not specified in web.config for SqlDataProvider"; } - - return path; - } - - private Version GetVersionInternal(bool current) - { - Version version = null; - IDataReader dr = null; - try - { - dr = current ? this.GetDatabaseVersion() : this.GetDatabaseInstallVersion(); - if (dr.Read()) - { - version = new Version(Convert.ToInt32(dr["Major"]), Convert.ToInt32(dr["Minor"]), - Convert.ToInt32(dr["Build"])); - } - } - catch (SqlException ex) - { - bool noStoredProc = false; - for (int i = 0; i <= ex.Errors.Count - 1; i++) - { - SqlError sqlError = ex.Errors[i]; - if (sqlError.Number == 2812 && sqlError.Class == 16) // 2812 - 16 means SP could not be found - { - noStoredProc = true; - break; - } - } - if (!noStoredProc) - { - throw; - } - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return version; + return path; } public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, string Owner, string Qualifier) @@ -368,7 +303,7 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, bError = false; break; } - + string filteredMessage = string.Empty; switch (sqlError.Number) { @@ -385,13 +320,13 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, filteredMessage = "Sql deadlock victim"; break; } - + errorMessages.Append("Index #: " + i + "
    " + "Source: " + sqlError.Source + "
    " + "Class: " + sqlError.Class + "
    " + "Number: " + sqlError.Number + "
    " + "Message: " + filteredMessage + "

    "); } - + if (bError) { connectionString = message + errorMessages; @@ -402,7 +337,7 @@ public virtual string TestDatabaseConnection(DbConnectionStringBuilder builder, CBO.CloseDataReader(dr, true); } } - + return connectionString; } @@ -432,8 +367,8 @@ public virtual int GetLastAppliedIteration(int Major, int Minor, int Build) public virtual string GetUnappliedIterations(string version) { return this.ExecuteScalar("GetUnappliedIterations", version); - } - + } + public virtual IDataReader GetHostSetting(string SettingName) { return this.ExecuteReader("GetHostSetting", SettingName); @@ -448,8 +383,8 @@ public virtual void UpdateHostSetting(string SettingName, string SettingValue, b int LastModifiedByUserID) { this.ExecuteNonQuery("UpdateHostSetting", SettingName, SettingValue, SettingIsSecure, LastModifiedByUserID); - } - + } + public virtual void DeleteServer(int ServerId) { this.ExecuteNonQuery("DeleteServer", ServerId); @@ -469,8 +404,8 @@ public virtual int UpdateServerActivity(string serverName, string iisAppName, Da DateTime lastActivityDate, int pingFailureCount, bool enabled) { return this.ExecuteScalar("UpdateServerActivity", serverName, iisAppName, createdDate, lastActivityDate, pingFailureCount, enabled); - } - + } + [Obsolete("Deprecated in Platform 7.4.0, please use CreatePortal version that contain's culturecode. Scheduled removal in v10.0.0.")] public virtual int CreatePortal(string portalname, string currency, DateTime ExpiryDate, double HostFee, double HostSpace, int PageQuota, int UserQuota, int SiteLogHistory, @@ -496,7 +431,7 @@ public virtual int CreatePortal(string portalname, string currency, DateTime Exp string HomeDirectory, string CultureCode, int CreatedByUserID) { return - this.ExecuteScalar( + this.ExecuteScalar( "AddPortalInfo", PortalSecurity.Instance.InputFilter(portalname, PortalSecurity.FilterFlag.NoMarkup), currency, @@ -542,7 +477,7 @@ public virtual IDataReader GetPortals(string CultureCode) { reader = this.ExecuteReader("GetPortals", CultureCode); } - + return reader; } @@ -560,7 +495,7 @@ public virtual IDataReader GetPortalsByUser(int userId) { return this.ExecuteReader("GetPortalsByUser", userId); } - + public virtual IDataReader GetPortalSettings(int PortalId, string CultureCode) { return this.ExecuteReader("GetPortalSettings", PortalId, CultureCode); @@ -619,7 +554,7 @@ public virtual void UpdatePortalInfo(int portalId, int portalGroupId, string por int termsTabId, int privacyTabId, string defaultLanguage, string homeDirectory, int lastModifiedByUserID, string cultureCode) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdatePortalInfo", portalId, portalGroupId, @@ -658,20 +593,6 @@ 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) { @@ -684,7 +605,7 @@ public virtual void UpdatePortalSetup(int portalId, int administratorId, int adm int userTabId, int searchTabId, int custom404TabId, int custom500TabId, int termsTabId, int privacyTabId, int adminTabId, string cultureCode) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdatePortalSetup", portalId, administratorId, @@ -702,11 +623,11 @@ public virtual void UpdatePortalSetup(int portalId, int administratorId, int adm privacyTabId, adminTabId, cultureCode); - } - + } + public virtual int AddTabAfter(TabInfo tab, int afterTabId, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddTabAfter", afterTabId, tab.ContentItemId, @@ -741,7 +662,7 @@ public virtual int AddTabAfter(TabInfo tab, int afterTabId, int createdByUserID) public virtual int AddTabBefore(TabInfo tab, int beforeTabId, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddTabBefore", beforeTabId, tab.ContentItemId, @@ -773,10 +694,10 @@ public virtual int AddTabBefore(TabInfo tab, int beforeTabId, int createdByUserI this.GetNull(tab.CultureCode), tab.IsSystem); } - + public virtual int AddTabToEnd(TabInfo tab, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddTabToEnd", tab.ContentItemId, this.GetNull(tab.PortalID), @@ -993,7 +914,7 @@ public virtual void UpdateTab(int tabId, int contentItemId, int portalId, Guid v bool permanentRedirect, float siteMapPriority, int lastModifiedByuserID, string cultureCode, bool IsSystem) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateTab", tabId, contentItemId, @@ -1050,14 +971,14 @@ public virtual void MarkAsPublished(int tabId) public virtual void UpdateTabVersion(int tabId, Guid versionGuid) { this.ExecuteNonQuery("UpdateTabVersion", tabId, versionGuid); - } - + } + public virtual int AddModule(int contentItemId, int portalId, int moduleDefId, bool allTabs, DateTime startDate, DateTime endDate, bool inheritViewPermissions, bool isShareable, bool isShareableViewOnly, bool isDeleted, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddModule", contentItemId, this.GetNull(portalId), @@ -1071,7 +992,7 @@ public virtual int AddModule(int contentItemId, int portalId, int moduleDefId, b isDeleted, createdByUserID); } - + public virtual void AddTabModule(int TabId, int ModuleId, string ModuleTitle, string Header, string Footer, int ModuleOrder, string PaneName, int CacheTime, string CacheMethod, string Alignment, string Color, string Border, string IconFile, int Visibility, @@ -1081,7 +1002,7 @@ public virtual void AddTabModule(int TabId, int ModuleId, string ModuleTitle, st Guid DefaultLanguageGuid, Guid LocalizedVersionGuid, string CultureCode, int createdByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "AddTabModule", TabId, ModuleId, @@ -1112,7 +1033,7 @@ public virtual void AddTabModule(int TabId, int ModuleId, string ModuleTitle, st CultureCode, createdByUserID); } - + public virtual void DeleteModule(int moduleId) { this.ExecuteNonQuery("DeleteModule", moduleId); @@ -1255,7 +1176,7 @@ public virtual void UpdateModule(int moduleId, int moduleDefId, int contentItemI bool isShareableViewOnly, bool isDeleted, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateModule", moduleId, moduleDefId, @@ -1296,7 +1217,7 @@ public virtual void UpdateTabModule(int TabModuleId, int TabId, int ModuleId, st Guid DefaultLanguageGuid, Guid LocalizedVersionGuid, string CultureCode, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateTabModule", TabModuleId, TabId, @@ -1353,15 +1274,15 @@ public virtual void UpdateTabModuleVersionByModule(int moduleId) public virtual IDataReader GetInstalledModules() { return this.ExecuteReader("GetInstalledModules"); - } - + } + public virtual int AddDesktopModule(int packageID, string moduleName, string folderName, string friendlyName, string description, string version, bool isPremium, bool isAdmin, string businessControllerClass, int supportedFeatures, int shareable, string compatibleVersions, string dependencies, string permissions, int contentItemId, int createdByUserID, string adminPage, string hostPage) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddDesktopModule", packageID, moduleName, @@ -1405,7 +1326,7 @@ public virtual void UpdateDesktopModule(int desktopModuleId, int packageID, stri string permissions, int contentItemId, int lastModifiedByUserID, string adminpage, string hostpage) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateDesktopModule", desktopModuleId, packageID, @@ -1426,8 +1347,8 @@ public virtual void UpdateDesktopModule(int desktopModuleId, int packageID, stri lastModifiedByUserID, adminpage, hostpage); - } - + } + public virtual int AddPortalDesktopModule(int portalId, int desktopModuleId, int createdByUserID) { return this.ExecuteScalar("AddPortalDesktopModule", portalId, desktopModuleId, createdByUserID); @@ -1441,8 +1362,8 @@ public virtual void DeletePortalDesktopModules(int portalId, int desktopModuleId public virtual IDataReader GetPortalDesktopModules(int portalId, int desktopModuleId) { return this.ExecuteReader("GetPortalDesktopModules", this.GetNull(portalId), this.GetNull(desktopModuleId)); - } - + } + public virtual int AddModuleDefinition(int desktopModuleId, string friendlyName, string definitionName, int defaultCacheTime, int createdByUserID) { @@ -1465,13 +1386,13 @@ public virtual void UpdateModuleDefinition(int moduleDefId, string friendlyName, { this.ExecuteNonQuery("UpdateModuleDefinition", moduleDefId, friendlyName, definitionName, defaultCacheTime, lastModifiedByUserID); - } - + } + public virtual int AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, int controlType, int viewOrder, string helpUrl, bool supportsPartialRendering, bool supportsPopUps, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddModuleControl", this.GetNull(moduleDefId), this.GetNull(controlKey), @@ -1503,7 +1424,7 @@ public virtual void UpdateModuleControl(int moduleControlId, int moduleDefId, st bool supportsPartialRendering, bool supportsPopUps, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateModuleControl", moduleControlId, this.GetNull(moduleDefId), @@ -1517,14 +1438,14 @@ public virtual void UpdateModuleControl(int moduleControlId, int moduleDefId, st supportsPartialRendering, supportsPopUps, lastModifiedByUserID); - } - + } + public virtual int AddFolder(int portalId, Guid uniqueId, Guid versionGuid, string folderPath, string mappedPath, int storageLocation, bool isProtected, bool isCached, DateTime lastUpdated, int createdByUserId, int folderMappingId, bool isVersioned, int workflowId, int parentId) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddFolder", this.GetNull(portalId), uniqueId, @@ -1582,7 +1503,7 @@ public virtual void UpdateFolder(int portalId, Guid versionGuid, int folderId, s bool isProtected, bool isCached, DateTime lastUpdated, int lastModifiedByUserID, int folderMappingID, bool isVersioned, int workflowID, int parentID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateFolder", this.GetNull(portalId), versionGuid, @@ -1608,14 +1529,14 @@ public virtual void UpdateFolderVersion(int folderId, Guid versionGuid) public virtual IDataReader UpdateLegacyFolders() { return this.ExecuteReader("UpdateLegacyFolders"); - } - + } + public virtual int AddFile(int portalId, Guid uniqueId, Guid versionGuid, string fileName, string extension, long size, int width, int height, string contentType, string folder, int folderId, int createdByUserID, string hash, DateTime lastModificationTime, string title, string description, DateTime startDate, DateTime endDate, bool enablePublishPeriod, int contentItemId) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddFile", this.GetNull(portalId), uniqueId, @@ -1729,7 +1650,7 @@ public virtual void UpdateFile(int fileId, Guid versionGuid, string fileName, st int lastModifiedByUserID, string hash, DateTime lastModificationTime, string title, string description, DateTime startDate, DateTime endDate, bool enablePublishPeriod, int contentItemId) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateFile", fileId, versionGuid, @@ -1753,7 +1674,7 @@ public virtual void UpdateFile(int fileId, Guid versionGuid, string fileName, st public virtual void UpdateFileLastModificationTime(int fileId, DateTime lastModificationTime) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateFileLastModificationTime", fileId, lastModificationTime); @@ -1761,7 +1682,7 @@ public virtual void UpdateFileLastModificationTime(int fileId, DateTime lastModi public virtual void UpdateFileHashCode(int fileId, string hashCode) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateFileHashCode", fileId, hashCode); @@ -1771,12 +1692,12 @@ public virtual void UpdateFileContent(int fileId, byte[] content) { this.ExecuteNonQuery("UpdateFileContent", fileId, this.GetNull(content)); } - + public virtual void UpdateFileVersion(int fileId, Guid versionGuid) { this.ExecuteNonQuery("UpdateFileVersion", fileId, versionGuid); - } - + } + public virtual int AddPermission(string permissionCode, int moduleDefID, string permissionKey, string permissionName, int createdByUserID) { return this.ExecuteScalar("AddPermission", moduleDefID, permissionCode, permissionKey, permissionName, createdByUserID); @@ -1790,13 +1711,13 @@ public virtual void DeletePermission(int permissionID) public virtual void UpdatePermission(int permissionID, string permissionCode, int moduleDefID, string permissionKey, string permissionName, int lastModifiedByUserID) { this.ExecuteNonQuery("UpdatePermission", permissionID, permissionCode, moduleDefID, permissionKey, permissionName, lastModifiedByUserID); - } - + } + public virtual int AddModulePermission(int moduleId, int portalId, int permissionId, int roleId, bool allowAccess, int userId, int createdByUserId) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddModulePermission", moduleId, portalId, @@ -1846,7 +1767,7 @@ public virtual void UpdateModulePermission(int modulePermissionId, int moduleId, int roleId, bool allowAccess, int userId, int lastModifiedByUserId) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateModulePermission", modulePermissionId, moduleId, @@ -1856,12 +1777,12 @@ public virtual void UpdateModulePermission(int modulePermissionId, int moduleId, allowAccess, this.GetNull(userId), lastModifiedByUserId); - } - + } + public virtual int AddTabPermission(int tabId, int permissionId, int roleID, bool allowAccess, int userId, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddTabPermission", tabId, permissionId, @@ -1900,7 +1821,7 @@ public virtual void UpdateTabPermission(int tabPermissionId, int tabId, int perm bool allowAccess, int userId, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateTabPermission", tabPermissionId, tabId, @@ -1909,12 +1830,12 @@ public virtual void UpdateTabPermission(int tabPermissionId, int tabId, int perm allowAccess, this.GetNull(userId), lastModifiedByUserID); - } - + } + public virtual int AddFolderPermission(int folderId, int permissionId, int roleID, bool allowAccess, int userId, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddFolderPermission", folderId, permissionId, @@ -1962,7 +1883,7 @@ public virtual IDataReader GetFolderPermissionsByPortalAndPath(int portalId, str public virtual void UpdateFolderPermission(int FolderPermissionID, int FolderID, int PermissionID, int roleID, bool AllowAccess, int UserID, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateFolderPermission", FolderPermissionID, FolderID, @@ -1971,12 +1892,12 @@ public virtual void UpdateFolderPermission(int FolderPermissionID, int FolderID, AllowAccess, this.GetNull(UserID), lastModifiedByUserID); - } - + } + public virtual int AddDesktopModulePermission(int portalDesktopModuleID, int permissionID, int roleID, bool allowAccess, int userID, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddDesktopModulePermission", portalDesktopModuleID, permissionID, @@ -2020,7 +1941,7 @@ public virtual void UpdateDesktopModulePermission(int desktopModulePermissionID, int permissionID, int roleID, bool allowAccess, int userID, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateDesktopModulePermission", desktopModulePermissionID, portalDesktopModuleID, @@ -2029,8 +1950,8 @@ public virtual void UpdateDesktopModulePermission(int desktopModulePermissionID, allowAccess, this.GetNull(userID), lastModifiedByUserID); - } - + } + public virtual int AddRoleGroup(int portalId, string groupName, string description, int createdByUserID) { return this.ExecuteScalar("AddRoleGroup", portalId, groupName, description, createdByUserID); @@ -2060,14 +1981,14 @@ public virtual void UpdateRoleGroup(int roleGroupId, string groupName, string de int lastModifiedByUserID) { this.ExecuteNonQuery("UpdateRoleGroup", roleGroupId, groupName, description, lastModifiedByUserID); - } - + } + public virtual int AddRole(int portalId, int roleGroupId, string roleName, string description, float serviceFee, string billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, bool isPublic, bool autoAssignment, string rsvpCode, string iconFile, int createdByUserID, int status, int securityMode, bool isSystemRole) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddRole", portalId, this.GetNull(roleGroupId), @@ -2121,7 +2042,7 @@ public virtual void UpdateRole(int roleId, int roleGroupId, string roleName, str string iconFile, int lastModifiedByUserID, int status, int securityMode, bool isSystemRole) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateRole", roleId, this.GetNull(roleGroupId), @@ -2146,19 +2067,19 @@ public virtual void UpdateRole(int roleId, int roleGroupId, string roleName, str public virtual void UpdateRoleSetting(int roleId, string settingName, string settingValue, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateRoleSetting", roleId, settingName, settingValue, lastModifiedByUserID); - } - + } + public virtual int AddUser(int portalID, string username, string firstName, string lastName, int affiliateId, bool isSuperUser, string email, string displayName, bool updatePassword, bool isApproved, int createdByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddUser", portalID, username, @@ -2338,7 +2259,7 @@ public virtual void UpdateUser(int userId, int portalID, string firstName, strin bool isApproved, bool refreshRoles, string lastIpAddress, Guid passwordResetToken, DateTime passwordResetExpiration, bool isDeleted, int lastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateUser", userId, this.GetNull(portalID), @@ -2371,8 +2292,8 @@ public virtual void UserAgreedToTerms(int portalId, int userId) public virtual void UserRequestsRemoval(int portalId, int userId, bool remove) { this.ExecuteNonQuery("UserRequestsRemoval", portalId, userId, remove); - } - + } + public virtual int AddUserRole(int portalId, int userId, int roleId, int status, bool isOwner, DateTime effectiveDate, DateTime expiryDate, int createdByUserID) { @@ -2410,8 +2331,8 @@ public virtual void UpdateUserRole(int userRoleId, int status, bool isOwner, Dat { this.ExecuteNonQuery("UpdateUserRole", userRoleId, status, isOwner, this.GetNull(effectiveDate), this.GetNull(expiryDate), lastModifiedByUserID); - } - + } + [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 virtual void DeleteUsersOnline(int timeWindow) { @@ -2438,7 +2359,7 @@ public virtual void UpdateUsersOnline(Hashtable userList) // No users to process, quit method return; } - + foreach (string key in userList.Keys) { var info = userList[key] as AnonymousUserInfo; @@ -2453,8 +2374,8 @@ public virtual void UpdateUsersOnline(Hashtable userList) this.ExecuteNonQuery("UpdateOnlineUser", user.UserID, user.PortalID, user.TabID, user.LastActiveDate); } } - } - + } + public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int dataType, string defaultValue, string propertyCategory, string propertyName, bool readOnly, bool required, string validationExpression, int viewOrder, @@ -2463,7 +2384,7 @@ public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int data int retValue; try { - retValue = this.ExecuteScalar( + retValue = this.ExecuteScalar( "AddPropertyDefinition", this.GetNull(portalId), moduleDefId, @@ -2491,7 +2412,7 @@ public virtual int AddPropertyDefinition(int portalId, int moduleDefId, int data throw; } } - + return retValue; } @@ -2533,7 +2454,7 @@ public virtual void UpdatePropertyDefinition(int propertyDefinitionId, int dataT bool required, string validation, int viewOrder, bool visible, int length, int defaultVisibility, int lastModifiedByUserId) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdatePropertyDefinition", propertyDefinitionId, dataType, @@ -2553,13 +2474,13 @@ public virtual void UpdatePropertyDefinition(int propertyDefinitionId, int dataT public virtual IDataReader SearchProfilePropertyValues(int portalId, string propertyName, string searchString) { return this.ExecuteReader("SearchProfilePropertyValues", portalId, propertyName, searchString); - } - + } + public virtual int AddSkinControl(int packageID, string ControlKey, string ControlSrc, bool SupportsPartialRendering, int CreatedByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddSkinControl", this.GetNull(packageID), this.GetNull(ControlKey), @@ -2596,7 +2517,7 @@ public virtual IDataReader GetSkinControlByPackageID(int packageID) public virtual void UpdateSkinControl(int skinControlID, int packageID, string ControlKey, string ControlSrc, bool SupportsPartialRendering, int LastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateSkinControl", skinControlID, this.GetNull(packageID), @@ -2604,8 +2525,8 @@ public virtual void UpdateSkinControl(int skinControlID, int packageID, string C ControlSrc, SupportsPartialRendering, LastModifiedByUserID); - } - + } + public virtual int AddSkin(int skinPackageID, string skinSrc) { return this.ExecuteScalar("AddSkin", skinPackageID, skinSrc); @@ -2653,8 +2574,8 @@ public virtual void UpdateSkinPackage(int skinPackageID, int packageID, int port { this.ExecuteNonQuery("UpdateSkinPackage", skinPackageID, packageID, this.GetNull(portalID), skinName, skinType, LastModifiedByUserID); - } - + } + public virtual void AddProfile(int userId, int portalId) { this.ExecuteNonQuery("AddProfile", userId, portalId); @@ -2673,8 +2594,8 @@ public virtual IDataReader GetProfile(int userId, int portalId) public virtual void UpdateProfile(int userId, int portalId, string profileData) { this.ExecuteNonQuery("UpdateProfile", userId, portalId, profileData); - } - + } + public virtual void AddUrl(int PortalID, string Url) { this.ExecuteNonQuery("AddUrl", PortalID, Url); @@ -2731,8 +2652,8 @@ public virtual void UpdateUrlTracking(int PortalID, string Url, bool LogActivity public virtual void UpdateUrlTrackingStats(int PortalID, string Url, int ModuleID) { this.ExecuteNonQuery("UpdateUrlTrackingStats", PortalID, Url, this.GetNull(ModuleID)); - } - + } + public virtual IDataReader GetDefaultLanguageByModule(string ModuleList) { return this.ExecuteReader("GetDefaultLanguageByModule", ModuleList); @@ -2756,8 +2677,8 @@ public virtual IDataReader GetSearchResultModules(int PortalID) public virtual IDataReader GetSearchSettings(int ModuleId) { return this.ExecuteReader("GetSearchSettings", ModuleId); - } - + } + public virtual int AddListEntry(string ListName, string Value, string Text, int ParentID, int Level, bool EnableSortOrder, int DefinitionID, string Description, int PortalID, bool SystemList, @@ -2765,7 +2686,7 @@ public virtual int AddListEntry(string ListName, string Value, string Text, int { try { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddListEntry", ListName, Value, @@ -2839,8 +2760,8 @@ public virtual void UpdateListEntry(int EntryID, string Value, string Text, stri public virtual void UpdateListSortOrder(int EntryID, bool MoveUp) { this.ExecuteNonQuery("UpdateListSortOrder", EntryID, MoveUp); - } - + } + public virtual int AddPortalAlias(int PortalID, string HTTPAlias, string cultureCode, string skin, string browserType, bool isPrimary, int createdByUserID) { return this.ExecuteScalar("AddPortalAlias", PortalID, HTTPAlias, this.GetNull(cultureCode), this.GetNull(skin), this.GetNull(browserType), isPrimary, createdByUserID); @@ -2869,14 +2790,14 @@ public virtual void UpdatePortalAlias(string PortalAlias, int lastModifiedByUser public virtual void UpdatePortalAliasInfo(int PortalAliasID, int PortalID, string HTTPAlias, string cultureCode, string skin, string browserType, bool isPrimary, int lastModifiedByUserID) { this.ExecuteNonQuery("UpdatePortalAlias", PortalAliasID, PortalID, HTTPAlias, this.GetNull(cultureCode), this.GetNull(skin), this.GetNull(browserType), isPrimary, lastModifiedByUserID); - } - + } + public virtual int AddEventMessage(string eventName, int priority, string processorType, string processorCommand, string body, string sender, string subscriberId, string authorizedRoles, string exceptionMessage, DateTime sentDate, DateTime expirationDate, string attributes) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddEventMessage", eventName, priority, @@ -2905,13 +2826,13 @@ public virtual IDataReader GetEventMessagesBySubscriber(string eventName, string public virtual void SetEventMessageComplete(int eventMessageId) { this.ExecuteNonQuery("SetEventMessageComplete", eventMessageId); - } - + } + public virtual int AddAuthentication(int packageID, string authenticationType, bool isEnabled, string settingsControlSrc, string loginControlSrc, string logoffControlSrc, int CreatedByUserID) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddAuthentication", packageID, authenticationType, @@ -2973,7 +2894,7 @@ public virtual void UpdateAuthentication(int authenticationID, int packageID, st bool isEnabled, string settingsControlSrc, string loginControlSrc, string logoffControlSrc, int LastModifiedByUserID) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateAuthentication", authenticationID, packageID, @@ -2983,14 +2904,14 @@ public virtual void UpdateAuthentication(int authenticationID, int packageID, st loginControlSrc, logoffControlSrc, LastModifiedByUserID); - } - + } + public virtual int AddPackage(int portalID, string name, string friendlyName, string description, string type, string version, string license, string manifest, string owner, string organization, string url, string email, string releaseNotes, bool isSystemPackage, int createdByUserID, string folderName, string iconFile) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddPackage", this.GetNull(portalID), name, @@ -3025,7 +2946,7 @@ public virtual IDataReader GetPackageDependencies() { return this.ExecuteReader("GetPackageDependencies"); } - + public virtual IDataReader GetPackages(int portalID) { return this.ExecuteReader("GetPackages", this.GetNull(portalID)); @@ -3057,7 +2978,7 @@ public virtual void UpdatePackage(int packageID, int portalID, string friendlyNa bool isSystemPackage, int lastModifiedByUserID, string folderName, string iconFile) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdatePackage", packageID, this.GetNull(portalID), @@ -3081,8 +3002,8 @@ public virtual void UpdatePackage(int packageID, int portalID, string friendlyNa public virtual void SetCorePackageVersions() { this.ExecuteNonQuery("SetCorePackageVersions"); - } - + } + public virtual int AddLanguage(string cultureCode, string cultureName, string fallbackCulture, int CreatedByUserID) { @@ -3171,8 +3092,8 @@ public virtual void UpdatePortalDefaultLanguage(int portalID, string CultureCode public virtual void UpdatePortalLanguage(int portalID, int languageID, bool IsPublished, int UpdatedByUserID) { this.ExecuteNonQuery("UpdatePortalLanguage", portalID, languageID, IsPublished, UpdatedByUserID); - } - + } + public virtual void AddDefaultFolderTypes(int portalID) { this.ExecuteNonQuery("AddDefaultFolderTypes", portalID); @@ -3232,8 +3153,8 @@ public virtual void UpdateFolderMappingSetting(int folderMappingID, string setti { this.ExecuteNonQuery("UpdateFolderMappingsSetting", folderMappingID, settingName, settingValue, lastModifiedByUserID); - } - + } + [Obsolete("Deprecated in Platform 9.2.0, please use the overload that takes passwordsRetained and daysRetained. Scheduled removal in v11.0.0.")] public virtual IDataReader GetPasswordHistory(int userId) { @@ -3254,8 +3175,8 @@ public virtual void AddPasswordHistory(int userId, string password, string passw public virtual void AddPasswordHistory(int userId, string password, string passwordHistory, int passwordsRetained, int daysRetained) { this.ExecuteNonQuery("AddPasswordHistory", this.GetNull(userId), password, passwordHistory, passwordsRetained, daysRetained, this.GetNull(userId)); - } - + } + public virtual DateTime GetDatabaseTimeUtc() { return this.ExecuteScalar("GetDatabaseTimeUtc"); @@ -3273,8 +3194,8 @@ public virtual DateTimeOffset GetDatabaseTimeOffset() reader.Read(); return reader.GetDateTimeOffset(0); } - } - + } + public virtual void DeletePreviewProfile(int id) { this.ExecuteNonQuery("Mobile_DeletePreviewProfile", id); @@ -3328,32 +3249,32 @@ public virtual int SaveRedirection(int id, int portalId, string name, int type, public virtual void SaveRedirectionRule(int id, int redirectionId, string capbility, string expression) { this.ExecuteNonQuery("Mobile_SaveRedirectionRule", id, redirectionId, capbility, expression); - } - + } + public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, string logUserName, int logPortalID, string logPortalName, DateTime logCreateDate, string logServerName, string logProperties, int logConfigID, ExceptionInfo exception, bool notificationActive) { if (exception != null) { - if (!string.IsNullOrEmpty(exception.ExceptionHash)) - { - this.ExecuteNonQuery( + if (!string.IsNullOrEmpty(exception.ExceptionHash)) + { + this.ExecuteNonQuery( "AddException", exception.ExceptionHash, exception.Message, exception.StackTrace, exception.InnerMessage, exception.InnerStackTrace, - exception.Source); - } - - // DNN-6218 + DNN-6239 + DNN-6242: Due to change in the AddEventLog stored - // procedure in 7.4.0, we need to try a fallback especially during upgrading + exception.Source); + } + + // DNN-6218 + DNN-6239 + DNN-6242: Due to change in the AddEventLog stored + // procedure in 7.4.0, we need to try a fallback especially during upgrading int logEventID; try { - logEventID = this.ExecuteScalar( + logEventID = this.ExecuteScalar( "AddEventLog", logGUID, logTypeKey, @@ -3370,7 +3291,7 @@ public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, str } catch (SqlException) { - var s = this.ExecuteScalar( + var s = this.ExecuteScalar( "AddEventLog", logGUID, logTypeKey, @@ -3384,15 +3305,15 @@ public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, str logConfigID); // old SPROC wasn't returning anything; trying a workaround - if (!int.TryParse(s ?? "-1", out logEventID)) - { - logEventID = Null.NullInteger; - } + if (!int.TryParse(s ?? "-1", out logEventID)) + { + logEventID = Null.NullInteger; + } } if (!string.IsNullOrEmpty(exception.AssemblyVersion) && exception.AssemblyVersion != "-1") { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "AddExceptionEvent", logEventID, exception.AssemblyVersion, @@ -3406,7 +3327,7 @@ public virtual void AddLog(string logGUID, string logTypeKey, int logUserID, str } else { - this.ExecuteScalar( + this.ExecuteScalar( "AddEventLog", logGUID, logTypeKey, @@ -3440,7 +3361,7 @@ public virtual void AddLogTypeConfigInfo(bool loggingIsActive, string logTypeKey { logTypeKey = string.Empty; } - + if (logTypePortalID == "*") { portalID = -1; @@ -3449,8 +3370,8 @@ public virtual void AddLogTypeConfigInfo(bool loggingIsActive, string logTypeKey { portalID = Convert.ToInt32(logTypePortalID); } - - this.ExecuteNonQuery( + + this.ExecuteNonQuery( "AddEventLogConfig", this.GetNull(logTypeKey), this.GetNull(portalID), @@ -3552,7 +3473,7 @@ public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, str { logTypeKey = string.Empty; } - + if (logTypePortalID == "*") { portalID = -1; @@ -3561,8 +3482,8 @@ public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, str { portalID = Convert.ToInt32(logTypePortalID); } - - this.ExecuteNonQuery( + + this.ExecuteNonQuery( "UpdateEventLogConfig", id, this.GetNull(logTypeKey), @@ -3575,15 +3496,15 @@ public virtual void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, str this.GetNull(notificationThresholdTimeType), mailFromAddress, mailToAddress); - } - + } + public virtual int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, int CreatedByUserID, string FriendlyName, DateTime ScheduleStartDate) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddSchedule", TypeFullName, TimeLapse, @@ -3668,7 +3589,7 @@ public virtual void UpdateSchedule(int ScheduleID, string TypeFullName, int Time string ObjectDependencies, string Servers, int LastModifiedByUserID, string FriendlyName, DateTime ScheduleStartDate) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateSchedule", ScheduleID, TypeFullName, @@ -3690,9 +3611,9 @@ public virtual void UpdateSchedule(int ScheduleID, string TypeFullName, int Time public virtual void UpdateScheduleHistory(int ScheduleHistoryID, DateTime EndDate, bool Succeeded, string LogNotes, DateTime NextStart) { this.ExecuteNonQuery("UpdateScheduleHistory", ScheduleHistoryID, FixDate(EndDate), this.GetNull(Succeeded), LogNotes, FixDate(NextStart)); - } - - public virtual int AddExtensionUrlProvider( + } + + public virtual int AddExtensionUrlProvider( int providerId, int desktopModuleId, string providerName, @@ -3703,7 +3624,7 @@ public virtual int AddExtensionUrlProvider( bool redirectAllUrls, bool replaceAllUrls) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddExtensionUrlProvider", providerId, desktopModuleId, @@ -3734,8 +3655,8 @@ public virtual void SaveExtensionUrlProviderSetting(int providerId, int portalId public virtual void UpdateExtensionUrlProvider(int providerId, bool isActive) { this.ExecuteNonQuery("UpdateExtensionUrlProvider", providerId, isActive); - } - + } + public virtual IDataReader GetIPFilters() { return this.ExecuteReader("GetIPFilters"); @@ -3759,8 +3680,8 @@ public virtual void UpdateIPFilter(int ipFilterid, string ipAddress, string subn public virtual IDataReader GetIPFilter(int ipf) { return this.ExecuteReader("GetIPFilter", ipf); - } - + } + public virtual IDataReader GetFileVersions(int fileId) { return this.ExecuteReader("GetFileVersions", fileId); @@ -3778,7 +3699,7 @@ public virtual int AddFileVersion(int fileId, Guid uniqueId, Guid versionGuid, s { if (content == null) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddFileVersion", fileId, uniqueId, @@ -3801,8 +3722,8 @@ public virtual int AddFileVersion(int fileId, Guid uniqueId, Guid versionGuid, s this.GetNull(contentItemID), published); } - - return this.ExecuteScalar( + + return this.ExecuteScalar( "AddFileVersion", fileId, uniqueId, @@ -3845,8 +3766,8 @@ public virtual IDataReader GetFileVersion(int fileId, int version) public void SetPublishedVersion(int fileId, int newPublishedVersion) { this.ExecuteNonQuery("SetPublishedVersion", fileId, newPublishedVersion); - } - + } + public virtual int GetContentWorkflowUsageCount(int workflowId) { return this.ExecuteScalar("GetContentWorkflowUsageCount", workflowId); @@ -3865,7 +3786,7 @@ public virtual int GetContentWorkflowStateUsageCount(int stateId) [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual int AddContentWorkflow(int portalId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddContentWorkflow", this.GetNull(portalId), workflowName, @@ -3891,7 +3812,7 @@ public virtual IDataReader GetContentWorkflows(int portalId) [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public virtual void UpdateContentWorkflow(int workflowId, string workflowName, string description, bool isDeleted, bool startAfterCreating, bool startAfterEditing, bool dispositionEnabled) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateContentWorkflow", workflowId, workflowName, @@ -3908,7 +3829,7 @@ public virtual int AddContentWorkflowState(int workflowId, string stateName, int string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddContentWorkflowState", workflowId, stateName, @@ -3935,7 +3856,7 @@ public virtual void UpdateContentWorkflowState(int stateId, string stateName, in string onCompleteMessageSubject, string onCompleteMessageBody, string onDiscardMessageSubject, string onDiscardMessageBody) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateContentWorkflowState", stateId, stateName, @@ -3965,7 +3886,7 @@ public virtual IDataReader GetContentWorkflowStates(int workflowId) [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowLogger.AddWorkflowLog. Scheduled removal in v10.0.0.")] public virtual int AddContentWorkflowLog(string action, string comment, int user, int workflowId, int contentItemId) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddContentWorkflowLog", action, comment, @@ -3988,7 +3909,7 @@ public virtual int DeleteContentWorkflowLogs(int contentItemId, int workflowId) public virtual int AddContentWorkflowStatePermission(int stateId, int permissionId, int roleId, bool allowAccess, int userId, int createdByUserId) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddContentWorkflowStatePermission", stateId, permissionId, @@ -4000,7 +3921,7 @@ public virtual int AddContentWorkflowStatePermission(int stateId, int permission public virtual void UpdateContentWorkflowStatePermission(int workflowStatePermissionId, int stateId, int permissionId, int roleId, bool allowAccess, int userId, int lastModifiedByUserId) { - this.ExecuteNonQuery( + this.ExecuteNonQuery( "UpdateContentWorkflowStatePermission", workflowStatePermissionId, stateId, @@ -4041,13 +3962,13 @@ public virtual IDataReader GetContentWorkflowSource(int workflowId, string sourc public virtual int AddContentWorkflowSource(int workflowId, string sourceName, string sourceType) { return this.ExecuteScalar("AddContentWorkflowSource", workflowId, sourceName, sourceType); - } - + } + public virtual IDataReader GetAllSearchTypes() { return this.ExecuteReader("SearchTypes_GetAll"); - } - + } + public virtual IDataReader GetAllSynonymsGroups(int portalId, string cultureCode) { return this.ExecuteReader("GetAllSynonymsGroups", portalId, cultureCode); @@ -4055,7 +3976,7 @@ public virtual IDataReader GetAllSynonymsGroups(int portalId, string cultureCode public virtual int AddSynonymsGroup(string synonymsTags, int createdByUserId, int portalId, string cultureCode) { - return this.ExecuteScalar( + return this.ExecuteScalar( "AddSynonymsGroup", synonymsTags, createdByUserId, @@ -4071,8 +3992,8 @@ public virtual void UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags public virtual void DeleteSynonymsGroup(int synonymsGroupId) { this.ExecuteNonQuery("DeleteSynonymsGroup", synonymsGroupId); - } - + } + public virtual IDataReader GetSearchStopWords(int portalId, string cultureCode) { return this.ExecuteReader("GetSearchStopWords", portalId, cultureCode); @@ -4091,8 +4012,8 @@ public virtual void UpdateSearchStopWords(int stopWordsId, string stopWords, int public virtual void DeleteSearchStopWords(int stopWordsId) { this.ExecuteNonQuery("DeleteSearchStopWords", stopWordsId); - } - + } + public void AddSearchDeletedItems(SearchDocumentToDelete deletedIDocument) { try @@ -4120,13 +4041,13 @@ public void DeleteProcessedSearchDeletedItems(DateTime cutoffTime) public IDataReader GetSearchDeletedItems(DateTime cutoffTime) { return this.ExecuteReader("SearchDeletedItems_Select", cutoffTime); - } - + } + public virtual IDataReader GetAvailableUsersForIndex(int portalId, DateTime startDate, int startUserId, int numberOfUsers) { return this.ExecuteReader(90, "GetAvailableUsersForIndex", portalId, startDate, startUserId, numberOfUsers); - } - + } + public virtual void AddOutputCacheItem(int itemId, string cacheKey, string output, DateTime expiration) { Instance().ExecuteNonQuery("OutputCacheAddItem", itemId, cacheKey, output, expiration); @@ -4165,8 +4086,8 @@ public virtual void PurgeOutputCache() public virtual void RemoveOutputCacheItem(int itemId) { Instance().ExecuteNonQuery("OutputCacheRemoveItem", itemId); - } - + } + public virtual Guid AddRedirectMessage(int userId, int tabId, string text) { return this.ExecuteScalar("AddRedirectMessage", userId, tabId, text); @@ -4180,8 +4101,8 @@ public virtual string GetRedirectMessage(Guid id) public virtual void DeleteOldRedirectMessage(DateTime cutofDateTime) { this.ExecuteNonQuery("DeleteOldRedirectMessage", FixDate(cutofDateTime)); - } - + } + public virtual void UpdateAuthCookie(string cookieValue, DateTime utcExpiry, int userId) { this.ExecuteNonQuery("AuthCookies_Update", cookieValue, FixDate(utcExpiry), userId); @@ -4200,8 +4121,8 @@ public virtual void DeleteAuthCookie(string cookieValue) public virtual void DeleteExpiredAuthCookies(DateTime utcExpiredBefore) { this.ExecuteNonQuery("AuthCookies_DeleteOld", FixDate(utcExpiredBefore)); - } - + } + [Obsolete("Deprecated in 7.0.0. This method is unneccessary. You can get a reader and convert it to a DataSet. Scheduled removal in v10.0.0.")] public virtual DataSet ExecuteDataSet(string procedureName, params object[] commandParameters) { @@ -4226,7 +4147,7 @@ public virtual IDataReader ExecuteSQL(string sql, params IDataParameter[] comman sqlCommandParameters[intIndex] = (SqlParameter)commandParameters[intIndex]; } } - + sql = DataUtil.ReplaceTokens(sql); try { @@ -4243,6 +4164,85 @@ public virtual IDataReader ExecuteSQL(string sql, params IDataParameter[] comman public virtual IDataReader GetFiles(int folderId, bool retrieveUnpublishedFiles = false) { return this.GetFiles(folderId, retrieveUnpublishedFiles, false); - } + } + + 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; + } + + private static DateTime FixDate(DateTime dateToFix) + { + // Fix for Sql Dates having a minimum value of January 1, 1753 + // or maximum value of December 31, 9999 + if (dateToFix <= SqlDateTime.MinValue.Value) + { + dateToFix = SqlDateTime.MinValue.Value.AddDays(1); + } + else if (dateToFix >= SqlDateTime.MaxValue.Value) + { + dateToFix = SqlDateTime.MaxValue.Value.AddDays(-1); + } + + return dateToFix; + } + + private object GetRoleNull(int RoleID) + { + if (RoleID.ToString(CultureInfo.InvariantCulture) == Globals.glbRoleNothing) + { + return DBNull.Value; + } + + return RoleID; + } + + private Version GetVersionInternal(bool current) + { + Version version = null; + IDataReader dr = null; + try + { + dr = current ? this.GetDatabaseVersion() : this.GetDatabaseInstallVersion(); + if (dr.Read()) + { + version = new Version(Convert.ToInt32(dr["Major"]), Convert.ToInt32(dr["Minor"]), + Convert.ToInt32(dr["Build"])); + } + } + catch (SqlException ex) + { + bool noStoredProc = false; + for (int i = 0; i <= ex.Errors.Count - 1; i++) + { + SqlError sqlError = ex.Errors[i]; + if (sqlError.Number == 2812 && sqlError.Class == 16) // 2812 - 16 means SP could not be found + { + noStoredProc = true; + break; + } + } + + if (!noStoredProc) + { + throw; + } + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return version; + } } } diff --git a/DNN Platform/Library/Data/DataUtil.cs b/DNN Platform/Library/Data/DataUtil.cs index 1f7fecbe2a9..0230ef517fa 100644 --- a/DNN Platform/Library/Data/DataUtil.cs +++ b/DNN Platform/Library/Data/DataUtil.cs @@ -32,7 +32,7 @@ internal static string GenerateExecuteStoredProcedureSql(string procedureName, p { // Add output for output params parameterFormat += " output"; } - + parameterName = param.ParameterName; } diff --git a/DNN Platform/Library/Data/DatabaseConnectionProvider.cs b/DNN Platform/Library/Data/DatabaseConnectionProvider.cs index b55504066ce..ed6d796cb76 100644 --- a/DNN Platform/Library/Data/DatabaseConnectionProvider.cs +++ b/DNN Platform/Library/Data/DatabaseConnectionProvider.cs @@ -9,12 +9,12 @@ namespace DotNetNuke.Data using DotNetNuke.ComponentModel; public abstract class DatabaseConnectionProvider - { + { public static DatabaseConnectionProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + public abstract int ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string query); public abstract void ExecuteNonQuery(string connectionString, CommandType commandType, int commandTimeout, string procedure, object[] commandParameters); @@ -27,6 +27,6 @@ public static DatabaseConnectionProvider Instance() public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable); - public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); + public abstract void BulkInsert(string connectionString, int commandTimeout, string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters); } } diff --git a/DNN Platform/Library/Data/IDataContext.cs b/DNN Platform/Library/Data/IDataContext.cs index 1aa6def0802..a63842ed59c 100644 --- a/DNN Platform/Library/Data/IDataContext.cs +++ b/DNN Platform/Library/Data/IDataContext.cs @@ -11,20 +11,20 @@ namespace DotNetNuke.Data public interface IDataContext : IDisposable { void BeginTransaction(); - + void Commit(); void Execute(CommandType type, string sql, params object[] args); - + IEnumerable ExecuteQuery(CommandType type, string sql, params object[] args); - + T ExecuteScalar(CommandType type, string sql, params object[] args); - + T ExecuteSingleOrDefault(CommandType type, string sql, params object[] args); - IRepository GetRepository() - where T : class; - + IRepository GetRepository() + where T : class; + void RollbackTransaction(); } } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs index f7173eda2c0..46679090a92 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentColumnMap.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Data.PetaPoco [CLSCompliant(false)] public class FluentColumnMap - { + { public FluentColumnMap() { } @@ -24,17 +24,17 @@ public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConvert { } - public ColumnInfo ColumnInfo { get; set; } + public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter, Func toDbConverter) + { + this.ColumnInfo = columnInfo; + this.FromDbConverter = fromDbConverter; + this.ToDbConverter = toDbConverter; + } - public Func FromDbConverter { get; set; } + public ColumnInfo ColumnInfo { get; set; } - public Func ToDbConverter { get; set; } + public Func FromDbConverter { get; set; } - public FluentColumnMap(ColumnInfo columnInfo, Func fromDbConverter, Func toDbConverter) - { - this.ColumnInfo = columnInfo; - this.FromDbConverter = fromDbConverter; - this.ToDbConverter = toDbConverter; - } + public Func ToDbConverter { get; set; } } } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs b/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs index c3a1f9be247..c34ed47906e 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentMapper.cs @@ -46,11 +46,11 @@ public TableInfo GetTableInfo(Type pocoType) public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { var fluentMap = default(FluentColumnMap); - if (this.Mappings.TryGetValue(pocoProperty.Name, out fluentMap)) - { - return fluentMap.ColumnInfo; - } - + if (this.Mappings.TryGetValue(pocoProperty.Name, out fluentMap)) + { + return fluentMap.ColumnInfo; + } + return null; } @@ -58,11 +58,11 @@ public Func GetFromDbConverter(PropertyInfo targetProperty, Type { // ReSharper disable once RedundantAssignment var fluentMap = default(FluentColumnMap); - if (this.Mappings.TryGetValue(targetProperty.Name, out fluentMap)) - { - return fluentMap.FromDbConverter; - } - + if (this.Mappings.TryGetValue(targetProperty.Name, out fluentMap)) + { + return fluentMap.FromDbConverter; + } + return null; } @@ -70,11 +70,11 @@ public Func GetToDbConverter(PropertyInfo sourceProperty) { // ReSharper disable once RedundantAssignment var fluentMap = default(FluentColumnMap); - if (this.Mappings.TryGetValue(sourceProperty.Name, out fluentMap)) - { - return fluentMap.ToDbConverter; - } - + if (this.Mappings.TryGetValue(sourceProperty.Name, out fluentMap)) + { + return fluentMap.ToDbConverter; + } + return null; } diff --git a/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs b/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs index 61989f76a5e..e6b66c3d04a 100644 --- a/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs +++ b/DNN Platform/Library/Data/PetaPoco/FluentMapperExtensions.cs @@ -35,20 +35,20 @@ public static FluentMapper Cache(this FluentMapper mappe return mapper; } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, bool primaryKey = false, bool readOnly = false) - where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, bool primaryKey = false, bool readOnly = false) + where TModel : class { return mapper.Property(action, column, null, primaryKey, readOnly); } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, bool primaryKey = false, bool readOnly = false) - where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, bool primaryKey = false, bool readOnly = false) + where TModel : class { return mapper.Property(action, column, fromDbConverter, null, primaryKey, readOnly); } - public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, Func toDbConverter, bool primaryKey = false, bool readOnly = false) - where TModel : class + public static FluentMapper Property(this FluentMapper mapper, Expression> action, string column, Func fromDbConverter, Func toDbConverter, bool primaryKey = false, bool readOnly = false) + where TModel : class { var expression = (MemberExpression)action.Body; string name = expression.Member.Name; @@ -57,14 +57,14 @@ public static FluentMapper Property(this FluentMapper if (primaryKey) { - if (!string.IsNullOrEmpty(mapper.TableInfo.PrimaryKey)) - { - mapper.TableInfo.PrimaryKey += ","; - } - + if (!string.IsNullOrEmpty(mapper.TableInfo.PrimaryKey)) + { + mapper.TableInfo.PrimaryKey += ","; + } + mapper.TableInfo.PrimaryKey += column; } - + return mapper; } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs index 3edb093489d..b5d8f315af9 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoDataContext.cs @@ -14,10 +14,10 @@ namespace DotNetNuke.Data.PetaPoco [CLSCompliant(false)] public class PetaPocoDataContext : IDataContext - { + { private readonly Database _database; - private readonly IMapper _mapper; - + private readonly IMapper _mapper; + public PetaPocoDataContext() : this(ConfigurationManager.ConnectionStrings[0].Name, string.Empty) { @@ -41,18 +41,18 @@ public PetaPocoDataContext(string connectionStringName, string tablePrefix, Dict this._mapper = new PetaPocoMapper(tablePrefix); this.TablePrefix = tablePrefix; this.FluentMappers = mappers; - } - + } + public Dictionary FluentMappers { get; private set; } - public string TablePrefix { 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() { this._database.BeginTransaction(); @@ -105,8 +105,8 @@ public T ExecuteSingleOrDefault(CommandType type, string sql, params object[] return this._database.SingleOrDefault(DataUtil.ReplaceTokens(sql), args); } - public IRepository GetRepository() - where T : class + public IRepository GetRepository() + where T : class { PetaPocoRepository rep = null; @@ -131,11 +131,11 @@ public IRepository GetRepository() public void RollbackTransaction() { this._database.AbortTransaction(); - } - + } + public void Dispose() { this._database.Dispose(); - } + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs index 78f6ae9d857..6df07575f72 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoExt.cs @@ -30,10 +30,10 @@ public static IDataReader ExecuteReader(this Database database, string sql, para { throw; } - + reader = null; } - + return reader; } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoHelper.cs index d2957d2e824..1630038aa9f 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 const string SqlProviderName = "System.Data.SqlClient"; - + 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); @@ -62,16 +62,16 @@ public static void BulkInsert(string connectionString, int timeoutSec, string pr using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand(procedureName, con)) { - if (!tableParameterName.StartsWith("@")) - { - tableParameterName = "@" + tableParameterName; - } - - if (timeoutSec > 0) - { - cmd.CommandTimeout = timeoutSec; - } - + if (!tableParameterName.StartsWith("@")) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(tableParameterName, dataTable); con.Open(); @@ -84,12 +84,12 @@ public static void BulkInsert(string connectionString, int timeoutSec, string pr Logger.Error("[2] Error executing SQL: " + cmd.CommandText + Environment.NewLine + ex.Message); throw; } - + con.Close(); } } } - + public static void BulkInsert(string connectionString, string procedureName, string tableParameterName, DataTable dataTable, Dictionary args) { BulkInsert(connectionString, procedureName, tableParameterName, dataTable, Null.NullInteger, args); @@ -102,23 +102,23 @@ public static void BulkInsert(string connectionString, string procedureName, str using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand(procedureName, con)) { - if (!tableParameterName.StartsWith("@")) - { - tableParameterName = "@" + tableParameterName; - } - - if (timeoutSec > 0) - { - cmd.CommandTimeout = timeoutSec; - } - + if (!tableParameterName.StartsWith("@")) + { + tableParameterName = "@" + tableParameterName; + } + + if (timeoutSec > 0) + { + cmd.CommandTimeout = timeoutSec; + } + cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(tableParameterName, dataTable); foreach (var arg in args) { cmd.Parameters.AddWithValue(arg.Key, arg.Value); } - + con.Open(); try { @@ -129,7 +129,7 @@ public static void BulkInsert(string connectionString, string procedureName, str Logger.Error("[2] Error executing SQL: " + cmd.CommandText); throw; } - + con.Close(); } } @@ -165,7 +165,7 @@ public static IDataReader ExecuteReader(string connectionString, CommandType typ { Logger.Error("[3] Error executing SQL: " + sql + Environment.NewLine + ex.Message); } - + throw; } } @@ -227,6 +227,6 @@ public static void ExecuteSQL(string connectionString, string sql, int timeoutSe throw; } } - } + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs index a1135e2eaf5..c6a1b2a1d9d 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoMapper.cs @@ -20,8 +20,8 @@ public PetaPocoMapper(string tablePrefix) { this._tablePrefix = tablePrefix; _defaultMapper = new StandardMapper(); - } - + } + public static void SetMapper(IMapper mapper) { _lock.EnterWriteLock(); @@ -37,7 +37,7 @@ public static void SetMapper(IMapper mapper) _lock.ExitWriteLock(); } } - + public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) { bool includeColumn = true; @@ -58,7 +58,7 @@ public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty) if (pocoProperty.GetCustomAttributes(typeof(IgnoreColumnAttribute), true).Length > 0) { includeColumn = false; - } + } } ColumnInfo ci = null; @@ -98,6 +98,6 @@ public Func GetFromDbConverter(PropertyInfo pi, Type SourceType) public Func GetToDbConverter(PropertyInfo SourceProperty) { return null; - } + } } } diff --git a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs index 072057e91ef..3490d7e6aea 100644 --- a/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs +++ b/DNN Platform/Library/Data/PetaPoco/PetaPocoRepository.cs @@ -14,8 +14,8 @@ public class PetaPocoRepository : RepositoryBase where T : class { private readonly Database _database; - private readonly IMapper _mapper; - + private readonly IMapper _mapper; + public PetaPocoRepository(Database database, IMapper mapper) { Requires.NotNull("database", database); @@ -24,8 +24,8 @@ public PetaPocoRepository(Database database, IMapper mapper) this._mapper = mapper; PetaPocoMapper.SetMapper(mapper); - } - + } + public override void Delete(string sqlCondition, params object[] args) { this._database.Delete(DataUtil.ReplaceTokens(sqlCondition), args); @@ -43,7 +43,7 @@ public override IPagedList Find(int pageIndex, int pageSize, string sqlCondit { sqlCondition = string.Format("{0} ORDER BY {1}", sqlCondition, this._mapper.GetTableInfo(typeof(T)).PrimaryKey); } - + Page petaPocoPage = this._database.Page(pageIndex + 1, pageSize, DataUtil.ReplaceTokens(sqlCondition), args); return new PagedList(petaPocoPage.Items, (int)petaPocoPage.TotalItems, pageIndex, pageSize); @@ -52,8 +52,8 @@ public override IPagedList Find(int pageIndex, int pageSize, string sqlCondit public override void Update(string sqlCondition, params object[] args) { this._database.Update(DataUtil.ReplaceTokens(sqlCondition), args); - } - + } + protected override void DeleteInternal(T item) { this._database.Delete(item); diff --git a/DNN Platform/Library/Data/RepositoryBase.cs b/DNN Platform/Library/Data/RepositoryBase.cs index 2b335f04a08..e9f93f265d9 100644 --- a/DNN Platform/Library/Data/RepositoryBase.cs +++ b/DNN Platform/Library/Data/RepositoryBase.cs @@ -16,18 +16,20 @@ namespace DotNetNuke.Data public abstract class RepositoryBase : IRepository where T : class - { + { protected RepositoryBase() { this.InitializeInternal(); - } - + } + protected CacheItemArgs CacheArgs { get; private set; } protected string Scope { get; private set; } protected bool IsCacheable { get; private set; } - + + protected bool IsScoped { get; private set; } + public void Delete(T item) { this.DeleteInternal(item); @@ -103,63 +105,8 @@ public void Update(T item) this.ClearCache(item); } - public abstract void Update(string sqlCondition, params object[] args); - - private void CheckIfScoped() - { - if (!this.IsScoped) - { - throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined"); - } - } - - private void ClearCache(T item) - { - if (this.IsCacheable) - { - DataCache.RemoveCache(this.IsScoped - ? string.Format(this.CacheArgs.CacheKey, this.GetScopeValue(item)) - : this.CacheArgs.CacheKey); - } - } - - private void InitializeInternal() - { - var type = typeof(T); - this.Scope = string.Empty; - this.IsCacheable = false; - this.IsScoped = false; - this.CacheArgs = null; - - var scopeAttribute = DataUtil.GetAttribute(type); - if (scopeAttribute != null) - { - this.Scope = scopeAttribute.Scope; - } - - this.IsScoped = !string.IsNullOrEmpty(this.Scope); + public abstract void Update(string sqlCondition, params object[] args); - var cacheableAttribute = DataUtil.GetAttribute(type); - if (cacheableAttribute != null) - { - this.IsCacheable = true; - var cacheKey = !string.IsNullOrEmpty(cacheableAttribute.CacheKey) - ? cacheableAttribute.CacheKey - : string.Format("OR_{0}", type.Name); - var cachePriority = cacheableAttribute.CachePriority; - var cacheTimeOut = cacheableAttribute.CacheTimeOut; - - if (this.IsScoped) - { - cacheKey += "_" + this.Scope + "_{0}"; - } - - this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); - } - } - - protected bool IsScoped { get; private set; } - public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority cachePriority = CacheItemPriority.Default, string scope = "") { this.Scope = scope; @@ -171,7 +118,7 @@ public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority { cacheKey += "_" + this.Scope + "_{0}"; } - + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); } else @@ -179,19 +126,19 @@ public void Initialize(string cacheKey, int cacheTimeOut = 20, CacheItemPriority this.CacheArgs = null; } } - + protected int CompareTo(TProperty first, TProperty second) { Requires.IsTypeOf("first", first); Requires.IsTypeOf("second", second); var firstComparable = first as IComparable; - var secondComparable = second as IComparable; - - // ReSharper disable PossibleNullReferenceException - return firstComparable.CompareTo(secondComparable); - - // ReSharper restore PossibleNullReferenceException + var secondComparable = second as IComparable; + + // ReSharper disable PossibleNullReferenceException + return firstComparable.CompareTo(secondComparable); + + // ReSharper restore PossibleNullReferenceException } protected TProperty GetPropertyValue(T item, string propertyName) @@ -207,8 +154,8 @@ protected TProperty GetPrimaryKey(T item) protected TProperty GetScopeValue(T item) { return DataUtil.GetPropertyValue(item, this.Scope); - } - + } + protected abstract void DeleteInternal(T item); protected abstract IEnumerable GetInternal(); @@ -223,6 +170,59 @@ protected TProperty GetScopeValue(T item) protected abstract void InsertInternal(T item); - protected abstract void UpdateInternal(T item); + protected abstract void UpdateInternal(T item); + + private void CheckIfScoped() + { + if (!this.IsScoped) + { + throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined"); + } + } + + private void ClearCache(T item) + { + if (this.IsCacheable) + { + DataCache.RemoveCache(this.IsScoped + ? string.Format(this.CacheArgs.CacheKey, this.GetScopeValue(item)) + : this.CacheArgs.CacheKey); + } + } + + private void InitializeInternal() + { + var type = typeof(T); + this.Scope = string.Empty; + this.IsCacheable = false; + this.IsScoped = false; + this.CacheArgs = null; + + var scopeAttribute = DataUtil.GetAttribute(type); + if (scopeAttribute != null) + { + this.Scope = scopeAttribute.Scope; + } + + this.IsScoped = !string.IsNullOrEmpty(this.Scope); + + var cacheableAttribute = DataUtil.GetAttribute(type); + if (cacheableAttribute != null) + { + this.IsCacheable = true; + var cacheKey = !string.IsNullOrEmpty(cacheableAttribute.CacheKey) + ? cacheableAttribute.CacheKey + : string.Format("OR_{0}", type.Name); + var cachePriority = cacheableAttribute.CachePriority; + var cacheTimeOut = cacheableAttribute.CacheTimeOut; + + if (this.IsScoped) + { + cacheKey += "_" + this.Scope + "_{0}"; + } + + this.CacheArgs = new CacheItemArgs(cacheKey, cacheTimeOut, cachePriority); + } + } } } diff --git a/DNN Platform/Library/Data/SqlDataProvider.cs b/DNN Platform/Library/Data/SqlDataProvider.cs index de691cd3be6..781a362188b 100644 --- a/DNN Platform/Library/Data/SqlDataProvider.cs +++ b/DNN Platform/Library/Data/SqlDataProvider.cs @@ -19,10 +19,10 @@ namespace DotNetNuke.Data public sealed class SqlDataProvider : DataProvider { - private const string ScriptDelimiter = "(?<=(?:[^\\w]+|^))GO(?=(?: |\\t)*?(?:\\r?\\n|$))"; + 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 static DatabaseConnectionProvider _dbConnectionProvider = DatabaseConnectionProvider.Instance() ?? new SqlDatabaseConnectionProvider(); + public override bool IsConnectionValid { get @@ -37,8 +37,8 @@ public override Dictionary Settings { return ComponentFactory.GetComponentSettings() as Dictionary; } - } - + } + public override void ExecuteNonQuery(string procedureName, params object[] commandParameters) { _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); @@ -48,7 +48,136 @@ public override void ExecuteNonQuery(int timeoutSec, string procedureName, param { _dbConnectionProvider.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); } - + + public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable) + { + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); + } + + public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec) + { + _dbConnectionProvider.BulkInsert(this.ConnectionString, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); + } + + public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters) + { + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); + } + + public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary commandParameters) + { + _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); + } + + public override IDataReader ExecuteReader(string procedureName, params object[] commandParameters) + { + return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + + public override IDataReader ExecuteReader(int timeoutSec, string procedureName, params object[] commandParameters) + { + return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + + public override T ExecuteScalar(string procedureName, params object[] commandParameters) + { + return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + + public override T ExecuteScalar(int timeoutSec, string procedureName, params object[] commandParameters) + { + return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); + } + + public override string ExecuteScript(string script) + { + return this.ExecuteScript(script, 0); + } + + public override string ExecuteScript(string script, int timeoutSec) + { + string exceptions = this.ExecuteScriptInternal(this.UpgradeConnectionString, script, timeoutSec); + + // if the upgrade connection string is specified or or db_owner setting is not set to dbo + if (this.UpgradeConnectionString != this.ConnectionString || !this.DatabaseOwner.Trim().Equals("dbo.", StringComparison.InvariantCultureIgnoreCase)) + { + try + { + // grant execute rights to the public role or userid for all stored procedures. This is + // necesary because the UpgradeConnectionString will create stored procedures + // which restrict execute permissions for the ConnectionString user account. This is also + // necessary when db_owner is not set to "dbo" + exceptions += this.GrantStoredProceduresPermission("EXECUTE", this.GetConnectionStringUserID()); + } + catch (SqlException objException) + { + Logger.Error(objException); + + exceptions += objException + Environment.NewLine + Environment.NewLine + script + Environment.NewLine + Environment.NewLine; + } + + try + { + // grant execute or select rights to the public role or userid for all user defined functions based + // on what type of function it is (scalar function or table function). This is + // necesary because the UpgradeConnectionString will create user defined functions + // which restrict execute permissions for the ConnectionString user account. This is also + // necessary when db_owner is not set to "dbo" + exceptions += this.GrantUserDefinedFunctionsPermission("EXECUTE", "SELECT", this.GetConnectionStringUserID()); + } + catch (SqlException objException) + { + Logger.Error(objException); + + exceptions += objException + Environment.NewLine + Environment.NewLine + script + Environment.NewLine + Environment.NewLine; + } + } + + return exceptions; + } + + public override string ExecuteScript(string connectionString, string script) + { + return this.ExecuteScriptInternal(connectionString, script); + } + + public override string ExecuteScript(string connectionString, string script, int timeoutSec) + { + return this.ExecuteScriptInternal(connectionString, script, timeoutSec); + } + + public override IDataReader ExecuteSQL(string sql) + { + return this.ExecuteSQLInternal(this.ConnectionString, sql); + } + + public override IDataReader ExecuteSQL(string sql, int timeoutSec) + { + return this.ExecuteSQLInternal(this.ConnectionString, sql, timeoutSec); + } + + public override IDataReader ExecuteSQLTemp(string connectionString, string sql) + { + string errorMessage; + return this.ExecuteSQLTemp(connectionString, sql, out errorMessage); + } + + public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec) + { + string errorMessage; + return this.ExecuteSQLTemp(connectionString, sql, timeoutSec, out errorMessage); + } + + public override IDataReader ExecuteSQLTemp(string connectionString, string sql, out string errorMessage) + { + return this.ExecuteSQLInternal(connectionString, sql, 0, out errorMessage); + } + + public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage) + { + return this.ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); + } + private static bool CanConnect(string connectionString, string owner, string qualifier) { bool connectionValid = true; @@ -112,11 +241,11 @@ private IDataReader ExecuteSQLInternal(string connectionString, string sql, int sql = DataUtil.ReplaceTokens(sql); errorMessage = string.Empty; - if (string.IsNullOrEmpty(connectionString)) - { - throw new ArgumentNullException(nameof(connectionString)); - } - + if (string.IsNullOrEmpty(connectionString)) + { + throw new ArgumentNullException(nameof(connectionString)); + } + return _dbConnectionProvider.ExecuteSql(connectionString, CommandType.Text, timeoutSec, sql); } catch (SqlException sqlException) @@ -130,7 +259,7 @@ private IDataReader ExecuteSQLInternal(string connectionString, string sql, int Logger.Error(ex); errorMessage = ex.ToString(); } - + errorMessage += Environment.NewLine + Environment.NewLine + sql + Environment.NewLine + Environment.NewLine; return null; } @@ -158,7 +287,7 @@ private string GetConnectionStringUserID() } } } - + return DBUser; } @@ -241,137 +370,8 @@ private string ExecuteUpgradedConnectionQuery(string sql) exceptions += objException + Environment.NewLine + Environment.NewLine + sql + Environment.NewLine + Environment.NewLine; } - - return exceptions; - } - - public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable) - { - _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); - } - - public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec) - { - _dbConnectionProvider.BulkInsert(this.ConnectionString, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable); - } - - public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, Dictionary commandParameters) - { - _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); - } - - public override void BulkInsert(string procedureName, string tableParameterName, DataTable dataTable, int timeoutSec, Dictionary commandParameters) - { - _dbConnectionProvider.BulkInsert(this.ConnectionString, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, tableParameterName, dataTable, commandParameters); - } - - public override IDataReader ExecuteReader(string procedureName, params object[] commandParameters) - { - return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } - - public override IDataReader ExecuteReader(int timeoutSec, string procedureName, params object[] commandParameters) - { - return _dbConnectionProvider.ExecuteReader(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } - - public override T ExecuteScalar(string procedureName, params object[] commandParameters) - { - return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, 0, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } - - public override T ExecuteScalar(int timeoutSec, string procedureName, params object[] commandParameters) - { - return _dbConnectionProvider.ExecuteScalar(this.ConnectionString, CommandType.StoredProcedure, timeoutSec, this.DatabaseOwner + this.ObjectQualifier + procedureName, commandParameters); - } - - public override string ExecuteScript(string script) - { - return this.ExecuteScript(script, 0); - } - public override string ExecuteScript(string script, int timeoutSec) - { - string exceptions = this.ExecuteScriptInternal(this.UpgradeConnectionString, script, timeoutSec); - - // if the upgrade connection string is specified or or db_owner setting is not set to dbo - if (this.UpgradeConnectionString != this.ConnectionString || !this.DatabaseOwner.Trim().Equals("dbo.", StringComparison.InvariantCultureIgnoreCase)) - { - try - { - // grant execute rights to the public role or userid for all stored procedures. This is - // necesary because the UpgradeConnectionString will create stored procedures - // which restrict execute permissions for the ConnectionString user account. This is also - // necessary when db_owner is not set to "dbo" - exceptions += this.GrantStoredProceduresPermission("EXECUTE", this.GetConnectionStringUserID()); - } - catch (SqlException objException) - { - Logger.Error(objException); - - exceptions += objException + Environment.NewLine + Environment.NewLine + script + Environment.NewLine + Environment.NewLine; - } - - try - { - // grant execute or select rights to the public role or userid for all user defined functions based - // on what type of function it is (scalar function or table function). This is - // necesary because the UpgradeConnectionString will create user defined functions - // which restrict execute permissions for the ConnectionString user account. This is also - // necessary when db_owner is not set to "dbo" - exceptions += this.GrantUserDefinedFunctionsPermission("EXECUTE", "SELECT", this.GetConnectionStringUserID()); - } - catch (SqlException objException) - { - Logger.Error(objException); - - exceptions += objException + Environment.NewLine + Environment.NewLine + script + Environment.NewLine + Environment.NewLine; - } - } - return exceptions; } - - public override string ExecuteScript(string connectionString, string script) - { - return this.ExecuteScriptInternal(connectionString, script); - } - - public override string ExecuteScript(string connectionString, string script, int timeoutSec) - { - return this.ExecuteScriptInternal(connectionString, script, timeoutSec); - } - - public override IDataReader ExecuteSQL(string sql) - { - return this.ExecuteSQLInternal(this.ConnectionString, sql); - } - - public override IDataReader ExecuteSQL(string sql, int timeoutSec) - { - return this.ExecuteSQLInternal(this.ConnectionString, sql, timeoutSec); - } - - public override IDataReader ExecuteSQLTemp(string connectionString, string sql) - { - string errorMessage; - return this.ExecuteSQLTemp(connectionString, sql, out errorMessage); - } - - public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec) - { - string errorMessage; - return this.ExecuteSQLTemp(connectionString, sql, timeoutSec, out errorMessage); - } - - public override IDataReader ExecuteSQLTemp(string connectionString, string sql, out string errorMessage) - { - return this.ExecuteSQLInternal(connectionString, sql, 0, out errorMessage); - } - - public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage) - { - return this.ExecuteSQLInternal(connectionString, sql, timeoutSec, out errorMessage); - } } } diff --git a/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs b/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs index 5d7bcffc38a..9f4127b68ed 100644 --- a/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs +++ b/DNN Platform/Library/Data/SqlDatabaseConnectionProvider.cs @@ -16,11 +16,11 @@ public override int ExecuteNonQuery(string connectionString, CommandType command using (var connection = new SqlConnection(connectionString)) using (var command = new SqlCommand(query, connection)) { - if (commandTimeout > 0) - { - command.CommandTimeout = commandTimeout; - } - + if (commandTimeout > 0) + { + command.CommandTimeout = commandTimeout; + } + connection.Open(); try { diff --git a/DNN Platform/Library/DotNetNuke.Library.csproj b/DNN Platform/Library/DotNetNuke.Library.csproj index 6a73fd64eb6..dbae0799d72 100644 --- a/DNN Platform/Library/DotNetNuke.Library.csproj +++ b/DNN Platform/Library/DotNetNuke.Library.csproj @@ -754,6 +754,7 @@ + @@ -792,6 +793,7 @@ + diff --git a/DNN Platform/Library/Entities/BaseEntityInfo.cs b/DNN Platform/Library/Entities/BaseEntityInfo.cs index 5317e6ad3de..cf31ef9541c 100644 --- a/DNN Platform/Library/Entities/BaseEntityInfo.cs +++ b/DNN Platform/Library/Entities/BaseEntityInfo.cs @@ -35,7 +35,7 @@ protected BaseEntityInfo() /// /// An Integer. /// ----------------------------------------------------------------------------- - [Browsable(false)] + [Browsable(false)] [XmlIgnore] public int CreatedByUserID { get; internal set; } @@ -45,7 +45,7 @@ protected BaseEntityInfo() /// /// A DateTime. /// ----------------------------------------------------------------------------- - [Browsable(false)] + [Browsable(false)] [XmlIgnore] public DateTime CreatedOnDate { get; private set; } @@ -55,7 +55,7 @@ protected BaseEntityInfo() /// /// An Integer. /// ----------------------------------------------------------------------------- - [Browsable(false)] + [Browsable(false)] [XmlIgnore] public int LastModifiedByUserID { get; internal set; } @@ -65,7 +65,7 @@ protected BaseEntityInfo() /// /// A DateTime. /// ----------------------------------------------------------------------------- - [Browsable(false)] + [Browsable(false)] [XmlIgnore] public DateTime LastModifiedOnDate { get; private set; } @@ -83,7 +83,7 @@ public UserInfo CreatedByUser(int portalId) UserInfo user = UserController.GetUserById(portalId, this.CreatedByUserID); return user; } - + return null; } @@ -101,7 +101,7 @@ public UserInfo LastModifiedByUser(int portalId) UserInfo user = UserController.GetUserById(portalId, this.LastModifiedByUserID); return user; } - + return null; } diff --git a/DNN Platform/Library/Entities/Content/AttachmentController.cs b/DNN Platform/Library/Entities/Content/AttachmentController.cs index 4fe9da98180..38e08548b18 100644 --- a/DNN Platform/Library/Entities/Content/AttachmentController.cs +++ b/DNN Platform/Library/Entities/Content/AttachmentController.cs @@ -22,11 +22,12 @@ public class AttachmentController : IAttachmentController internal const string FilesKey = "Files"; internal const string ImageKey = "Images"; internal const string VideoKey = "Videos"; - + internal const string TitleKey = "Title"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AttachmentController)); - private readonly IContentController _contentController; - + private readonly IContentController _contentController; + public AttachmentController() : this(Util.GetContentController()) { @@ -46,15 +47,6 @@ 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) { @@ -95,7 +87,7 @@ public IList GetFilesByContent(int contentItemId) var files = this.GetFilesByContent(contentItemId, FilesKey); return files.Select(fileId => FileManager.Instance.GetFile(fileId)).ToList(); - } + } internal static void SerializeAttachmentMetadata(ContentItem contentItem) { @@ -144,8 +136,8 @@ internal static string SerializeFileInfo(IEnumerable files) } return fileList.ToJson(); - } - + } + private static void SerializeToMetadata(IList files, NameValueCollection nvc, string key) { var remove = !files.Any(); @@ -169,6 +161,15 @@ private static void SerializeToMetadata(IList files, NameValueCollect } } + private void AddToContent(int contentItemId, Action action) + { + var contentItem = this._contentController.GetContentItem(contentItemId); + + action(contentItem); + + this._contentController.UpdateContentItem(contentItem); + } + private IEnumerable GetFilesByContent(int contentItemId, string type) { var contentItem = this._contentController.GetContentItem(contentItemId); @@ -194,6 +195,5 @@ private IEnumerable GetFilesByContent(int contentItemId, string type) 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 60dfe004b90..852ce342780 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentExtensions.cs @@ -38,7 +38,7 @@ namespace DotNetNuke.Entities.Content.Common /// /// public static class ContentExtensions - { + { /// /// Toes the delimitted string. /// @@ -56,11 +56,11 @@ public static string ToDelimittedString(this List terms, string delimitter { sb.Append(delimitter); } - + sb.Append(_Term.Name); } } - + return sb.ToString(); } @@ -82,14 +82,14 @@ public static string ToDelimittedString(this List terms, string format, st { sb.Append(delimitter); } - + sb.Append(string.Format(format, _Term.Name)); } } - + return sb.ToString(); - } - + } + /// /// Gets the child terms. /// @@ -118,7 +118,7 @@ internal static Vocabulary GetVocabulary(this Term term, int vocabularyId) return (from v in ctl.GetVocabularies() where v.VocabularyId == vocabularyId select v).SingleOrDefault(); } - + /// /// Gets the type of the scope. /// @@ -143,8 +143,8 @@ internal static List GetTerms(this Vocabulary voc, int vocabularyId) ITermController ctl = Util.GetTermController(); return ctl.GetTermsByVocabulary(vocabularyId).ToList(); - } - + } + /// /// Gets the meta data. /// @@ -189,6 +189,6 @@ internal static List GetTerms(this ContentItem item, int contentItemId) } return _Terms; - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs b/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs index 482ca939565..f43a10c5ca3 100644 --- a/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs +++ b/DNN Platform/Library/Entities/Content/Common/ContentItemEqualityComparer.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Content.Common using System.Collections.Generic; internal class ContentItemEqualityComparer : IEqualityComparer - { + { public bool Equals(ContentItem x, ContentItem y) { return x.ContentItemId == y.ContentItemId; @@ -16,6 +16,6 @@ public bool Equals(ContentItem x, ContentItem y) public int GetHashCode(ContentItem obj) { return obj.ContentItemId.GetHashCode(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs b/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs index 53a7e905081..2cb3501328f 100644 --- a/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs +++ b/DNN Platform/Library/Entities/Content/Common/NameValueEqualityComparer.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Content.Common using System.Collections.Generic; internal class NameValueEqualityComparer : IEqualityComparer> - { + { public bool Equals(KeyValuePair x, KeyValuePair y) { return x.Key == y.Key && x.Value == y.Value; @@ -16,6 +16,6 @@ public bool Equals(KeyValuePair x, KeyValuePair public int GetHashCode(KeyValuePair obj) { return obj.Key.GetHashCode() ^ obj.Value.GetHashCode(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Common/Util.cs b/DNN Platform/Library/Entities/Content/Common/Util.cs index dc470846edf..5f1f6340134 100644 --- a/DNN Platform/Library/Entities/Content/Common/Util.cs +++ b/DNN Platform/Library/Entities/Content/Common/Util.cs @@ -25,7 +25,7 @@ public static IDataService GetDataService() ds = new DataService(); ComponentFactory.RegisterComponentInstance(ds); } - + return ds; } @@ -42,7 +42,7 @@ public static IContentController GetContentController() ctl = new ContentController(); ComponentFactory.RegisterComponentInstance(ctl); } - + return ctl; } @@ -59,7 +59,7 @@ public static IScopeTypeController GetScopeTypeController() ctl = new ScopeTypeController(); ComponentFactory.RegisterComponentInstance(ctl); } - + return ctl; } @@ -76,7 +76,7 @@ public static ITermController GetTermController() ctl = new TermController(); ComponentFactory.RegisterComponentInstance(ctl); } - + return ctl; } @@ -93,7 +93,7 @@ public static IVocabularyController GetVocabularyController() ctl = new VocabularyController(); ComponentFactory.RegisterComponentInstance(ctl); } - + return ctl; } } diff --git a/DNN Platform/Library/Entities/Content/ContentController.cs b/DNN Platform/Library/Entities/Content/ContentController.cs index 4e91d8cacc8..7d9c7085cc9 100644 --- a/DNN Platform/Library/Entities/Content/ContentController.cs +++ b/DNN Platform/Library/Entities/Content/ContentController.cs @@ -22,7 +22,7 @@ public class ContentController : ServiceLocator GetFactory() - { - return () => new ContentController(); - } - public void DeleteContentItem(ContentItem contentItem) { // Argument Contract @@ -116,9 +111,9 @@ 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. + } + + /// Get a list of content items by ContentType. /// public IQueryable GetContentItemsByContentType(ContentType contentType) { @@ -134,7 +129,7 @@ public IQueryable GetContentItemsByTerms(string[] terms) { var union = new List(); - union = terms.Aggregate( + union = terms.Aggregate( union, (current, term) => !current.Any() @@ -234,6 +229,11 @@ public NameValueCollection GetMetaData(int contentItemId) return metadata; } + protected override Func GetFactory() + { + return () => new ContentController(); + } + private static bool MetaDataChanged( IEnumerable> lh, IEnumerable> rh) @@ -246,13 +246,18 @@ private static void UpdateContentItemsCache(ContentItem contentItem, bool readdI DataCache.RemoveCache(GetContentItemCacheKey(contentItem.ContentItemId)); // remove first to synch web-farm servers if (readdItem) { - CBO.GetCachedObject( + 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); + } + private void SaveMetadataDelta(ContentItem contentItem) { var persisted = this.GetMetaData(contentItem.ContentItemId); @@ -276,10 +281,5 @@ private void SaveMetadataDelta(ContentItem contentItem) UpdateContentItemsCache(contentItem, false); } - - 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 5c56a31c1ef..894e8f2dc8a 100644 --- a/DNN Platform/Library/Entities/Content/ContentItem.cs +++ b/DNN Platform/Library/Entities/Content/ContentItem.cs @@ -75,8 +75,66 @@ public ContentItem() this.ContentTypeId = Null.NullInteger; this.ContentItemId = Null.NullInteger; this.StateID = Null.NullInteger; - } - + } + + /// + /// Gets the metadata. + /// + /// metadata collection. + [XmlIgnore] + [ScriptIgnore] + public NameValueCollection Metadata + { + get + { + return this._metadata ?? (this._metadata = this.GetMetaData(this.ContentItemId)); + } + } + + /// + /// Gets the terms. + /// + /// Terms Collection. + [XmlIgnore] + [ScriptIgnore] + public List Terms + { + get + { + return this._terms ?? (this._terms = this.GetTerms(this.ContentItemId)); + } + } + + /// + /// Gets files that are attached to this ContentItem. + /// + [XmlIgnore] + [ScriptIgnore] + public List Files + { + get { return this._files ?? (this._files = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.FilesKey]).ToList()); } + } + + /// + /// Gets video files attached to this ContentItem. + /// + [XmlIgnore] + [ScriptIgnore] + public List Videos + { + get { return this._videos ?? (this._videos = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.VideoKey]).ToList()); } + } + + /// + /// Gets images associated with this ContentItem. + /// + [XmlIgnore] + [ScriptIgnore] + public List Images + { + get { return this._images ?? (this._images = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.ImageKey]).ToList()); } + } + /// /// Gets or sets the content item id. /// @@ -126,20 +184,6 @@ public ContentItem() [ScriptIgnore] public bool Indexed { get; set; } - /// - /// Gets the metadata. - /// - /// metadata collection. - [XmlIgnore] - [ScriptIgnore] - public NameValueCollection Metadata - { - get - { - return this._metadata ?? (this._metadata = this.GetMetaData(this.ContentItemId)); - } - } - /// /// Gets or sets the module ID. /// @@ -158,20 +202,6 @@ public NameValueCollection Metadata [XmlElement("tabid")] public int TabID { get; set; } - /// - /// Gets the terms. - /// - /// Terms Collection. - [XmlIgnore] - [ScriptIgnore] - public List Terms - { - get - { - return this._terms ?? (this._terms = this.GetTerms(this.ContentItemId)); - } - } - /// Gets or sets the title of the ContentItem. [XmlElement("contentTitle")] public string ContentTitle @@ -180,43 +210,13 @@ public string ContentTitle { return this.Metadata[AttachmentController.TitleKey]; } - + set { this.Metadata[AttachmentController.TitleKey] = value; } } - /// - /// Gets files that are attached to this ContentItem. - /// - [XmlIgnore] - [ScriptIgnore] - public List Files - { - get { return this._files ?? (this._files = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.FilesKey]).ToList()); } - } - - /// - /// Gets video files attached to this ContentItem. - /// - [XmlIgnore] - [ScriptIgnore] - public List Videos - { - get { return this._videos ?? (this._videos = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.VideoKey]).ToList()); } - } - - /// - /// Gets images associated with this ContentItem. - /// - [XmlIgnore] - [ScriptIgnore] - public List Images - { - get { return this._images ?? (this._images = AttachmentController.DeserializeFileInfo(this.Metadata[AttachmentController.ImageKey]).ToList()); } - } - /// /// Gets or sets the Content Workflow State ID. /// @@ -224,7 +224,7 @@ public List Images /// The Content Workflow State ID. /// [XmlIgnore] - public int StateID { get; set; } + public int StateID { get; set; } /// /// Gets or sets the key ID. @@ -242,13 +242,13 @@ public virtual int KeyID { return this.ContentItemId; } - + set { this.ContentItemId = value; } - } - + } + /// /// Fill this content object will the information from data reader. /// @@ -258,7 +258,7 @@ public virtual void Fill(IDataReader dr) { this.FillInternal(dr); } - + /// /// Fills the internal. /// @@ -300,6 +300,6 @@ protected void Clone(ContentItem cloneItem, ContentItem originalItem) cloneItem.ContentKey = originalItem.ContentKey; cloneItem.Indexed = originalItem.Indexed; cloneItem.StateID = originalItem.StateID; - } + } } } diff --git a/DNN Platform/Library/Entities/Content/ContentType.cs b/DNN Platform/Library/Entities/Content/ContentType.cs index 9cbca0334c9..c2ba9da3db2 100644 --- a/DNN Platform/Library/Entities/Content/ContentType.cs +++ b/DNN Platform/Library/Entities/Content/ContentType.cs @@ -20,16 +20,16 @@ namespace DotNetNuke.Entities.Content /// [Serializable] public class ContentType : ContentTypeMemberNameFixer, IHydratable - { + { private const string desktopModuleContentTypeName = "DesktopModule"; private const string moduleContentTypeName = "Module"; - + private const string tabContentTypeName = "Tab"; + private static ContentType _desktopModule; private static ContentType _module; private static ContentType _tab; - private const string tabContentTypeName = "Tab"; - - public ContentType() + + public ContentType() : this(Null.NullString) { } @@ -38,8 +38,8 @@ public ContentType(string contentType) { this.ContentTypeId = Null.NullInteger; this.ContentType = contentType; - } - + } + public static ContentType DesktopModule { get @@ -62,15 +62,15 @@ public static ContentType Tab { return _tab ?? (_tab = new ContentTypeController().GetContentTypes().FirstOrDefault(type => type.ContentType == tabContentTypeName)); } - } - + } + /// /// Gets or sets the content type id. /// /// /// The content type id. /// - public int ContentTypeId { get; set; } + public int ContentTypeId { get; set; } /// /// Gets or sets the key ID. @@ -84,13 +84,13 @@ public int KeyID { return this.ContentTypeId; } - + set { this.ContentTypeId = value; } - } - + } + /// /// Fill this content object will the information from data reader. /// @@ -101,7 +101,7 @@ 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/ContentTypeController.cs b/DNN Platform/Library/Entities/Content/ContentTypeController.cs index 9c57927bc1d..eba2c375971 100644 --- a/DNN Platform/Library/Entities/Content/ContentTypeController.cs +++ b/DNN Platform/Library/Entities/Content/ContentTypeController.cs @@ -31,9 +31,9 @@ namespace DotNetNuke.Entities.Content /// public class ContentTypeController : IContentTypeController { - private readonly IDataService _DataService; - - public ContentTypeController() + private readonly IDataService _DataService; + + public ContentTypeController() : this(Util.GetDataService()) { } @@ -41,8 +41,8 @@ public ContentTypeController() public ContentTypeController(IDataService dataService) { this._DataService = dataService; - } - + } + /// /// Adds the type of the content. /// @@ -96,8 +96,8 @@ public void DeleteContentType(ContentType contentType) /// content type collection. public IQueryable GetContentTypes() { - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( DataCache.ContentTypesCacheKey, DataCache.ContentTypesCacheTimeOut, DataCache.ContentTypesCachePriority), @@ -122,6 +122,6 @@ public void UpdateContentType(ContentType contentType) // Refresh cached collection of types this.ClearContentTypeCache(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Data/DataService.cs b/DNN Platform/Library/Entities/Content/Data/DataService.cs index 70048ac1d56..4a961151ed0 100644 --- a/DNN Platform/Library/Entities/Content/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Content/Data/DataService.cs @@ -34,8 +34,8 @@ namespace DotNetNuke.Entities.Content.Data /// public class DataService : IDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - + private readonly DataProvider _provider = DataProvider.Instance(); + /// /// Adds the content item. /// @@ -44,7 +44,7 @@ public class DataService : IDataService /// content item id. public int AddContentItem(ContentItem contentItem, int createdByUserId) { - return this._provider.ExecuteScalar( + return this._provider.ExecuteScalar( "AddContentItem", contentItem.Content, contentItem.ContentTypeId, @@ -102,7 +102,7 @@ public IDataReader GetContentItemsByTerm(string term) /// /// Get a list of content items of the specified content type, . /// - /// The type of content items you are searching for. + /// The type of content items you are searching for. /// public IDataReader GetContentItemsByContentType(int contentTypeId) { @@ -112,7 +112,7 @@ public IDataReader GetContentItemsByContentType(int contentTypeId) /// /// Get a list of content items based on TabID (PageID). /// - /// The TabID (or "Page ID") that the content items are associated with. + /// The TabID (or "Page ID") that the content items are associated with. /// public IDataReader GetContentItemsByTabId(int tabId) { @@ -121,7 +121,7 @@ public IDataReader GetContentItemsByTabId(int tabId) /// /// Retrieve all content items associated with a articular Module ID, . - /// + /// /// public IDataReader GetContentItemsByModuleId(int moduleId) { @@ -130,7 +130,7 @@ public IDataReader GetContentItemsByModuleId(int moduleId) /// /// Retrieve a list of content items containg terms from the specified Vocabulary ID. - /// + /// /// public IDataReader GetContentItemsByVocabularyId(int vocabularyId) { @@ -153,7 +153,7 @@ public IDataReader GetUnIndexedContentItems() /// The created by user id. public void UpdateContentItem(ContentItem contentItem, int createdByUserId) { - this._provider.ExecuteNonQuery( + this._provider.ExecuteNonQuery( "UpdateContentItem", contentItem.ContentItemId, contentItem.Content, @@ -164,8 +164,8 @@ public void UpdateContentItem(ContentItem contentItem, int createdByUserId) contentItem.Indexed, createdByUserId, this._provider.GetNull(contentItem.StateID)); - } - + } + /// /// Adds the meta data. /// @@ -239,8 +239,8 @@ public void DeleteMetaData(ContentItem contentItem, string name, string value) public IDataReader GetMetaData(int contentItemId) { return this._provider.ExecuteReader("GetMetaData", contentItemId); - } - + } + /// /// Adds the type of the content. /// @@ -272,8 +272,8 @@ public IDataReader GetContentTypes() public void UpdateContentType(ContentType contentType) { this._provider.ExecuteNonQuery("UpdateContentType", contentType.ContentTypeId, contentType.ContentType); - } - + } + /// /// Adds the type of the scope. /// @@ -309,8 +309,8 @@ public IDataReader GetScopeTypes() public void UpdateScopeType(ScopeType scopeType) { this._provider.ExecuteNonQuery("UpdateScopeType", scopeType.ScopeTypeId, scopeType.ScopeType); - } - + } + /// /// Adds the heirarchical term. /// @@ -368,7 +368,7 @@ public IDataReader GetTerm(int termId) /// /// Retrieve term usage data for the specified Term ID, . - /// + /// /// public IDataReader GetTermUsage(int termId) { @@ -422,8 +422,8 @@ public void UpdateHeirarchicalTerm(Term term, int lastModifiedByUserId) public void UpdateSimpleTerm(Term term, int lastModifiedByUserId) { this._provider.ExecuteNonQuery("UpdateSimpleTerm", term.TermId, term.VocabularyId, term.Name, term.Description, term.Weight, lastModifiedByUserId); - } - + } + /// /// Adds the vocabulary. /// @@ -432,7 +432,7 @@ public void UpdateSimpleTerm(Term term, int lastModifiedByUserId) /// Vocabulary id. public int AddVocabulary(Vocabulary vocabulary, int createdByUserId) { - return this._provider.ExecuteScalar( + return this._provider.ExecuteScalar( "AddVocabulary", vocabulary.Type, vocabulary.Name, @@ -468,7 +468,7 @@ public IDataReader GetVocabularies() /// The last modified by user id. public void UpdateVocabulary(Vocabulary vocabulary, int lastModifiedByUserId) { - this._provider.ExecuteNonQuery( + this._provider.ExecuteNonQuery( "UpdateVocabulary", vocabulary.VocabularyId, vocabulary.Type, @@ -478,6 +478,6 @@ public void UpdateVocabulary(Vocabulary vocabulary, int lastModifiedByUserId) vocabulary.ScopeId, vocabulary.ScopeTypeId, lastModifiedByUserId); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Data/IDataService.cs b/DNN Platform/Library/Entities/Content/Data/IDataService.cs index 2ce355bd773..07e509026bd 100644 --- a/DNN Platform/Library/Entities/Content/Data/IDataService.cs +++ b/DNN Platform/Library/Entities/Content/Data/IDataService.cs @@ -45,7 +45,7 @@ public interface IDataService IDataReader GetMetaData(int contentItemId); - void SynchronizeMetaData( + void SynchronizeMetaData( ContentItem contentItem, IEnumerable> added, IEnumerable> deleted); diff --git a/DNN Platform/Library/Entities/Content/IContentController.cs b/DNN Platform/Library/Entities/Content/IContentController.cs index 113bcd371ae..9a40d509b87 100644 --- a/DNN Platform/Library/Entities/Content/IContentController.cs +++ b/DNN Platform/Library/Entities/Content/IContentController.cs @@ -54,37 +54,37 @@ public interface IContentController ContentItem GetContentItem(int contentItemId); /// Return ContentItems that have the specified term attached. - /// Term name is empty. + /// Term name is empty. /// IQueryable GetContentItemsByTerm(string term); /// Return ContentItems that have the specified term attached. - /// Term name is empty. + /// Term name is empty. /// IQueryable GetContentItemsByTerm(Term term); /// /// Get a list of content items by ContentType ID. /// - /// The Content Type ID of the content items we want to query. + /// The Content Type ID of the content items we want to query. /// IQueryable GetContentItemsByContentType(int contentTypeId); /// /// Get a list of content items by ContentType. /// - /// The Content Type of the content items we want to query. + /// The Content Type of the content items we want to query. /// IQueryable GetContentItemsByContentType(ContentType contentType); /// /// Return a list of ContentItems that have all of the specified terms attached. /// - /// A list of terms that should be attached to the ContentItems returned. + /// A list of terms that should be attached to the ContentItems returned. /// - IQueryable GetContentItemsByTerms(IList terms); - - /// Return a list of ContentItems that have all of the specified terms attached. + IQueryable GetContentItemsByTerms(IList terms); + + /// Return a list of ContentItems that have all of the specified terms attached. /// IQueryable GetContentItemsByTerms(string[] terms); @@ -97,20 +97,20 @@ public interface IContentController /// /// Retrieve all content items associated with the specified module ID, . /// - /// The module ID to use in the content item lookup. + /// The module ID to use in the content item lookup. /// IQueryable GetContentItemsByModuleId(int moduleId); /// /// Retrieve all content items on the specified page (tab). /// - /// The page ID to use in the lookup of content items. + /// The page ID to use in the lookup of content items. /// IQueryable GetContentItemsByTabId(int tabId); /// /// Get a list of content items tagged with terms from the specified Vocabulary ID. - /// + /// /// IQueryable GetContentItemsByVocabularyId(int vocabularyId); diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs index 74572ea423e..edf1eee11bb 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeType.cs @@ -27,7 +27,7 @@ public abstract class ScopeTypeMemberNameFixer [Serializable] public class ScopeType : ScopeTypeMemberNameFixer, IHydratable { - public ScopeType() + public ScopeType() : this(Null.NullString) { } @@ -46,7 +46,7 @@ public int KeyID { return this.ScopeTypeId; } - + set { this.ScopeTypeId = value; diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs index c59a0cf440e..a0d8834e100 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/ScopeTypeController.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.Entities.Content.Taxonomy /// public class ScopeTypeController : IScopeTypeController { - private const int _CacheTimeOut = 20; + private const int _CacheTimeOut = 20; private readonly IDataService _DataService; - - public ScopeTypeController() + + public ScopeTypeController() : this(Util.GetDataService()) { } @@ -28,8 +28,8 @@ public ScopeTypeController() public ScopeTypeController(IDataService dataService) { this._DataService = dataService; - } - + } + public int AddScopeType(ScopeType scopeType) { // Argument Contract @@ -48,11 +48,6 @@ public void ClearScopeTypeCache() { DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); } - - private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(this._DataService.GetScopeTypes()).ToList(); - } public void DeleteScopeType(ScopeType scopeType) { @@ -82,6 +77,11 @@ public void UpdateScopeType(ScopeType scopeType) // Refresh cached collection of types DataCache.RemoveCache(DataCache.ScopeTypesCacheKey); - } + } + + private object GetScopeTypesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetScopeTypes()).ToList(); + } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs index 2cb5d74112f..52b84866b61 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Term.cs @@ -49,6 +49,7 @@ namespace DotNetNuke.Entities.Content.Taxonomy public class Term : BaseEntityInfo, IHydratable { private static readonly PortalSecurity Security = PortalSecurity.Instance; + private readonly List _synonyms = new List(); private List _childTerms; private string _description; @@ -56,28 +57,27 @@ public class Term : BaseEntityInfo, IHydratable private string _name; private int? _parentTermId; private int _right; - private readonly List _synonyms = new List(); private int _termId; private Vocabulary _vocabulary; private int _vocabularyId; - private int _weight; - - public Term() + private int _weight; + + public Term() : this(Null.NullString, Null.NullString, Null.NullInteger) { } - public Term(int vocabularyId) + public Term(int vocabularyId) : this(Null.NullString, Null.NullString, vocabularyId) { } - public Term(string name) + public Term(string name) : this(name, Null.NullString, Null.NullInteger) { } - public Term(string name, string description) + public Term(string name, string description) : this(name, description, Null.NullInteger) { } @@ -93,8 +93,8 @@ public Term(string name, string description, int vocabularyId) this._left = 0; this._right = 0; this.Weight = 0; - } - + } + [XmlIgnore] [ScriptIgnore] public List ChildTerms @@ -105,143 +105,143 @@ public List ChildTerms { this._childTerms = this.GetChildTerms(this._termId, this._vocabularyId); } - + return this._childTerms; } } [XmlIgnore] [ScriptIgnore] - public string Description + public bool IsHeirarchical { get { - return this._description; - } - - set - { - this._description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + return this.Vocabulary.Type == VocabularyType.Hierarchy; } } [XmlIgnore] [ScriptIgnore] - public bool IsHeirarchical + public int Left { get { - return this.Vocabulary.Type == VocabularyType.Hierarchy; + return this._left; } } [XmlIgnore] [ScriptIgnore] - public int Left + public int Right { get { - return this._left; + return this._right; } } [XmlIgnore] [ScriptIgnore] - public string Name + public List Synonyms { get { - return this._name; - } - - set - { - if (HtmlUtils.IsUrlEncoded(value)) - { - value = System.Net.WebUtility.UrlDecode(value); - } - - if (HtmlUtils.ContainsEntity(value)) - { - value = System.Net.WebUtility.HtmlDecode(value); - } - - this._name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + return this._synonyms; } } [XmlIgnore] [ScriptIgnore] - public int? ParentTermId + public Vocabulary Vocabulary { get { - return this._parentTermId; - } - - set - { - this._parentTermId = value; + if (this._vocabulary == null && this._vocabularyId > Null.NullInteger) + { + this._vocabulary = this.GetVocabulary(this._vocabularyId); + } + + return this._vocabulary; } } [XmlIgnore] [ScriptIgnore] - public int Right + public int VocabularyId { get { - return this._right; + return this._vocabularyId; } } [XmlIgnore] [ScriptIgnore] - public List Synonyms + public string Description { get { - return this._synonyms; + return this._description; + } + + set + { + this._description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } [XmlIgnore] [ScriptIgnore] - public int TermId + public string Name { get { - return this._termId; + return this._name; } - + set { - this._termId = value; + if (HtmlUtils.IsUrlEncoded(value)) + { + value = System.Net.WebUtility.UrlDecode(value); + } + + if (HtmlUtils.ContainsEntity(value)) + { + value = System.Net.WebUtility.HtmlDecode(value); + } + + this._name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } [XmlIgnore] [ScriptIgnore] - public Vocabulary Vocabulary + public int? ParentTermId { get { - if (this._vocabulary == null && this._vocabularyId > Null.NullInteger) - { - this._vocabulary = this.GetVocabulary(this._vocabularyId); - } - - return this._vocabulary; + return this._parentTermId; + } + + set + { + this._parentTermId = value; } } [XmlIgnore] [ScriptIgnore] - public int VocabularyId + public int TermId { get { - return this._vocabularyId; + return this._termId; + } + + set + { + this._termId = value; } } @@ -253,12 +253,12 @@ public int Weight { return this._weight; } - + set { this._weight = value; } - } + } public int KeyID { @@ -266,13 +266,13 @@ public int KeyID { return this.TermId; } - + set { this.TermId = value; } - } - + } + public virtual void Fill(IDataReader dr) { this.TermId = Null.SetNullInteger(dr["TermID"]); @@ -285,12 +285,12 @@ public virtual void Fill(IDataReader dr) { this._left = Convert.ToInt32(dr["TermLeft"]); } - + if (dr["TermRight"] != DBNull.Value) { this._right = Convert.ToInt32(dr["TermRight"]); } - + if (dr["ParentTermID"] != DBNull.Value) { this.ParentTermId = Convert.ToInt32(dr["ParentTermID"]); @@ -299,7 +299,7 @@ public virtual void Fill(IDataReader dr) // Fill base class properties this.FillInternal(dr); } - + public string GetTermPath() { string path = "\\\\" + this.Name; @@ -315,7 +315,7 @@ public string GetTermPath() path = parentTerm.GetTermPath() + path; } } - + return path; } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs index 7111fc64d7b..e937480b279 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermController.cs @@ -30,10 +30,10 @@ namespace DotNetNuke.Entities.Content.Taxonomy public class TermController : ITermController { private const CacheItemPriority _CachePriority = CacheItemPriority.Normal; - private const int _CacheTimeOut = 20; + private const int _CacheTimeOut = 20; private readonly IDataService _DataService; - - public TermController() + + public TermController() : this(Util.GetDataService()) { } @@ -41,8 +41,8 @@ public TermController() public TermController(IDataService dataService) { this._DataService = dataService; - } - + } + /// /// Adds the term. /// @@ -90,12 +90,6 @@ 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. @@ -135,11 +129,11 @@ public Term GetTerm(int termId) return CBO.FillObject(this._DataService.GetTerm(termId)); } - + /// /// Retrieve usage data for the specified term ID. /// - /// Term ID in question. + /// Term ID in question. /// public TermUsage GetTermUsage(int termId) { @@ -240,6 +234,12 @@ public void UpdateTerm(Term term) // Clear Cache DataCache.RemoveCache(string.Format(DataCache.TermCacheKey, term.VocabularyId)); - } + } + + private object GetTermsCallBack(CacheItemArgs cacheItemArgs) + { + var vocabularyId = (int)cacheItemArgs.ParamList[0]; + return CBO.FillQueryable(this._DataService.GetTermsByVocabulary(vocabularyId)).ToList(); + } } } diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs index 8799294fb7e..bbff1da5c9b 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/TermUsage.cs @@ -6,7 +6,7 @@ namespace DotNetNuke.Entities.Content.Taxonomy { public class TermUsage { - /// + /// /// Initializes a new instance of the class. /// parameterless constructor, so that it can be used in CBO. /// @@ -24,13 +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; } + 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 9a03a6ffb25..b8ea237aff7 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/Vocabulary.cs @@ -31,24 +31,24 @@ public class Vocabulary : BaseEntityInfo, IHydratable private VocabularyType _Type; private int _VocabularyId; - private int _Weight; - - public Vocabulary() + private int _Weight; + + public Vocabulary() : this(Null.NullString, Null.NullString, VocabularyType.Simple) { } - public Vocabulary(string name) + public Vocabulary(string name) : this(name, Null.NullString, VocabularyType.Simple) { } - public Vocabulary(string name, string description) + public Vocabulary(string name, string description) : this(name, description, VocabularyType.Simple) { } - public Vocabulary(VocabularyType type) + public Vocabulary(VocabularyType type) : this(Null.NullString, Null.NullString, type) { } @@ -63,26 +63,52 @@ public Vocabulary(string name, string description, VocabularyType type) this.ScopeTypeId = Null.NullInteger; this.VocabularyId = Null.NullInteger; this.Weight = 0; - } - - public string Description + } + + public bool IsHeirarchical { get { - return this._Description; + return this.Type == VocabularyType.Hierarchy; } - - set + } + + public ScopeType ScopeType + { + get { - this._Description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); + if (this._ScopeType == null) + { + this._ScopeType = this.GetScopeType(this._ScopeTypeId); + } + + return this._ScopeType; } } - public bool IsHeirarchical + public List Terms { get { - return this.Type == VocabularyType.Hierarchy; + if (this._Terms == null) + { + this._Terms = this.GetTerms(this._VocabularyId); + } + + return this._Terms; + } + } + + public string Description + { + get + { + return this._Description; + } + + set + { + this._Description = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -92,7 +118,7 @@ public bool IsSystem { return this._IsSystem; } - + set { this._IsSystem = value; @@ -105,14 +131,14 @@ public string Name { return this._Name; } - + set { - if (HtmlUtils.ContainsEntity(value)) - { - value = System.Net.WebUtility.HtmlDecode(value); - } - + if (HtmlUtils.ContainsEntity(value)) + { + value = System.Net.WebUtility.HtmlDecode(value); + } + this._Name = Security.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } @@ -123,59 +149,33 @@ public int ScopeId { return this._ScopeId; } - + set { this._ScopeId = value; } } - public ScopeType ScopeType - { - get - { - if (this._ScopeType == null) - { - this._ScopeType = this.GetScopeType(this._ScopeTypeId); - } - - return this._ScopeType; - } - } - public int ScopeTypeId { get { return this._ScopeTypeId; } - + set { this._ScopeTypeId = value; } } - public List Terms - { - get - { - if (this._Terms == null) - { - this._Terms = this.GetTerms(this._VocabularyId); - } - - return this._Terms; - } - } - public VocabularyType Type { get { return this._Type; } - + set { this._Type = value; @@ -188,7 +188,7 @@ public int VocabularyId { return this._VocabularyId; } - + set { this._VocabularyId = value; @@ -201,12 +201,12 @@ public int Weight { return this._Weight; } - + set { this._Weight = value; } - } + } public virtual int KeyID { @@ -214,13 +214,13 @@ public virtual int KeyID { return this.VocabularyId; } - + set { this.VocabularyId = value; } - } - + } + public virtual void Fill(IDataReader dr) { this.VocabularyId = Null.SetNullInteger(dr["VocabularyID"]); @@ -233,7 +233,7 @@ public virtual void Fill(IDataReader dr) this.Type = VocabularyType.Hierarchy; break; } - + this.IsSystem = Null.SetNullBoolean(dr["IsSystem"]); this.Name = Null.SetNullString(dr["Name"]); this.Description = Null.SetNullString(dr["Description"]); diff --git a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs index ccc236cd91f..fa615d9b314 100644 --- a/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs +++ b/DNN Platform/Library/Entities/Content/Taxonomy/VocabularyController.cs @@ -18,10 +18,10 @@ namespace DotNetNuke.Entities.Content.Taxonomy /// public class VocabularyController : IVocabularyController { - private const int _CacheTimeOut = 20; + private const int _CacheTimeOut = 20; private readonly IDataService _DataService; - - public VocabularyController() + + public VocabularyController() : this(Util.GetDataService()) { } @@ -29,8 +29,8 @@ public VocabularyController() public VocabularyController(IDataService dataService) { this._DataService = dataService; - } - + } + public int AddVocabulary(Vocabulary vocabulary) { // Argument Contract @@ -50,11 +50,6 @@ public void ClearVocabularyCache() { DataCache.RemoveCache(DataCache.VocabularyCacheKey); } - - private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillQueryable(this._DataService.GetVocabularies()).ToList(); - } public void DeleteVocabulary(Vocabulary vocabulary) { @@ -84,6 +79,11 @@ public void UpdateVocabulary(Vocabulary vocabulary) DataCache.RemoveCache(DataCache.VocabularyCacheKey); this._DataService.UpdateVocabulary(vocabulary, UserController.Instance.GetCurrentUserInfo().UserID); - } + } + + private object GetVocabulariesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillQueryable(this._DataService.GetVocabularies()).ToList(); + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs index 92b47be73e9..d923945af4b 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Actions/WorkflowActionManager.cs @@ -11,14 +11,14 @@ namespace DotNetNuke.Entities.Content.Workflow.Actions using DotNetNuke.Framework; public class WorkflowActionManager : ServiceLocator, IWorkflowActionManager - { - private readonly IWorkflowActionRepository _workflowActionRepository; - + { + private readonly IWorkflowActionRepository _workflowActionRepository; + public WorkflowActionManager() { this._workflowActionRepository = WorkflowActionRepository.Instance; - } - + } + public IWorkflowAction GetWorkflowActionInstance(int contentTypeId, WorkflowActionTypes actionType) { var action = this._workflowActionRepository.GetWorkflowAction(contentTypeId, actionType.ToString()); @@ -41,11 +41,11 @@ public void RegisterWorkflowAction(WorkflowAction workflowAction) } this._workflowActionRepository.AddWorkflowAction(workflowAction); - } - + } + protected override Func GetFactory() { return () => new WorkflowActionManager(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs index bb9be995435..91227a15d64 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Entities/Workflow.cs @@ -19,6 +19,30 @@ namespace DotNetNuke.Entities.Content.Workflow.Entities [Serializable] public class Workflow { + /// + /// Gets first workflow state. + /// + [IgnoreColumn] + public WorkflowState FirstState + { + get + { + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).FirstOrDefault(); + } + } + + /// + /// Gets last workflow state. + /// + [IgnoreColumn] + public WorkflowState LastState + { + get + { + return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).LastOrDefault(); + } + } + /// /// Gets or sets workflow Id. /// @@ -58,29 +82,5 @@ public class Workflow /// [IgnoreColumn] public IEnumerable States { get; internal set; } - - /// - /// Gets first workflow state. - /// - [IgnoreColumn] - public WorkflowState FirstState - { - get - { - return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).FirstOrDefault(); - } - } - - /// - /// Gets last workflow state. - /// - [IgnoreColumn] - public WorkflowState LastState - { - get - { - return this.States == null || !this.States.Any() ? null : this.States.OrderBy(s => s.Order).LastOrDefault(); - } - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs index a8b1166627d..e215f37fd03 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowException.cs @@ -12,12 +12,12 @@ public WorkflowException() { } - public WorkflowException(string message) + public WorkflowException(string message) : base(message) { } - public WorkflowException(string message, Exception innerException) + public WorkflowException(string message, Exception innerException) : base(message, innerException) { } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs index 3e40c7c2334..d96e93802ff 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Exceptions/WorkflowSecurityException.cs @@ -6,9 +6,9 @@ namespace DotNetNuke.Entities.Content.Workflow.Exceptions { public class WorkflowSecurityException : WorkflowException { - public WorkflowSecurityException(string message) + public WorkflowSecurityException(string message) : base(message) - { - } + { + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs index daf30addc87..10a16cac639 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/IWorkflowEngine.cs @@ -95,7 +95,7 @@ public interface IWorkflowEngine /// State transaction Dto. /// Thrown when the current state of the workflow is not the same of the current state specified in the StateTransaction Dto. void CompleteWorkflow(StateTransaction stateTransaction); - + /// /// This method returns the user that started the workflow for the contentItem. /// diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs index bec2699951e..8e7114dc616 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowController.cs @@ -32,8 +32,8 @@ public class ContentWorkflowController : ComponentBase GetWorkflowLogs(int contentItemId, int wo public void DeleteWorkflowLogs(int contentItemID, int workflowID) { DataProvider.Instance().DeleteContentWorkflowLogs(contentItemID, workflowID); - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflowStatePermissionByState(int stateID) { @@ -218,7 +218,7 @@ public IEnumerable GetWorkflowStatePermissionByS [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { - DataProvider.Instance().AddContentWorkflowStatePermission( + DataProvider.Instance().AddContentWorkflowStatePermission( permission.StateID, permission.PermissionID, permission.RoleID, @@ -230,7 +230,7 @@ public void AddWorkflowStatePermission(ContentWorkflowStatePermission permission [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permission, int lastModifiedByUserID) { - DataProvider.Instance().UpdateContentWorkflowStatePermission( + DataProvider.Instance().UpdateContentWorkflowStatePermission( permission.WorkflowStatePermissionID, permission.StateID, permission.PermissionID, @@ -244,8 +244,8 @@ public void UpdateWorkflowStatePermission(ContentWorkflowStatePermission permiss public void DeleteWorkflowStatePermission(int workflowStatePermissionID) { DataProvider.Instance().DeleteContentWorkflowStatePermission(workflowStatePermissionID); - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public ContentWorkflowState GetWorkflowStateByID(int stateID) { @@ -255,7 +255,7 @@ public ContentWorkflowState GetWorkflowStateByID(int stateID) [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void AddWorkflowState(ContentWorkflowState state) { - var id = DataProvider.Instance().AddContentWorkflowState( + var id = DataProvider.Instance().AddContentWorkflowState( state.WorkflowID, state.StateName, state.Order, @@ -273,7 +273,7 @@ public void AddWorkflowState(ContentWorkflowState state) [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowStateManager. Scheduled removal in v10.0.0.")] public void UpdateWorkflowState(ContentWorkflowState state) { - DataProvider.Instance().UpdateContentWorkflowState( + DataProvider.Instance().UpdateContentWorkflowState( state.StateID, state.StateName, state.Order, @@ -291,8 +291,8 @@ public void UpdateWorkflowState(ContentWorkflowState state) public IEnumerable GetWorkflowStates(int workflowID) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStates(workflowID)); - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowManager. Scheduled removal in v10.0.0.")] public IEnumerable GetWorkflows(int portalID) { @@ -303,11 +303,11 @@ public IEnumerable GetWorkflows(int portalID) public ContentWorkflow GetWorkflow(ContentItem item) { var state = this.GetWorkflowStateByID(item.StateID); - if (state == null) - { - return null; - } - + if (state == null) + { + return null; + } + return this.GetWorkflowByID(state.WorkflowID); } @@ -333,10 +333,10 @@ public ContentWorkflow GetWorkflowByID(int workflowID) workflow.States = this.GetWorkflowStates(workflowID); return workflow; } - + return null; - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead ISystemWorkflowManager. Scheduled removal in v10.0.0.")] public void CreateDefaultWorkflows(int portalId) { @@ -439,8 +439,8 @@ public ContentWorkflow GetDefaultWorkflow(int portalID) var wf = this.GetWorkflows(portalID).First(); // We assume there is only 1 Workflow. This needs to be changed for other scenarios wf.States = this.GetWorkflowStates(wf.WorkflowID); return wf; - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Use instead IWorkflowSecurity. Scheduled removal in v10.0.0.")] public bool IsAnyReviewer(int workflowID) { @@ -485,8 +485,8 @@ public bool IsCurrentReviewer(int itemID) { var item = this.contentController.GetContentItem(itemID); return this.IsReviewer(item.StateID); - } - + } + [Obsolete("Deprecated in Platform 7.4.0. Scheduled removal in v10.0.0.")] public ContentWorkflowSource GetWorkflowSource(int workflowId, string sourceName) { @@ -500,7 +500,7 @@ public void SendWorkflowNotification(bool sendEmail, bool sendMessage, PortalSet var replacedSubject = this.ReplaceNotificationTokens(subject, null, null, null, settings.PortalId, userID); 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) { @@ -525,7 +525,7 @@ private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo { return users.All(u => u.UserID != superUser.UserID); } - + private void AddWorkflowCommentLog(ContentItem item, string userComment, int userID) { var workflow = this.GetWorkflow(item); @@ -540,7 +540,7 @@ private void SendNotification(bool sendEmail, bool sendMessage, PortalSettings s { this.SendEmailNotifications(settings, roles, users, subject, body, comment); } - + if (sendMessage) { this.SendMessageNotifications(settings, roles, users, subject, body, comment, userID, source, parameters); @@ -583,7 +583,7 @@ private void SendMessageNotifications(PortalSettings settings, IEnumerable GetRolesFromPermissions(PortalSettings settings, I var adminRole = RoleController.Instance.GetRoleByName(settings.PortalId, settings.AdministratorRoleName); roles.Add(adminRole); } - + return roles; } @@ -642,7 +642,7 @@ private IEnumerable GetUsersFromPermissions(PortalSettings settings, I users.Add(UserController.GetUserById(settings.PortalId, permission.UserID)); } } - + return IncludeSuperUsers(users); } @@ -686,7 +686,7 @@ private int GetFirstWorkflowStateID(ContentWorkflow workflow) { intStateID = states.OrderBy(s => s.Order).FirstOrDefault().StateID; } - + return intStateID; } @@ -698,7 +698,7 @@ private int GetLastWorkflowStateID(ContentWorkflow workflow) { intStateID = states.OrderBy(s => s.Order).LastOrDefault().StateID; } - + return intStateID; } @@ -715,7 +715,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) { intPreviousStateID = initState.StateID; } - + for (int i = 0; i < states.Count(); i++) { if (states.ElementAt(i).StateID == stateID) @@ -724,7 +724,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) intItem = i; } } - + // get previous active state if (intPreviousStateID == stateID) { @@ -736,7 +736,7 @@ private int GetPreviousWorkflowStateID(ContentWorkflow workflow, int stateID) intPreviousStateID = states.ElementAt(intItem).StateID; break; } - + intItem = intItem - 1; } } @@ -777,7 +777,7 @@ private int GetNextWorkflowStateID(ContentWorkflow workflow, int stateID) intNextStateID = states.ElementAt(intItem).StateID; break; } - + intItem = intItem + 1; } } @@ -802,6 +802,6 @@ private bool IsWorkflowCompleted(ContentWorkflow workflow, ContentItem item) var endStateID = this.GetLastWorkflowStateID(workflow); return item.StateID == Null.NullInteger || endStateID == item.StateID; - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs index c9299a707f6..98c2571b5a1 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Obsolete/ContentWorkflowState.cs @@ -34,7 +34,7 @@ public class ContentWorkflowState /// Gets or sets state Order. /// public int Order { get; set; } - + public bool IsActive { get; set; } public bool SendEmail { get; set; } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs index ff7dbd09d28..f7017d71304 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowLogRepository.cs @@ -30,7 +30,7 @@ internal interface IWorkflowLogRepository /// This method gets all the Content workflow logs. /// /// Content item Id. - /// Workflow Id. + /// Workflow Id. /// IEnumerable GetWorkflowLogs(int contentItemId, int workflowId); } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs index fbb1da588d8..527e89aa4d0 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/IWorkflowStatePermissionsRepository.cs @@ -24,7 +24,7 @@ internal interface IWorkflowStatePermissionsRepository /// Persists a new Workflow State Permission entity. /// /// Workflow State Permission entity. - /// User Id who modifies the permissions set. + /// User Id who modifies the permissions set. /// int AddWorkflowStatePermission(WorkflowStatePermission permission, int lastModifiedByUserId); diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs index 045ef053138..ddb61d214cf 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowActionRepository.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories using DotNetNuke.Framework; internal class WorkflowActionRepository : ServiceLocator, IWorkflowActionRepository - { + { public WorkflowAction GetWorkflowAction(int contentTypeId, string type) { using (var context = DataContext.Instance()) @@ -29,11 +29,11 @@ public void AddWorkflowAction(WorkflowAction action) var rep = context.GetRepository(); rep.Insert(action); } - } - + } + protected override Func GetFactory() { return () => new WorkflowActionRepository(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs index 1a59897a45c..b81fe753677 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowLogRepository.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories using DotNetNuke.Framework; internal class WorkflowLogRepository : ServiceLocator, IWorkflowLogRepository - { + { public IEnumerable GetWorkflowLogs(int contentItemId, int workflowId) { using (var context = DataContext.Instance()) @@ -42,11 +42,11 @@ public void AddWorkflowLog(WorkflowLog workflowLog) rep.Insert(workflowLog); } - } - + } + protected override Func GetFactory() { return () => new WorkflowLogRepository(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs index 6ce3039c9c7..7d98c438118 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowRepository.cs @@ -16,14 +16,14 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories // TODO: add interface metadata documentation // TODO: removed unused SPRoc and DataProvider layer internal class WorkflowRepository : ServiceLocator, IWorkflowRepository - { - private readonly IWorkflowStateRepository _stateRepository; - + { + private readonly IWorkflowStateRepository _stateRepository; + public WorkflowRepository() { this._stateRepository = WorkflowStateRepository.Instance; - } - + } + public IEnumerable GetWorkflows(int portalId) { using (var context = DataContext.Instance()) @@ -60,7 +60,7 @@ public WorkflowRepository() public Entities.Workflow GetWorkflow(int workflowId) { - return CBO.GetCachedObject( + return CBO.GetCachedObject( new CacheItemArgs( GetWorkflowItemKey(workflowId), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => @@ -99,7 +99,7 @@ public void AddWorkflow(Entities.Workflow workflow) { throw new WorkflowNameAlreadyExistsException(); } - + rep.Insert(workflow); } @@ -117,7 +117,7 @@ public void UpdateWorkflow(Entities.Workflow workflow) { throw new WorkflowNameAlreadyExistsException(); } - + rep.Update(workflow); } @@ -134,18 +134,18 @@ 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) { return rep.Find( @@ -157,11 +157,11 @@ private static void CacheWorkflow(Entities.Workflow workflow) { if (workflow.WorkflowID > 0) { - CBO.GetCachedObject( - new CacheItemArgs( + CBO.GetCachedObject( + new CacheItemArgs( GetWorkflowItemKey(workflow.WorkflowID), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => workflow); } - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs index d9be683435d..2f804d7d414 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStatePermissionsRepository.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories using DotNetNuke.Framework; internal class WorkflowStatePermissionsRepository : ServiceLocator, IWorkflowStatePermissionsRepository - { + { public IEnumerable GetWorkflowStatePermissionByState(int stateId) { return CBO.FillCollection(DataProvider.Instance().GetContentWorkflowStatePermissionsByStateID(stateId)); @@ -21,7 +21,7 @@ public IEnumerable GetWorkflowStatePermissionByState(in public int AddWorkflowStatePermission(WorkflowStatePermission permission, int lastModifiedByUserId) { - return DataProvider.Instance().AddContentWorkflowStatePermission( + return DataProvider.Instance().AddContentWorkflowStatePermission( permission.StateID, permission.PermissionID, permission.RoleID, @@ -33,11 +33,11 @@ public int AddWorkflowStatePermission(WorkflowStatePermission permission, int la public void DeleteWorkflowStatePermission(int workflowStatePermissionId) { DataProvider.Instance().DeleteContentWorkflowStatePermission(workflowStatePermissionId); - } - + } + protected override Func GetFactory() { return () => new WorkflowStatePermissionsRepository(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs index 25e43ecef37..05039e0b401 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/Repositories/WorkflowStateRepository.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Entities.Content.Workflow.Repositories using DotNetNuke.Framework; internal class WorkflowStateRepository : ServiceLocator, IWorkflowStateRepository - { + { public IEnumerable GetWorkflowStates(int workflowId) { using (var context = DataContext.Instance()) @@ -28,7 +28,7 @@ public IEnumerable GetWorkflowStates(int workflowId) public WorkflowState GetWorkflowStateByID(int stateId) { - return CBO.GetCachedObject( + return CBO.GetCachedObject( new CacheItemArgs( GetWorkflowStateKey(stateId), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => @@ -95,13 +95,13 @@ public void DeleteWorkflowState(WorkflowState state) DataCache.RemoveCache(GetWorkflowStateKey(state.StateID)); DataCache.RemoveCache(WorkflowRepository.GetWorkflowItemKey(state.WorkflowID)); - } - + } + protected override Func GetFactory() { return () => new WorkflowStateRepository(); - } - + } + private static bool DoesExistWorkflowState(WorkflowState state, IRepository rep) { return rep.Find( @@ -118,11 +118,11 @@ private void CacheWorkflowState(WorkflowState state) { if (state.StateID > 0) { - CBO.GetCachedObject( + CBO.GetCachedObject( new CacheItemArgs( GetWorkflowStateKey(state.StateID), DataCache.WorkflowsCacheTimeout, DataCache.WorkflowsCachePriority), _ => state); } - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs index 4bbbf358a2f..eb19c78a317 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/SystemWorkflowManager.cs @@ -13,19 +13,19 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Localization; public class SystemWorkflowManager : ServiceLocator, ISystemWorkflowManager - { + { public const string DirectPublishWorkflowKey = "DirectPublish"; public const string SaveDraftWorkflowKey = "SaveDraft"; - public const string ContentAprovalWorkflowKey = "ContentApproval"; + public const string ContentAprovalWorkflowKey = "ContentApproval"; private readonly IWorkflowRepository _workflowRepository; - private readonly IWorkflowStateRepository _workflowStateRepository; - + private readonly IWorkflowStateRepository _workflowStateRepository; + public SystemWorkflowManager() { this._workflowRepository = WorkflowRepository.Instance; this._workflowStateRepository = WorkflowStateRepository.Instance; - } - + } + public void CreateSystemWorkflows(int portalId) { this.CreateDirectPublishWorkflow(portalId); @@ -37,7 +37,45 @@ public Entities.Workflow GetDirectPublishWorkflow(int portalId) { return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == DirectPublishWorkflowKey); } - + + public Entities.Workflow GetSaveDraftWorkflow(int portalId) + { + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == SaveDraftWorkflowKey); + } + + public Entities.Workflow GetContentApprovalWorkflow(int portalId) + { + return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == ContentAprovalWorkflowKey); + } + + public WorkflowState GetDraftStateDefinition(int order) + { + var state = this.GetDefaultWorkflowState(order); + state.StateName = Localization.GetString("DefaultWorkflowState1.StateName"); + return state; + } + + public WorkflowState GetPublishedStateDefinition(int order) + { + var state = this.GetDefaultWorkflowState(order); + state.StateName = Localization.GetString("DefaultWorkflowState3.StateName"); + return state; + } + + public WorkflowState GetReadyForReviewStateDefinition(int order) + { + var state = this.GetDefaultWorkflowState(order); + state.StateName = Localization.GetString("DefaultWorkflowState2.StateName"); + state.SendNotification = true; + state.SendNotificationToAdministrators = true; + return state; + } + + protected override Func GetFactory() + { + return () => new SystemWorkflowManager(); + } + private WorkflowState GetDefaultWorkflowState(int order) { return new WorkflowState @@ -109,44 +147,6 @@ private void CreateContentApprovalWorkflow(int portalId) state = this.GetPublishedStateDefinition(3); state.WorkflowID = workflow.WorkflowID; this._workflowStateRepository.AddWorkflowState(state); - } - - public Entities.Workflow GetSaveDraftWorkflow(int portalId) - { - return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == SaveDraftWorkflowKey); - } - - public Entities.Workflow GetContentApprovalWorkflow(int portalId) - { - return this._workflowRepository.GetSystemWorkflows(portalId).SingleOrDefault(sw => sw.WorkflowKey == ContentAprovalWorkflowKey); - } - - public WorkflowState GetDraftStateDefinition(int order) - { - var state = this.GetDefaultWorkflowState(order); - state.StateName = Localization.GetString("DefaultWorkflowState1.StateName"); - return state; - } - - public WorkflowState GetPublishedStateDefinition(int order) - { - var state = this.GetDefaultWorkflowState(order); - state.StateName = Localization.GetString("DefaultWorkflowState3.StateName"); - return state; } - - public WorkflowState GetReadyForReviewStateDefinition(int order) - { - var state = this.GetDefaultWorkflowState(order); - state.StateName = Localization.GetString("DefaultWorkflowState2.StateName"); - state.SendNotification = true; - state.SendNotificationToAdministrators = true; - return state; - } - - protected override Func GetFactory() - { - return () => new SystemWorkflowManager(); - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs index 5a8956f79be..81565f79a01 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowEngine.cs @@ -25,10 +25,10 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Social.Notifications; public class WorkflowEngine : ServiceLocator, IWorkflowEngine - { + { private const string ContentWorkflowNotificationType = "ContentWorkflowNotification"; private const string ContentWorkflowNotificationNoActionType = "ContentWorkflowNoActionNotification"; - private const string ContentWorkflowNotificatioStartWorkflowType = "ContentWorkflowStartWorkflowNotification"; + private const string ContentWorkflowNotificatioStartWorkflowType = "ContentWorkflowStartWorkflowNotification"; private readonly IContentController _contentController; private readonly IWorkflowRepository _workflowRepository; private readonly IWorkflowStateRepository _workflowStateRepository; @@ -40,8 +40,8 @@ public class WorkflowEngine : ServiceLocator, I private readonly INotificationsController _notificationsController; private readonly IWorkflowManager _workflowManager; private readonly IWorkflowLogger _workflowLogger; - private readonly ISystemWorkflowManager _systemWorkflowManager; - + private readonly ISystemWorkflowManager _systemWorkflowManager; + public WorkflowEngine() { this._contentController = Util.GetContentController(); @@ -56,8 +56,8 @@ public WorkflowEngine() this._workflowManager = WorkflowManager.Instance; this._workflowLogger = WorkflowLogger.Instance; this._systemWorkflowManager = SystemWorkflowManager.Instance; - } - + } + public UserInfo GetStartedDraftStateUser(ContentItem contentItem) { return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.WorkflowStarted); @@ -68,10 +68,267 @@ public UserInfo GetSubmittedDraftStateUser(ContentItem contentItem) return this.GetUserByWorkflowLogType(contentItem, WorkflowLogType.DraftCompleted); } + public void StartWorkflow(int workflowId, int contentItemId, int userId) + { + Requires.NotNegative("workflowId", workflowId); + + var contentItem = this._contentController.GetContentItem(contentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); + + // If already exists a started workflow + if (workflow != null && !this.IsWorkflowCompleted(contentItem)) + { + throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowAlreadyStarted", "Workflow cannot get started for this Content Item. It already has a started workflow.")); + } + + if (workflow == null || workflow.WorkflowID != workflowId) + { + workflow = this._workflowRepository.GetWorkflow(workflowId); + } + + var initialTransaction = this.CreateInitialTransaction(contentItemId, workflow.FirstState.StateID, userId); + + // Perform action before starting workflow + this.PerformWorkflowActionOnStateChanging(initialTransaction, WorkflowActionTypes.StartWorkflow); + this.UpdateContentItemWorkflowState(workflow.FirstState.StateID, contentItem); + + // Send notifications to stater + if (workflow.WorkflowID != this._systemWorkflowManager.GetDirectPublishWorkflow(workflow.PortalID).WorkflowID) // This notification is not sent in Direct Publish WF + { + this.SendNotificationToWorkflowStarter(initialTransaction, workflow, contentItem, userId, WorkflowActionTypes.StartWorkflow); + } + + // Delete previous logs + this._workflowLogRepository.DeleteWorkflowLogs(contentItemId, workflowId); + + // Add logs + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowStarted, userId); + this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, userId); + + // Perform action after starting workflow + this.PerformWorkflowActionOnStateChanged(initialTransaction, WorkflowActionTypes.StartWorkflow); + } + + public void CompleteState(StateTransaction stateTransaction) + { + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); + + if (workflow == null) + { + return; + } + + if (this.IsWorkflowCompleted(contentItem) + && !(workflow.IsSystem && workflow.States.Count() == 1)) + { + throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowSystemWorkflowStateCannotComplete", "System workflow state cannot be completed.")); + } + + var isFirstState = workflow.FirstState.StateID == contentItem.StateID; + + if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) + { + throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); + } + + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + if (currentState.StateID != stateTransaction.CurrentStateId) + { + throw new WorkflowConcurrencyException(); + } + + var nextState = this.GetNextWorkflowState(workflow, contentItem.StateID); + if (nextState.StateID == workflow.LastState.StateID) + { + this.CompleteWorkflow(stateTransaction); + return; + } + + // before-change action + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteState); + this.UpdateContentItemWorkflowState(nextState.StateID, contentItem); + + // Add logs + this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, currentState, + currentState.StateID == workflow.FirstState.StateID + ? WorkflowLogType.DraftCompleted + : WorkflowLogType.StateCompleted, stateTransaction.UserId); + this.AddWorkflowLog( + contentItem, + nextState.StateID == workflow.LastState.StateID + ? WorkflowLogType.WorkflowApproved + : WorkflowLogType.StateInitiated, stateTransaction.UserId); + + this.SendNotificationsToReviewers(contentItem, nextState, stateTransaction, WorkflowActionTypes.CompleteState, new PortalSettings(workflow.PortalID)); + + this.DeleteWorkflowNotifications(contentItem, currentState); + + // after-change action + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteState); + } + + public void DiscardState(StateTransaction stateTransaction) + { + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + var workflow = this._workflowManager.GetWorkflow(contentItem); + if (workflow == null) + { + return; + } + + var isFirstState = workflow.FirstState.StateID == contentItem.StateID; + var isLastState = workflow.LastState.StateID == contentItem.StateID; + + if (isLastState) + { + throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowCannotDiscard", "Cannot discard on last workflow state")); + } + + if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) + { + throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); + } + + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + if (currentState.StateID != stateTransaction.CurrentStateId) + { + throw new WorkflowConcurrencyException(); + } + + var previousState = this.GetPreviousWorkflowState(workflow, contentItem.StateID); + if (previousState.StateID == workflow.LastState.StateID) + { + this.DiscardWorkflow(stateTransaction); + return; + } + + // before-change action + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardState); + + this.UpdateContentItemWorkflowState(previousState.StateID, contentItem); + + // Add logs + this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, currentState, WorkflowLogType.StateDiscarded, stateTransaction.UserId); + this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, stateTransaction.UserId); + + if (previousState.StateID == workflow.FirstState.StateID) + { + // Send to author - workflow comes back to draft state + this.SendNotificationToAuthor(stateTransaction, previousState, workflow, contentItem, WorkflowActionTypes.DiscardState); + } + else + { + this.SendNotificationsToReviewers(contentItem, previousState, stateTransaction, WorkflowActionTypes.DiscardState, new PortalSettings(workflow.PortalID)); + } + + this.DeleteWorkflowNotifications(contentItem, currentState); + + // after-change action + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardState); + } + + public bool IsWorkflowCompleted(int contentItemId) + { + var contentItem = this._contentController.GetContentItem(contentItemId); + return this.IsWorkflowCompleted(contentItem); + } + + public bool IsWorkflowCompleted(ContentItem contentItem) + { + var workflow = this._workflowManager.GetWorkflow(contentItem); + if (workflow == null) + { + return true; // If item has not workflow, then it is considered as completed + } + + return contentItem.StateID == Null.NullInteger || workflow.LastState.StateID == contentItem.StateID; + } + + public bool IsWorkflowOnDraft(int contentItemId) + { + var contentItem = this._contentController.GetContentItem(contentItemId); // Ensure DB values + return this.IsWorkflowOnDraft(contentItem); + } + + public bool IsWorkflowOnDraft(ContentItem contentItem) + { + var workflow = this._workflowManager.GetWorkflow(contentItem); + if (workflow == null) + { + return false; // If item has not workflow, then it is not on Draft + } + + return contentItem.StateID == workflow.FirstState.StateID; + } + + public void DiscardWorkflow(StateTransaction stateTransaction) + { + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + if (currentState.StateID != stateTransaction.CurrentStateId) + { + throw new WorkflowConcurrencyException(); + } + + // before-change action + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardWorkflow); + + var workflow = this._workflowManager.GetWorkflow(contentItem); + this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); + + // Logs + this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowDiscarded, stateTransaction.UserId); + + // Notifications + this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.DiscardWorkflow); + this.DeleteWorkflowNotifications(contentItem, currentState); + + // after-change action + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardWorkflow); + } + + public void CompleteWorkflow(StateTransaction stateTransaction) + { + var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); + + var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); + if (currentState.StateID != stateTransaction.CurrentStateId) + { + throw new WorkflowConcurrencyException(); + } + + // before-change action + this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteWorkflow); + + var workflow = this._workflowManager.GetWorkflow(contentItem); + this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); + + // Logs + this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); + this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowApproved, stateTransaction.UserId); + + // Notifications + this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.CompleteWorkflow); + this.DeleteWorkflowNotifications(contentItem, currentState); + + // after-change action + this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteWorkflow); + } + + protected override Func GetFactory() + { + return () => new WorkflowEngine(); + } + private static List GetRolesFromPermissions(PortalSettings settings, IEnumerable permissions) { - return (from permission in permissions - where permission.AllowAccess && permission.RoleID > Null.NullInteger + return (from permission in permissions + where permission.AllowAccess && permission.RoleID > Null.NullInteger select RoleController.Instance.GetRoleById(settings.PortalId, permission.RoleID)).ToList(); } @@ -79,7 +336,39 @@ private static bool IsAdministratorRoleAlreadyIncluded(PortalSettings settings, { return roles.Any(r => r.RoleName == settings.AdministratorRoleName); } - + + 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(); + } + + private static List 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.ToList(); + } + + private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) + { + 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 StateTransaction CreateInitialTransaction(int contentItemId, int stateId, int userId) { return new StateTransaction @@ -151,7 +440,7 @@ private UserInfo GetUserByWorkflowLogType(ContentItem contentItem, WorkflowLogTy { return this._userController.GetUserById(workflow.PortalID, logDraftCompleted.User); } - + return null; } @@ -160,8 +449,8 @@ private bool WasDraftSubmitted(Entities.Workflow workflow, int currentStateId) var isDirectPublishWorkflow = workflow.IsSystem && workflow.States.Count() == 1; var draftSubmitted = workflow.FirstState.StateID != currentStateId; return !(isDirectPublishWorkflow || !draftSubmitted); - } - + } + private string GetWorkflowNotificationContext(ContentItem contentItem, WorkflowState state) { return string.Format("{0}:{1}:{2}", contentItem.ContentItemId, state.WorkflowID, state.StateID); @@ -215,7 +504,7 @@ private void SendNotificationToAuthor(StateTransaction stateTransaction, Workflo var message = workflowAction.GetActionMessage(stateTransaction, state); var notification = this.GetNotification(this.GetWorkflowNotificationContext(contentItem, state), stateTransaction, message, ContentWorkflowNotificationNoActionType); - + this._notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); } catch (Exception ex) @@ -244,7 +533,7 @@ private void SendNotificationToWorkflowStarter(StateTransaction stateTransaction var message = workflowAction.GetActionMessage(stateTransaction, workflow.FirstState); var notification = this.GetNotification(this.GetWorkflowNotificationContext(contentItem, workflow.FirstState), stateTransaction, message, ContentWorkflowNotificatioStartWorkflowType); - + this._notificationsController.SendNotification(notification, workflow.PortalID, null, new[] { user }); } catch (Exception ex) @@ -306,10 +595,10 @@ private Notification GetNotification(string workflowContext, StateTransaction st 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) { @@ -328,67 +617,28 @@ private ReviewersDto GetUserAndRolesForStateReviewers(PortalSettings portalSetti reviewers.Users = IncludeSuperUsers(reviewers.Users); } - - return reviewers; - } - - private class ReviewersDto - { - public List Roles { get; set; } - - 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(); - } - - private static List 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.ToList(); - } - - private static bool IsSuperUserNotIncluded(IEnumerable users, UserInfo superUser) - { - 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"); + + return reviewers; } - + private void AddWorkflowCommentLog(ContentItem contentItem, int userId, string userComment) { if (string.IsNullOrEmpty(userComment)) { return; } - + var state = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); this.AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); } - + private void AddWorkflowCommentLog(ContentItem contentItem, WorkflowState state, int userId, string userComment) { if (string.IsNullOrEmpty(userComment)) { return; } - + this.AddWorkflowLog(contentItem, state, WorkflowLogType.CommentProvided, userId, userComment); } @@ -451,7 +701,7 @@ private WorkflowState GetNextWorkflowState(Entities.Workflow workflow, int state { nextState = states.ElementAt(index); } - + return nextState ?? workflow.FirstState; } @@ -477,263 +727,13 @@ private WorkflowState GetPreviousWorkflowState(Entities.Workflow workflow, int s } return previousState ?? workflow.LastState; - } - - public void StartWorkflow(int workflowId, int contentItemId, int userId) - { - Requires.NotNegative("workflowId", workflowId); - - var contentItem = this._contentController.GetContentItem(contentItemId); - var workflow = this._workflowManager.GetWorkflow(contentItem); - - // If already exists a started workflow - if (workflow != null && !this.IsWorkflowCompleted(contentItem)) - { - throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowAlreadyStarted", "Workflow cannot get started for this Content Item. It already has a started workflow.")); - } - - if (workflow == null || workflow.WorkflowID != workflowId) - { - workflow = this._workflowRepository.GetWorkflow(workflowId); - } - - var initialTransaction = this.CreateInitialTransaction(contentItemId, workflow.FirstState.StateID, userId); - - // Perform action before starting workflow - this.PerformWorkflowActionOnStateChanging(initialTransaction, WorkflowActionTypes.StartWorkflow); - this.UpdateContentItemWorkflowState(workflow.FirstState.StateID, contentItem); - - // Send notifications to stater - if (workflow.WorkflowID != this._systemWorkflowManager.GetDirectPublishWorkflow(workflow.PortalID).WorkflowID) // This notification is not sent in Direct Publish WF - { - this.SendNotificationToWorkflowStarter(initialTransaction, workflow, contentItem, userId, WorkflowActionTypes.StartWorkflow); - } - - // Delete previous logs - this._workflowLogRepository.DeleteWorkflowLogs(contentItemId, workflowId); - - // Add logs - this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowStarted, userId); - this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, userId); - - // Perform action after starting workflow - this.PerformWorkflowActionOnStateChanged(initialTransaction, WorkflowActionTypes.StartWorkflow); - } - - public void CompleteState(StateTransaction stateTransaction) - { - var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - var workflow = this._workflowManager.GetWorkflow(contentItem); - - if (workflow == null) - { - return; - } - - if (this.IsWorkflowCompleted(contentItem) - && !(workflow.IsSystem && workflow.States.Count() == 1)) - { - throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowSystemWorkflowStateCannotComplete", "System workflow state cannot be completed.")); - } - - var isFirstState = workflow.FirstState.StateID == contentItem.StateID; - - if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) - { - throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); - } - - var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - if (currentState.StateID != stateTransaction.CurrentStateId) - { - throw new WorkflowConcurrencyException(); - } - - var nextState = this.GetNextWorkflowState(workflow, contentItem.StateID); - if (nextState.StateID == workflow.LastState.StateID) - { - this.CompleteWorkflow(stateTransaction); - return; - } - - // before-change action - this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteState); - this.UpdateContentItemWorkflowState(nextState.StateID, contentItem); - - // Add logs - this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); - this.AddWorkflowLog(contentItem, currentState, - currentState.StateID == workflow.FirstState.StateID - ? WorkflowLogType.DraftCompleted - : WorkflowLogType.StateCompleted, stateTransaction.UserId); - this.AddWorkflowLog( - contentItem, - nextState.StateID == workflow.LastState.StateID - ? WorkflowLogType.WorkflowApproved - : WorkflowLogType.StateInitiated, stateTransaction.UserId); - - this.SendNotificationsToReviewers(contentItem, nextState, stateTransaction, WorkflowActionTypes.CompleteState, new PortalSettings(workflow.PortalID)); - - this.DeleteWorkflowNotifications(contentItem, currentState); - - // after-change action - this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteState); - } - - public void DiscardState(StateTransaction stateTransaction) - { - var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - var workflow = this._workflowManager.GetWorkflow(contentItem); - if (workflow == null) - { - return; - } - - var isFirstState = workflow.FirstState.StateID == contentItem.StateID; - var isLastState = workflow.LastState.StateID == contentItem.StateID; - - if (isLastState) - { - throw new WorkflowInvalidOperationException(Localization.GetExceptionMessage("WorkflowCannotDiscard", "Cannot discard on last workflow state")); - } - - if (!isFirstState && !this._workflowSecurity.HasStateReviewerPermission(workflow.PortalID, stateTransaction.UserId, contentItem.StateID)) - { - throw new WorkflowSecurityException(Localization.GetExceptionMessage("UserCannotReviewWorkflowState", "User cannot review the workflow state")); - } - - var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - if (currentState.StateID != stateTransaction.CurrentStateId) - { - throw new WorkflowConcurrencyException(); - } - - var previousState = this.GetPreviousWorkflowState(workflow, contentItem.StateID); - if (previousState.StateID == workflow.LastState.StateID) - { - this.DiscardWorkflow(stateTransaction); - return; - } - - // before-change action - this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardState); - - this.UpdateContentItemWorkflowState(previousState.StateID, contentItem); - - // Add logs - this.AddWorkflowCommentLog(contentItem, currentState, stateTransaction.UserId, stateTransaction.Message.UserComment); - this.AddWorkflowLog(contentItem, currentState, WorkflowLogType.StateDiscarded, stateTransaction.UserId); - this.AddWorkflowLog(contentItem, WorkflowLogType.StateInitiated, stateTransaction.UserId); - - if (previousState.StateID == workflow.FirstState.StateID) - { - // Send to author - workflow comes back to draft state - this.SendNotificationToAuthor(stateTransaction, previousState, workflow, contentItem, WorkflowActionTypes.DiscardState); - } - else - { - this.SendNotificationsToReviewers(contentItem, previousState, stateTransaction, WorkflowActionTypes.DiscardState, new PortalSettings(workflow.PortalID)); - } - - this.DeleteWorkflowNotifications(contentItem, currentState); - - // after-change action - this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardState); - } - - public bool IsWorkflowCompleted(int contentItemId) - { - var contentItem = this._contentController.GetContentItem(contentItemId); - return this.IsWorkflowCompleted(contentItem); - } - - public bool IsWorkflowCompleted(ContentItem contentItem) - { - var workflow = this._workflowManager.GetWorkflow(contentItem); - if (workflow == null) - { - return true; // If item has not workflow, then it is considered as completed - } - - return contentItem.StateID == Null.NullInteger || workflow.LastState.StateID == contentItem.StateID; - } - - public bool IsWorkflowOnDraft(int contentItemId) - { - var contentItem = this._contentController.GetContentItem(contentItemId); // Ensure DB values - return this.IsWorkflowOnDraft(contentItem); - } - - public bool IsWorkflowOnDraft(ContentItem contentItem) - { - var workflow = this._workflowManager.GetWorkflow(contentItem); - if (workflow == null) - { - return false; // If item has not workflow, then it is not on Draft - } - - return contentItem.StateID == workflow.FirstState.StateID; } - public void DiscardWorkflow(StateTransaction stateTransaction) + private class ReviewersDto { - var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - - var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - if (currentState.StateID != stateTransaction.CurrentStateId) - { - throw new WorkflowConcurrencyException(); - } - - // before-change action - this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.DiscardWorkflow); - - var workflow = this._workflowManager.GetWorkflow(contentItem); - this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); - - // Logs - this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); - this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowDiscarded, stateTransaction.UserId); - - // Notifications - this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.DiscardWorkflow); - this.DeleteWorkflowNotifications(contentItem, currentState); + public List Roles { get; set; } - // after-change action - this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.DiscardWorkflow); + public List Users { get; set; } } - - public void CompleteWorkflow(StateTransaction stateTransaction) - { - var contentItem = this._contentController.GetContentItem(stateTransaction.ContentItemId); - - var currentState = this._workflowStateRepository.GetWorkflowStateByID(contentItem.StateID); - if (currentState.StateID != stateTransaction.CurrentStateId) - { - throw new WorkflowConcurrencyException(); - } - - // before-change action - this.PerformWorkflowActionOnStateChanging(stateTransaction, WorkflowActionTypes.CompleteWorkflow); - - var workflow = this._workflowManager.GetWorkflow(contentItem); - this.UpdateContentItemWorkflowState(workflow.LastState.StateID, contentItem); - - // Logs - this.AddWorkflowCommentLog(contentItem, stateTransaction.UserId, stateTransaction.Message.UserComment); - this.AddWorkflowLog(contentItem, WorkflowLogType.WorkflowApproved, stateTransaction.UserId); - - // Notifications - this.SendNotificationToAuthor(stateTransaction, workflow.LastState, workflow, contentItem, WorkflowActionTypes.CompleteWorkflow); - this.DeleteWorkflowNotifications(contentItem, currentState); - - // after-change action - this.PerformWorkflowActionOnStateChanged(stateTransaction, WorkflowActionTypes.CompleteWorkflow); - } - - protected override Func GetFactory() - { - return () => new WorkflowEngine(); - } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs index 288a120bb32..8f461575aed 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowLogger.cs @@ -13,24 +13,34 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Localization; public class WorkflowLogger : ServiceLocator, IWorkflowLogger - { - private readonly IWorkflowLogRepository _workflowLogRepository; - + { + private readonly IWorkflowLogRepository _workflowLogRepository; + 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); } - + + public void AddWorkflowLog(int contentItemId, int workflowId, string action, string comment, int userId) + { + this.AddWorkflowLog(contentItemId, workflowId, WorkflowLogType.CommentProvided, action, comment, userId); + } + + protected override Func GetFactory() + { + return () => new WorkflowLogger(); + } + private void AddWorkflowLog(int contentItemId, int workflowId, WorkflowLogType type, string action, string comment, int userId) { var workflowLog = new WorkflowLog @@ -50,16 +60,6 @@ private string GetWorkflowActionText(WorkflowLogType logType) { var logName = Enum.GetName(typeof(WorkflowLogType), logType); return Localization.GetString(logName + ".Action"); - } - - public void AddWorkflowLog(int contentItemId, int workflowId, string action, string comment, int userId) - { - this.AddWorkflowLog(contentItemId, workflowId, WorkflowLogType.CommentProvided, action, comment, userId); - } - - protected override Func GetFactory() - { - return () => new WorkflowLogger(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs index c3c21c568fe..499289792bf 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowManager.cs @@ -15,20 +15,20 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Localization; public class WorkflowManager : ServiceLocator, IWorkflowManager - { + { private readonly DataProvider _dataProvider; private readonly IWorkflowRepository _workflowRepository; private readonly IWorkflowStateRepository _workflowStateRepository; - private readonly ISystemWorkflowManager _systemWorkflowManager; - + private readonly ISystemWorkflowManager _systemWorkflowManager; + public WorkflowManager() { this._dataProvider = DataProvider.Instance(); this._workflowRepository = WorkflowRepository.Instance; this._workflowStateRepository = WorkflowStateRepository.Instance; this._systemWorkflowManager = SystemWorkflowManager.Instance; - } - + } + public void DeleteWorkflow(Entities.Workflow workflow) { var workflowToDelete = this._workflowRepository.GetWorkflow(workflow.WorkflowID); @@ -62,7 +62,7 @@ public Entities.Workflow GetWorkflow(ContentItem contentItem) { return null; } - + var state = WorkflowStateRepository.Instance.GetWorkflowStateByID(contentItem.StateID); return state == null ? null : this.GetWorkflow(state.WorkflowID); } @@ -105,11 +105,11 @@ public IEnumerable GetWorkflowUsage(int workflowId, int pageI public int GetWorkflowUsageCount(int workflowId) { return this._dataProvider.GetContentWorkflowUsageCount(workflowId); - } - + } + protected override System.Func GetFactory() { return () => new WorkflowManager(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs index f9c3e03659d..b7b4ea36f1f 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowSecurity.cs @@ -15,13 +15,13 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Security.Permissions; public class WorkflowSecurity : ServiceLocator, IWorkflowSecurity - { + { private const string ReviewPermissionKey = "REVIEW"; - private const string ReviewPermissionCode = "SYSTEM_CONTENTWORKFLOWSTATE"; + private const string ReviewPermissionCode = "SYSTEM_CONTENTWORKFLOWSTATE"; private readonly IUserController _userController = UserController.Instance; private readonly IWorkflowManager _workflowManager = WorkflowManager.Instance; - private readonly IWorkflowStatePermissionsRepository _statePermissionsRepository = WorkflowStatePermissionsRepository.Instance; - + private readonly IWorkflowStatePermissionsRepository _statePermissionsRepository = WorkflowStatePermissionsRepository.Instance; + public bool HasStateReviewerPermission(PortalSettings settings, UserInfo user, int stateId) { var permissions = this._statePermissionsRepository.GetWorkflowStatePermissionByState(stateId); @@ -53,11 +53,11 @@ public bool IsWorkflowReviewer(int workflowId, int userId) public PermissionInfo GetStateReviewPermission() { return (PermissionInfo)new PermissionController().GetPermissionByCodeAndKey(ReviewPermissionCode, ReviewPermissionKey)[0]; - } - + } + protected override Func GetFactory() { return () => new WorkflowSecurity(); - } + } } } diff --git a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs index d2b5ad8a3a0..12be8dd2dc9 100644 --- a/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs +++ b/DNN Platform/Library/Entities/Content/Workflow/WorkflowStateManager.cs @@ -16,17 +16,17 @@ namespace DotNetNuke.Entities.Content.Workflow using DotNetNuke.Services.Localization; public class WorkflowStateManager : ServiceLocator, IWorkflowStateManager - { + { private readonly DataProvider _dataProvider; private readonly IWorkflowRepository _workflowRepository = WorkflowRepository.Instance; private readonly IWorkflowStateRepository _workflowStateRepository = WorkflowStateRepository.Instance; - private readonly IWorkflowStatePermissionsRepository _workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; - + private readonly IWorkflowStatePermissionsRepository _workflowStatePermissionsRepository = WorkflowStatePermissionsRepository.Instance; + public WorkflowStateManager() { this._dataProvider = DataProvider.Instance(); - } - + } + public IEnumerable GetWorkflowStates(int workflowId) { return this._workflowStateRepository.GetWorkflowStates(workflowId); @@ -95,7 +95,7 @@ public void UpdateWorkflowState(WorkflowState state) { throw new WorkflowDoesNotExistException(); } - + this._workflowStateRepository.UpdateWorkflowState(state); } @@ -119,12 +119,12 @@ public void MoveWorkflowStateDown(int stateId) for (var i = 0; i < states.Length; i++) { - if (states[i].StateID != stateId) - { - continue; - } - - // First and Second workflow state cannot be moved down + if (states[i].StateID != stateId) + { + continue; + } + + // First and Second workflow state cannot be moved down if (i <= 1) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); @@ -168,12 +168,12 @@ public void MoveWorkflowStateUp(int stateId) for (var i = 0; i < states.Length; i++) { - if (states[i].StateID != stateId) - { - continue; - } - - // Last and Next to Last workflow state cannot be moved up + if (states[i].StateID != stateId) + { + continue; + } + + // Last and Next to Last workflow state cannot be moved up if (i >= states.Length - 2) { throw new WorkflowInvalidOperationException(Localization.GetString("WorkflowStateCannotBeMoved", Localization.ExceptionsResourceFile)); @@ -240,13 +240,13 @@ public void DeleteWorkflowStatePermission(int workflowStatePermissionId) 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; @@ -257,13 +257,13 @@ private int GetStateIndex(WorkflowState[] states, WorkflowState currentState) { return i; } - + i++; } return i; } - + private void MoveState(WorkflowState state, int targetIndex, int currentIndex) { if (currentIndex == targetIndex) @@ -285,6 +285,6 @@ private void MoveState(WorkflowState state, int targetIndex, int currentIndex) this.MoveWorkflowStateDown(state.StateID); } } - } + } } } diff --git a/DNN Platform/Library/Entities/DataStructures/NTree.cs b/DNN Platform/Library/Entities/DataStructures/NTree.cs index b0dfd2d97d0..95033c72dad 100644 --- a/DNN Platform/Library/Entities/DataStructures/NTree.cs +++ b/DNN Platform/Library/Entities/DataStructures/NTree.cs @@ -17,7 +17,7 @@ public class NTree [DataMember(Name = "children")] public List> Children; - + public NTree() { this.Children = new List>(); diff --git a/DNN Platform/Library/Entities/EventManager.cs b/DNN Platform/Library/Entities/EventManager.cs index ce874f2520d..139857262fe 100644 --- a/DNN Platform/Library/Entities/EventManager.cs +++ b/DNN Platform/Library/Entities/EventManager.cs @@ -116,91 +116,91 @@ 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; 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) @@ -223,11 +223,6 @@ 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) @@ -577,6 +572,11 @@ public void RefreshTabSyncHandlers() } } + protected override Func GetFactory() + { + return () => new EventManager(); + } + private static void AddLog(IFileInfo fileInfo, int userId, EventLogController.EventLogType logType) { if (fileInfo == null) diff --git a/DNN Platform/Library/Entities/Host/Host.cs b/DNN Platform/Library/Entities/Host/Host.cs index 7de4b75dd14..5c928202b83 100644 --- a/DNN Platform/Library/Entities/Host/Host.cs +++ b/DNN Platform/Library/Entities/Host/Host.cs @@ -957,35 +957,6 @@ public static string PaymentProcessor } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the PerformanceSettings. - /// - /// - /// Defaults to PerformanceSettings.ModerateCaching. - /// - /// ----------------------------------------------------------------------------- - public static Globals.PerformanceSettings PerformanceSetting - { - get - { - if (!_performanceSetting.HasValue) - { - var s = HostController.Instance.GetString("PerformanceSetting"); - if (string.IsNullOrEmpty(s)) - { - return Globals.PerformanceSettings.ModerateCaching; - } - - _performanceSetting = (Globals.PerformanceSettings)Enum.Parse(typeof(Globals.PerformanceSettings), s); - } - - return _performanceSetting.Value; - } - - set { _performanceSetting = value; } - } - /// ----------------------------------------------------------------------------- /// /// Gets the Payment Processor Password. @@ -1340,50 +1311,6 @@ 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. @@ -1693,5 +1620,78 @@ public static bool IsLocked { get { return HostController.Instance.GetBoolean("IsLocked", false); } } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the PerformanceSettings. + /// + /// + /// Defaults to PerformanceSettings.ModerateCaching. + /// + /// ----------------------------------------------------------------------------- + public static Globals.PerformanceSettings PerformanceSetting + { + get + { + if (!_performanceSetting.HasValue) + { + var s = HostController.Instance.GetString("PerformanceSetting"); + if (string.IsNullOrEmpty(s)) + { + return Globals.PerformanceSettings.ModerateCaching; + } + + _performanceSetting = (Globals.PerformanceSettings)Enum.Parse(typeof(Globals.PerformanceSettings), s); + } + + return _performanceSetting.Value; + } + + set { _performanceSetting = value; } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } } } diff --git a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs index ed713a12dcc..35f94500a07 100644 --- a/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Host/HostPropertyAccess.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Entities.Host public class HostPropertyAccess : DictionaryPropertyAccess { - public HostPropertyAccess() + public HostPropertyAccess() : base(HostController.Instance.GetSettingsDictionary()) { } diff --git a/DNN Platform/Library/Entities/Host/ServerController.cs b/DNN Platform/Library/Entities/Host/ServerController.cs index 408b3deb583..ea2bab0d307 100644 --- a/DNN Platform/Library/Entities/Host/ServerController.cs +++ b/DNN Platform/Library/Entities/Host/ServerController.cs @@ -37,7 +37,7 @@ public static bool UseAppName { uniqueServers[server.ServerName] = server.IISAppName; } - + return uniqueServers.Count < GetEnabledServers().Count; } } @@ -67,7 +67,7 @@ public static List GetEnabledServers() } } } - + return servers; } @@ -78,7 +78,7 @@ public static string GetExecutingServerName() { executingServerName += "-" + Globals.IISAppName; } - + Logger.Debug("GetExecutingServerName:" + executingServerName); return executingServerName; } @@ -90,7 +90,7 @@ public static string GetServerName(ServerInfo webServer) { serverName += "-" + webServer.IISAppName; } - + Logger.Debug("GetServerName:" + serverName); return serverName; } @@ -119,13 +119,13 @@ public static void UpdateServerActivity(ServerInfo server) { // try to detect the server url from url adapter. server.Url = existServer == null || string.IsNullOrEmpty(existServer.Url) ? GetServerUrl() : existServer.Url; - + // try to detect the server unique id from url adapter. server.UniqueId = existServer == null || string.IsNullOrEmpty(existServer.UniqueId) ? GetServerUniqueId() : existServer.UniqueId; UpdateServer(server); } - + // log the server info var log = new LogInfo(); log.AddProperty(existServer != null ? "Server Updated" : "Add New Server", server.ServerName); diff --git a/DNN Platform/Library/Entities/Host/ServerInfo.cs b/DNN Platform/Library/Entities/Host/ServerInfo.cs index 3fcfc5b0eb3..6ceb5d70e45 100644 --- a/DNN Platform/Library/Entities/Host/ServerInfo.cs +++ b/DNN Platform/Library/Entities/Host/ServerInfo.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Host [Serializable] public class ServerInfo : IHydratable { - public ServerInfo() + public ServerInfo() : this(DateTime.Now, DateTime.Now) { } @@ -46,7 +46,7 @@ public ServerInfo(DateTime created, DateTime lastactivity) public int PingFailureCount { get; set; } - public string UniqueId { get; set; } + public string UniqueId { get; set; } /// ----------------------------------------------------------------------------- /// @@ -60,13 +60,13 @@ public int KeyID { return this.ServerID; } - + set { this.ServerID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a ServerInfo from a Data Reader. @@ -90,12 +90,12 @@ public void Fill(IDataReader dr) { this.PingFailureCount = Null.SetNullInteger(dr["PingFailureCount"]); } - + if (schema.Select("ColumnName = 'ServerGroup'").Length > 0) { this.ServerGroup = Null.SetNullString(dr["ServerGroup"]); } - + if (schema.Select("ColumnName = 'UniqueId'").Length > 0) { this.UniqueId = Null.SetNullString(dr["UniqueId"]); diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs index e93f132a812..2fdc1f7ff66 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterController.cs @@ -20,19 +20,19 @@ namespace DotNetNuke.Entities.Host using DotNetNuke.Services.Log.EventLog; public class IPFilterController : ComponentBase, IIPFilterController - { + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IPFilterController)); - + internal IPFilterController() { - } + } private enum FilterType { Allow = 1, Deny = 2, - } - + } + /// /// add a new IP filter. /// @@ -75,20 +75,11 @@ public IPFilterInfo GetIPFilter(int ipFilter) return CBO.FillObject(DataProvider.Instance().GetIPFilter(ipFilter)); } - /// - /// get the list of IP filters. - /// - /// list of IP filters. - IList IIPFilterController.GetIPFilters() - { - return CBO.FillCollection(DataProvider.Instance().GetIPFilters()); - } - [Obsolete("deprecated with 7.1.0 - please use IsIPBanned instead to return the value and apply your own logic. Scheduled removal in v10.0.0.")] public void IsIPAddressBanned(string ipAddress) { if (this.CheckIfBannedIPAddress(ipAddress)) - {// should throw 403.6 + {// should throw 403.6 throw new HttpException(403, string.Empty); } } @@ -129,7 +120,7 @@ public bool CanIPStillAccess(string myip, IList filterList) var denyRules = (from p in filterList where p.RuleType == (int)FilterType.Deny select p).ToList(); - + // if global allow and no deny if (allowAllIPs & denyRules.Count == 0) { @@ -183,9 +174,33 @@ public bool IsAllowableDeny(string currentIP, IPFilterInfo ipFilter) { return false; } - + return true; - } + } + + private static void AssertValidIPFilter(IPFilterInfo ipFilter) + { + IPAddress parsed; + if (IPAddress.TryParse(ipFilter.IPAddress, out parsed) == false) + { + throw new ArgumentException(Localization.GetExceptionMessage("IPAddressIncorrect", "IP address is not in correct format")); + } + + bool isIPRange = string.IsNullOrEmpty(ipFilter.SubnetMask) == false; + if (isIPRange && IPAddress.TryParse(ipFilter.SubnetMask, out parsed) == false) + { + throw new ArgumentException(Localization.GetExceptionMessage("SubnetMaskIncorrect", "Subnet mask is not in correct format")); + } + } + + /// + /// get the list of IP filters. + /// + /// list of IP filters. + IList IIPFilterController.GetIPFilters() + { + return CBO.FillCollection(DataProvider.Instance().GetIPFilters()); + } private bool CheckIfBannedIPAddress(string ipAddress) { @@ -203,7 +218,7 @@ private bool CheckIfBannedIPAddress(string 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) { @@ -213,10 +228,10 @@ private bool CheckIfBannedIPAddress(string ipAddress) } } } - + return ipAllowed; } - + private void LogBannedIPAttempt(string ipAddress) { var log = new LogInfo @@ -226,20 +241,5 @@ private void LogBannedIPAttempt(string ipAddress) log.LogProperties.Add(new LogDetailInfo("HostAddress", ipAddress)); LogController.Instance.AddLog(log); } - - private static void AssertValidIPFilter(IPFilterInfo ipFilter) - { - IPAddress parsed; - if (IPAddress.TryParse(ipFilter.IPAddress, out parsed) == false) - { - throw new ArgumentException(Localization.GetExceptionMessage("IPAddressIncorrect", "IP address is not in correct format")); - } - - bool isIPRange = string.IsNullOrEmpty(ipFilter.SubnetMask) == false; - if (isIPRange && IPAddress.TryParse(ipFilter.SubnetMask, out parsed) == false) - { - throw new ArgumentException(Localization.GetExceptionMessage("SubnetMaskIncorrect", "Subnet mask is not in correct format")); - } - } } } diff --git a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs index 430003c7d08..4024b1b41dc 100644 --- a/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs +++ b/DNN Platform/Library/Entities/IPFilter/IPFilterInfo.cs @@ -18,8 +18,8 @@ namespace DotNetNuke.Entities.Host [Serializable] public class IPFilterInfo : BaseEntityInfo, IHydratable - { - /// + { + /// /// Initializes a new instance of the class. /// Create new IPFilterInfo instance. /// @@ -37,15 +37,15 @@ public IPFilterInfo() this.IPAddress = string.Empty; this.SubnetMask = string.Empty; this.RuleType = -1; - } - + } + public int IPFilterID { get; set; } public string IPAddress { get; set; } public string SubnetMask { get; set; } - public int RuleType { get; set; } + public int RuleType { get; set; } /// /// Gets or sets and sets the Key ID. @@ -58,13 +58,13 @@ public int KeyID { return this.IPFilterID; } - + set { this.IPFilterID = value; } - } - + } + /// /// Fills an IPFilterInfo from a Data Reader. /// diff --git a/DNN Platform/Library/Entities/Icons/IconController.cs b/DNN Platform/Library/Entities/Icons/IconController.cs index 414220f0316..21245ceca74 100644 --- a/DNN Platform/Library/Entities/Icons/IconController.cs +++ b/DNN Platform/Library/Entities/Icons/IconController.cs @@ -43,14 +43,14 @@ public class 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"; + public const string IconStyleName = "IconStyle"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IconController)); private static readonly SharedDictionary _iconsStatusOnDisk = new SharedDictionary(); - + /// /// Gets the Icon URL. /// @@ -81,21 +81,21 @@ public static string IconURL(string key, string size) /// Link to the image, e.g. /Icons/Sigma/edit_16x16_standard.png. public static string IconURL(string key, string size, string style) { - if (string.IsNullOrEmpty(key)) - { - return string.Empty; - } - - if (string.IsNullOrEmpty(size)) - { - size = DefaultIconSize; - } - - if (string.IsNullOrEmpty(style)) - { - style = DefaultIconStyle; - } - + if (string.IsNullOrEmpty(key)) + { + return string.Empty; + } + + if (string.IsNullOrEmpty(size)) + { + size = DefaultIconSize; + } + + if (string.IsNullOrEmpty(style)) + { + style = DefaultIconStyle; + } + string fileName = string.Format("{0}/{1}_{2}_{3}.png", PortalSettings.Current.DefaultIconLocation, key, size, style); // In debug mode, we want to warn (onluy once) if icon is not present on disk @@ -111,7 +111,7 @@ public static string GetFileIconUrl(string extension) { return IconURL("Ext" + extension, "32x32", "Standard"); } - + return IconURL("ExtFile", "32x32", "Standard"); } @@ -123,23 +123,23 @@ public static string[] GetIconSets() foreach (var iconDir in iconRootDir.EnumerateDirectories()) { string testFile = Path.Combine(iconDir.FullName, "About_16x16_Standard.png"); - if (File.Exists(testFile)) - { - result += iconDir.Name + ","; - } + if (File.Exists(testFile)) + { + result += iconDir.Name + ","; + } } - + return result.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); } - + private static void CheckIconOnDisk(string path) { using (_iconsStatusOnDisk.GetReadLock()) { - if (_iconsStatusOnDisk.ContainsKey(path)) - { - return; - } + if (_iconsStatusOnDisk.ContainsKey(path)) + { + return; + } } using (_iconsStatusOnDisk.GetWriteLock()) @@ -148,10 +148,10 @@ private static void CheckIconOnDisk(string path) { _iconsStatusOnDisk.Add(path, true); string iconPhysicalPath = Path.Combine(Globals.ApplicationMapPath, path.Replace('/', '\\')); - if (!File.Exists(iconPhysicalPath)) - { - Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath)); - } + if (!File.Exists(iconPhysicalPath)) + { + Logger.WarnFormat(string.Format("Icon Not Present on Disk {0}", iconPhysicalPath)); + } } } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs b/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs index 8c202bab36d..c12bc45a894 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ActionEventArgs.cs @@ -18,10 +18,10 @@ namespace DotNetNuke.Entities.Modules.Actions public class ActionEventArgs : EventArgs { private readonly ModuleAction _action; - private readonly ModuleInfo _moduleConfiguration; - + private readonly ModuleInfo _moduleConfiguration; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -38,8 +38,8 @@ public ActionEventArgs(ModuleAction Action, ModuleInfo ModuleConfiguration) /// /// /// - /// - /// + /// + /// /// /// /// ----------------------------------------------------------------------------- @@ -55,8 +55,8 @@ public ModuleAction Action /// /// /// - /// - /// + /// + /// /// /// /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs index c09e4a491ed..bfe42c27aee 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/IModuleEventHandler.cs @@ -7,11 +7,11 @@ namespace DotNetNuke.Entities.Modules.Actions public interface IModuleEventHandler { void ModuleCreated(object sender, ModuleEventArgs args); - + void ModuleUpdated(object sender, ModuleEventArgs args); - + void ModuleRemoved(object sender, ModuleEventArgs args); - + void ModuleDeleted(object sender, ModuleEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs index 88899e1d2d3..ebdaa789f90 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleAction.cs @@ -23,22 +23,22 @@ namespace DotNetNuke.Entities.Modules.Actions /// ----------------------------------------------------------------------------- public class ModuleAction { - public ModuleAction(int id) + public ModuleAction(int id) : this(id, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName) + public ModuleAction(int id, string title, string cmdName) : this(id, title, cmdName, string.Empty, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName, string cmdArg) + public ModuleAction(int id, string title, string cmdName, string cmdArg) : this(id, title, cmdName, cmdArg, string.Empty, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } - public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon) + public ModuleAction(int id, string title, string cmdName, string cmdArg, string icon) : this(id, title, cmdName, cmdArg, icon, string.Empty, string.Empty, false, SecurityAccessLevel.Anonymous, true, false) { } @@ -208,40 +208,6 @@ public ModuleAction(int id, string title, string cmdName, string cmdArg, string /// ----------------------------------------------------------------------------- public string Icon { get; set; } - internal string ControlKey - { - get - { - string controlKey = string.Empty; - if (!string.IsNullOrEmpty(this.Url)) - { - int startIndex = this.Url.IndexOf("/ctl/"); - int endIndex = -1; - if (startIndex > -1) - { - startIndex += 4; - endIndex = this.Url.IndexOf("/", startIndex + 1); - } - else - { - startIndex = this.Url.IndexOf("ctl="); - if (startIndex > -1) - { - startIndex += 4; - endIndex = this.Url.IndexOf("&", startIndex + 1); - } - } - - if (startIndex > -1) - { - controlKey = endIndex > -1 ? this.Url.Substring(startIndex + 1, endIndex - startIndex - 1) : this.Url.Substring(startIndex + 1); - } - } - - return controlKey; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets the URL to which the user is redirected when the @@ -292,6 +258,40 @@ internal string ControlKey /// ----------------------------------------------------------------------------- public bool NewWindow { get; set; } + internal string ControlKey + { + get + { + string controlKey = string.Empty; + if (!string.IsNullOrEmpty(this.Url)) + { + int startIndex = this.Url.IndexOf("/ctl/"); + int endIndex = -1; + if (startIndex > -1) + { + startIndex += 4; + endIndex = this.Url.IndexOf("/", startIndex + 1); + } + else + { + startIndex = this.Url.IndexOf("ctl="); + if (startIndex > -1) + { + startIndex += 4; + endIndex = this.Url.IndexOf("&", startIndex + 1); + } + } + + if (startIndex > -1) + { + controlKey = endIndex > -1 ? this.Url.Substring(startIndex + 1, endIndex - startIndex - 1) : this.Url.Substring(startIndex + 1); + } + } + + return controlKey; + } + } + /// ----------------------------------------------------------------------------- /// /// Determines whether the action node contains any child actions. diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs index 7020e63cdd4..0bd59c99d17 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionCollection.cs @@ -19,9 +19,9 @@ namespace DotNetNuke.Entities.Modules.Actions /// collection which provides the ability to create a hierarchy of ModuleActions. /// ----------------------------------------------------------------------------- public class ModuleActionCollection : CollectionBase - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Initializes a new, empty instance of the class. /// @@ -79,7 +79,7 @@ public ModuleAction this[int index] { return (ModuleAction)this.List[index]; } - + set { this.List[index] = value; @@ -244,7 +244,7 @@ public ModuleAction GetActionByCommandName(string name) retAction = modAction; break; } - + // If action has children check them if (modAction.HasChildren()) { @@ -256,7 +256,7 @@ public ModuleAction GetActionByCommandName(string name) } } } - + return retAction; } @@ -271,14 +271,14 @@ public ModuleActionCollection GetActionsByCommandName(string name) { retActions.Add(modAction); } - + // If action has children check them if (modAction.HasChildren()) { retActions.AddRange(modAction.Actions.GetActionsByCommandName(name)); } } - + return retActions; } @@ -294,7 +294,7 @@ public ModuleAction GetActionByID(int id) retAction = modAction; break; } - + // If action has children check them if (modAction.HasChildren()) { @@ -306,7 +306,7 @@ public ModuleAction GetActionByID(int id) } } } - + return retAction; } diff --git a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs index 3593d23fd59..7d9220e10a8 100644 --- a/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs +++ b/DNN Platform/Library/Entities/Modules/Actions/ModuleActionEventListener.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.Entities.Modules.Actions public class ModuleActionEventListener { private readonly ActionEventHandler _actionEvent; - private readonly int _moduleID; - + private readonly int _moduleID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -37,8 +37,8 @@ public ModuleActionEventListener(int ModID, ActionEventHandler e) /// /// /// - /// - /// + /// + /// /// /// /// ----------------------------------------------------------------------------- @@ -54,8 +54,8 @@ public int ModuleID /// /// /// - /// - /// + /// + /// /// /// /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs index b01b51604ed..fbc27da8131 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicate.cs @@ -42,7 +42,7 @@ public ModuleListeners ModuleListeners return this._ModuleListeners; } } - + /// /// Loads the communicator. /// @@ -71,7 +71,7 @@ private int Add(IModuleCommunicator item) { item.ModuleCommunication += this._ModuleListeners[i].OnModuleCommunication; } - + return returnData; } diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs index 499f5900467..0337ab243b9 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleCommunicators.cs @@ -13,7 +13,7 @@ public IModuleCommunicator this[int index] { return (IModuleCommunicator)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs index 63f1ac81ef4..ab7f5a5d0c1 100644 --- a/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs +++ b/DNN Platform/Library/Entities/Modules/Communications/ModuleListeners.cs @@ -13,7 +13,7 @@ public IModuleListener this[int index] { return (IModuleListener)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Entities/Modules/ControlInfo.cs b/DNN Platform/Library/Entities/Modules/ControlInfo.cs index feef6f6ad06..21d904ba7c2 100644 --- a/DNN Platform/Library/Entities/Modules/ControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ControlInfo.cs @@ -82,7 +82,7 @@ protected void ReadXmlInternal(XmlReader reader) { this.SupportsPartialRendering = bool.Parse(elementvalue); } - + break; } } diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs index 8dc4a36c3c9..738a0f16675 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionController.cs @@ -27,13 +27,13 @@ namespace DotNetNuke.Entities.Modules.Definitions public class ModuleDefinitionController { private const string key = "ModuleDefID"; - private static readonly DataProvider dataProvider = DataProvider.Instance(); + private static readonly DataProvider dataProvider = DataProvider.Instance(); /// ----------------------------------------------------------------------------- /// /// GetModuleDefinitionByID gets a Module Definition by its ID. /// - /// The ID of the Module Definition. + /// The ID of the Module Definition. /// /// ----------------------------------------------------------------------------- public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) @@ -49,7 +49,7 @@ public static ModuleDefinitionInfo GetModuleDefinitionByID(int moduleDefID) /// GetModuleDefinitionByFriendlyName gets a Module Definition by its Friendly /// Name (and DesktopModuleID). /// - /// The friendly name. + /// The friendly name. /// /// ----------------------------------------------------------------------------- public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName) @@ -61,57 +61,6 @@ public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string frie select kvp.Value) .FirstOrDefault(); } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleDefinitionByID gets a Module Definition by its ID. - /// - /// The object of the Module Definition. - /// ----------------------------------------------------------------------------- - public void DeleteModuleDefinition(ModuleDefinitionInfo objModuleDefinition) - { - this.DeleteModuleDefinition(objModuleDefinition.ModuleDefID); - } - - /// ----------------------------------------------------------------------------- - /// - /// DeleteModuleDefinition deletes a Module Definition By ID. - /// - /// The ID of the Module Definition to delete. - /// ----------------------------------------------------------------------------- - public void DeleteModuleDefinition(int moduleDefinitionId) - { - // Delete associated permissions - var permissionController = new PermissionController(); - foreach (PermissionInfo permission in permissionController.GetPermissionsByModuleDefID(moduleDefinitionId)) - { - permissionController.DeletePermission(permission.PermissionID); - } - - dataProvider.DeleteModuleDefinition(moduleDefinitionId); - DataCache.ClearHostCache(true); - - // queue remove module definition from search index - var document = new SearchDocumentToDelete - { - ModuleDefId = moduleDefinitionId, - }; - - DataProvider.Instance().AddSearchDeletedItems(document); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from - /// the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call. - /// ----------------------------------------------------------------------------- - private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillDictionary(key, dataProvider.GetModuleDefinitions(), new Dictionary()); - } /// ----------------------------------------------------------------------------- /// @@ -119,7 +68,7 @@ private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) /// Name (and DesktopModuleID). /// /// The friendly name. - /// The ID of the Dekstop Module. + /// The ID of the Dekstop Module. /// /// ----------------------------------------------------------------------------- public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string friendlyName, int desktopModuleID) @@ -136,13 +85,13 @@ public static ModuleDefinitionInfo GetModuleDefinitionByFriendlyName(string frie /// ----------------------------------------------------------------------------- /// /// GetModuleDefinitions gets a Dictionary of Module Definitions. - /// + /// /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleDefinitions() { - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( DataCache.ModuleDefinitionCacheKey, DataCache.ModuleDefinitionCachePriority), GetModuleDefinitionsCallBack); @@ -153,7 +102,7 @@ public static Dictionary GetModuleDefinitions() /// GetModuleDefinitionsByDesktopModuleID gets a Dictionary of Module Definitions /// with a particular DesktopModuleID, keyed by the FriendlyName. /// - /// The ID of the Desktop Module. + /// The ID of the Desktop Module. /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleDefinitionsByDesktopModuleID(int desktopModuleID) @@ -186,7 +135,7 @@ public static ModuleDefinitionInfo GetModuleDefinitionByDefinitionName(string de /// /// The Module Definition to save. /// A flag that determines whether the child objects are also saved. - /// A flag that determines whether to clear the host cache. + /// A flag that determines whether to clear the host cache. /// /// ----------------------------------------------------------------------------- public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bool saveChildren, bool clearCache) @@ -195,7 +144,7 @@ public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bo if (moduleDefinitionID == Null.NullInteger) { // Add new Module Definition - moduleDefinitionID = dataProvider.AddModuleDefinition( + moduleDefinitionID = dataProvider.AddModuleDefinition( moduleDefinition.DesktopModuleID, moduleDefinition.FriendlyName, moduleDefinition.DefinitionName, @@ -207,7 +156,7 @@ public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bo // Upgrade Module Definition dataProvider.UpdateModuleDefinition(moduleDefinition.ModuleDefID, moduleDefinition.FriendlyName, moduleDefinition.DefinitionName, moduleDefinition.DefaultCacheTime, UserController.Instance.GetCurrentUserInfo().UserID); } - + if (saveChildren) { foreach (KeyValuePair kvp in moduleDefinition.Permissions) @@ -228,7 +177,7 @@ public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bo permissionController.AddPermission(kvp.Value); } } - + foreach (KeyValuePair kvp in moduleDefinition.ModuleControls) { kvp.Value.ModuleDefID = moduleDefinitionID; @@ -239,17 +188,68 @@ public static int SaveModuleDefinition(ModuleDefinitionInfo moduleDefinition, bo { kvp.Value.ModuleControlID = moduleControl.ModuleControlID; } - + ModuleControlController.SaveModuleControl(kvp.Value, clearCache); } } - + if (clearCache) { DataCache.ClearHostCache(true); } - + return moduleDefinitionID; } + + /// ----------------------------------------------------------------------------- + /// + /// GetModuleDefinitionByID gets a Module Definition by its ID. + /// + /// The object of the Module Definition. + /// ----------------------------------------------------------------------------- + public void DeleteModuleDefinition(ModuleDefinitionInfo objModuleDefinition) + { + this.DeleteModuleDefinition(objModuleDefinition.ModuleDefID); + } + + /// ----------------------------------------------------------------------------- + /// + /// DeleteModuleDefinition deletes a Module Definition By ID. + /// + /// The ID of the Module Definition to delete. + /// ----------------------------------------------------------------------------- + public void DeleteModuleDefinition(int moduleDefinitionId) + { + // Delete associated permissions + var permissionController = new PermissionController(); + foreach (PermissionInfo permission in permissionController.GetPermissionsByModuleDefID(moduleDefinitionId)) + { + permissionController.DeletePermission(permission.PermissionID); + } + + dataProvider.DeleteModuleDefinition(moduleDefinitionId); + DataCache.ClearHostCache(true); + + // queue remove module definition from search index + var document = new SearchDocumentToDelete + { + ModuleDefId = moduleDefinitionId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetModuleDefinitionsCallBack gets a Dictionary of Module Definitions from + /// the Database. + /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetModuleDefinitionsCallBack(CacheItemArgs cacheItemArgs) + { + 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 f9106b2abd3..5e73a315ea5 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionInfo.cs @@ -35,6 +35,25 @@ public ModuleDefinitionInfo() this.ModuleDefID = Null.NullInteger; } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Dictionary of ModuleControls that are part of this definition. + /// + /// A Dictionary(Of String, ModuleControlInfo). + /// ----------------------------------------------------------------------------- + public Dictionary ModuleControls + { + get + { + if (this._ModuleControls == null) + { + this.LoadControls(); + } + + return this._ModuleControls; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Module Definition ID. @@ -85,32 +104,13 @@ public string DefinitionName set { this._definitionName = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Dictionary of ModuleControls that are part of this definition. - /// - /// A Dictionary(Of String, ModuleControlInfo). - /// ----------------------------------------------------------------------------- - public Dictionary ModuleControls - { - get - { - if (this._ModuleControls == null) - { - this.LoadControls(); - } - - return this._ModuleControls; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the Dictionary of Permissions that are part of this definition. /// /// A String. /// ----------------------------------------------------------------------------- - public Dictionary Permissions { get; private set; } + public Dictionary Permissions { get; private set; } /// ----------------------------------------------------------------------------- /// @@ -124,13 +124,13 @@ public int KeyID { return this.ModuleDefID; } - + set { this.ModuleDefID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a ModuleDefinitionInfo from a Data Reader. @@ -148,11 +148,11 @@ public void Fill(IDataReader dr) this.DefinitionName = Null.SetNullString(dr["DefinitionName"]); } } - + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the ModuleDefinitionInfo. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -174,12 +174,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + if (reader.NodeType == XmlNodeType.Element && reader.Name == "moduleControls") { this.ReadModuleControls(reader); @@ -199,7 +199,7 @@ public void ReadXml(XmlReader reader) { this.DefaultCacheTime = int.Parse(elementvalue); } - + break; case "permissions": // Ignore permissons node reader.Skip(); @@ -212,7 +212,7 @@ public void ReadXml(XmlReader reader) { reader.ReadElementContentAsString(); } - + break; } } @@ -237,20 +237,20 @@ public void WriteXml(XmlWriter writer) // Write start of Module Controls writer.WriteStartElement("moduleControls"); - + // Iterate through controls foreach (ModuleControlInfo control in this.ModuleControls.Values) { control.WriteXml(writer); } - + // Write end of Module Controls writer.WriteEndElement(); // Write end of main element writer.WriteEndElement(); - } - + } + public void LoadControls() { this._ModuleControls = this.ModuleDefID > Null.NullInteger ? ModuleControlController.GetModuleControlsByModuleDefinitionID(this.ModuleDefID) : new Dictionary(); @@ -271,7 +271,7 @@ private void ReadModuleControls(XmlReader reader) var moduleControl = new ModuleControlInfo(); moduleControl.ReadXml(reader); this.ModuleControls.Add(moduleControl.ControlKey, moduleControl); - } + } while (reader.ReadToNextSibling("moduleControl")); } } diff --git a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs index 2f623a9b90d..29608792094 100644 --- a/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs +++ b/DNN Platform/Library/Entities/Modules/Definitions/ModuleDefinitionValidator.cs @@ -56,7 +56,7 @@ public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) default: return ModuleDefinitionVersion.VUnknown; } - + break; case "SkinObject": retValue = ModuleDefinitionVersion.V2_Skin; @@ -68,13 +68,13 @@ public ModuleDefinitionVersion GetModuleDefinitionVersion(Stream xmlStream) retValue = ModuleDefinitionVersion.VUnknown; break; } - + break; default: retValue = ModuleDefinitionVersion.VUnknown; break; } - + return retValue; } @@ -83,7 +83,7 @@ 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"]; @@ -91,10 +91,10 @@ private static string GetLocalizedString(string key) { return key; } - + return Localization.GetString(key, objPortalSettings); } - + private string GetDnnSchemaPath(Stream xmlStream) { ModuleDefinitionVersion Version = this.GetModuleDefinitionVersion(xmlStream); @@ -116,7 +116,7 @@ private string GetDnnSchemaPath(Stream xmlStream) 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 cf82a74dc5f..461393d3423 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleController.cs @@ -38,9 +38,9 @@ namespace DotNetNuke.Entities.Modules /// ----------------------------------------------------------------------------- public class DesktopModuleController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DesktopModuleController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DesktopModuleController)); private static readonly DataProvider DataProvider = DataProvider.Instance(); - + public static void AddModuleCategory(string category) { var termController = Util.GetTermController(); @@ -79,7 +79,7 @@ public static void DeleteDesktopModule(string moduleName) { var controller = new DesktopModuleController(); controller.DeleteDesktopModule(desktopModule.DesktopModuleID); - + // Delete the Package PackageController.Instance.DeleteExtensionPackage(PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID)); } @@ -93,7 +93,7 @@ public static void DeleteDesktopModule(string moduleName) /// if the DesktopModule is in the cache. If it is not in the cache it then makes a call /// to the Dataprovider. /// The ID of the Desktop Module to get. - /// The ID of the portal. + /// The ID of the portal. /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portalID) @@ -111,101 +111,19 @@ public static DesktopModuleInfo GetDesktopModule(int desktopModuleID, int portal .FirstOrDefault(); } - if (module == null) - { - Logger.WarnFormat("Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); - } - - 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) + if (module == null) { - contentType = new ContentType { ContentType = "DesktopModule" }; - contentType.ContentTypeId = typeController.AddContentType(contentType); + Logger.WarnFormat("Unable to find module by module ID. ID:{0} PortalID:{1}", desktopModuleID, portalID); } - 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); + return module; } /// ----------------------------------------------------------------------------- /// /// GetDesktopModuleByPackageID gets a Desktop Module by its Package ID. /// - /// The ID of the Package. + /// The ID of the Package. /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) @@ -215,11 +133,11 @@ public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) select kvp.Value) .FirstOrDefault(); - if (desktopModuleByPackageID == null) - { - Logger.WarnFormat("Unable to find module by package ID. ID:{0}", packageID); - } - + if (desktopModuleByPackageID == null) + { + Logger.WarnFormat("Unable to find module by package ID. ID:{0}", packageID); + } + return desktopModuleByPackageID; } @@ -231,7 +149,7 @@ public static DesktopModuleInfo GetDesktopModuleByPackageID(int packageID) /// if the DesktopModule is in the cache. If it is not in the cache it then makes a call /// to the Dataprovider. /// The name of the Desktop Module to get. - /// The ID of the portal. + /// The ID of the portal. /// /// ----------------------------------------------------------------------------- public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, int portalID) @@ -240,11 +158,11 @@ public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, where kvp.Value.ModuleName == moduleName select kvp.Value).FirstOrDefault(); - if (desktopModuleByModuleName == null) - { - Logger.WarnFormat("Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); - } - + if (desktopModuleByModuleName == null) + { + Logger.WarnFormat("Unable to find module by name. Name:{0} portalId:{1}", moduleName, portalID); + } + return desktopModuleByModuleName; } @@ -253,7 +171,7 @@ public static DesktopModuleInfo GetDesktopModuleByModuleName(string moduleName, /// GetDesktopModules gets a Dictionary of Desktop Modules. /// /// The ID of the Portal (Use PortalID = Null.NullInteger (-1) to get - /// all the DesktopModules including Modules not allowed for the current portal. + /// all the DesktopModules including Modules not allowed for the current portal. /// /// ----------------------------------------------------------------------------- public static Dictionary GetDesktopModules(int portalID) @@ -265,11 +183,11 @@ public static DesktopModuleInfo GetDesktopModuleByFriendlyName(string friendlyNa { var module = (from kvp in GetDesktopModulesInternal(Null.NullInteger) where kvp.Value.FriendlyName == friendlyName select kvp.Value).FirstOrDefault(); - if (module == null) - { - Logger.WarnFormat("Unable to find module by friendly name. Name:{0}", friendlyName); - } - + if (module == null) + { + Logger.WarnFormat("Unable to find module by friendly name. Name:{0}", friendlyName); + } + return module; } @@ -279,14 +197,14 @@ public static DesktopModuleInfo GetDesktopModuleByFriendlyName(string friendlyNa /// /// The Desktop Module to save. /// A flag that determines whether the child objects are also saved. - /// A flag that determines whether to clear the host cache. + /// A flag that determines whether to clear the host cache. /// /// ----------------------------------------------------------------------------- public static int SaveDesktopModule(DesktopModuleInfo desktopModule, bool saveChildren, bool clearCache) { 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); @@ -299,7 +217,7 @@ public static int AddDesktopModuleToPortal(int portalID, DesktopModuleInfo deskt DesktopModulePermissionController.AddDesktopModulePermission(permission); } } - + return portalDesktopModuleID; } @@ -310,7 +228,7 @@ public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bo if (portalDesktopModule == null) { portalDesktopModuleID = DataProvider.Instance().AddPortalDesktopModule(portalId, desktopModuleId, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PortalDesktopModuleID", portalDesktopModuleID.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -335,153 +253,22 @@ public static int AddDesktopModuleToPortal(int portalId, int desktopModuleId, bo { 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) - { - var desktopModuleID = desktopModule.DesktopModuleID; - if (desktopModuleID == Null.NullInteger) - { - CreateContentItem(desktopModule); - desktopModuleID = DataProvider.AddDesktopModule( - desktopModule.PackageID, - desktopModule.ModuleName, - desktopModule.FolderName, - desktopModule.FriendlyName, - desktopModule.Description, - desktopModule.Version, - desktopModule.IsPremium, - desktopModule.IsAdmin, - desktopModule.BusinessControllerClass, - desktopModule.SupportedFeatures, - (int)desktopModule.Shareable, - desktopModule.CompatibleVersions, - desktopModule.Dependencies, - desktopModule.Permissions, - desktopModule.ContentItemId, - UserController.Instance.GetCurrentUserInfo().UserID, - desktopModule.AdminPage, desktopModule.HostPage); - EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_CREATED); - } - else - { - // Update ContentItem If neccessary - if (desktopModule.ContentItemId == Null.NullInteger) - { - CreateContentItem(desktopModule); - } - - DataProvider.UpdateDesktopModule( - desktopModule.DesktopModuleID, - desktopModule.PackageID, - desktopModule.ModuleName, - desktopModule.FolderName, - desktopModule.FriendlyName, - desktopModule.Description, - desktopModule.Version, - desktopModule.IsPremium, - desktopModule.IsAdmin, - desktopModule.BusinessControllerClass, - desktopModule.SupportedFeatures, - (int)desktopModule.Shareable, - desktopModule.CompatibleVersions, - desktopModule.Dependencies, - desktopModule.Permissions, - desktopModule.ContentItemId, - UserController.Instance.GetCurrentUserInfo().UserID, - desktopModule.AdminPage, - desktopModule.HostPage); - - // Update Tags - if (saveTerms) - { - var termController = Util.GetTermController(); - termController.RemoveTermsFromContent(desktopModule); - foreach (var term in desktopModule.Terms) - { - termController.AddTermToContent(term, desktopModule); - } - } - - EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_UPDATED); - } - - if (saveChildren) - { - foreach (var definition in desktopModule.ModuleDefinitions.Values) - { - definition.DesktopModuleID = desktopModuleID; - var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName(definition.DefinitionName, desktopModuleID); - if (moduleDefinition != null) - { - definition.ModuleDefID = moduleDefinition.ModuleDefID; - } - - ModuleDefinitionController.SaveModuleDefinition(definition, true, clearCache); - } - } - - if (clearCache) - { - DataCache.ClearHostCache(true); - } - - return desktopModuleID; + return portalDesktopModuleID; } - private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleInfo) - { - var businessController = Reflection.CreateType(desktopModuleInfo.BusinessControllerClass); - var controller = Reflection.CreateObject(desktopModuleInfo.BusinessControllerClass, desktopModuleInfo.BusinessControllerClass); - - desktopModuleInfo.IsPortable = businessController.GetInterfaces().Contains(typeof(IPortable)); -#pragma warning disable 0618 - desktopModuleInfo.IsSearchable = (controller is ModuleSearchBase) || businessController.GetInterfaces().Contains(typeof(ISearchable)); -#pragma warning restore 0618 - desktopModuleInfo.IsUpgradeable = businessController.GetInterfaces().Contains(typeof(IUpgradeable)); - } - public static void AddDesktopModuleToPortals(int desktopModuleId) { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { AddDesktopModuleToPortal(portal.PortalID, desktopModuleId, true, false); } - + DataCache.ClearHostCache(true); } @@ -502,7 +289,7 @@ public static void AddDesktopModulesToPortal(int portalId) } } } - + DataCache.ClearPortalCache(portalId, true); } @@ -535,14 +322,14 @@ public static SortedList GetPortalDesktopModule lstModules.Add(desktopModule.FriendlyName, desktopModule); } } - + return lstModules; } public static void RemoveDesktopModuleFromPortal(int portalId, int desktopModuleId, bool clearCache) { DataProvider.Instance().DeletePortalDesktopModules(portalId, desktopModuleId); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "DesktopModuleID", desktopModuleId.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -557,7 +344,7 @@ public static void RemoveDesktopModuleFromPortal(int portalId, int desktopModule public static void RemoveDesktopModuleFromPortals(int desktopModuleId) { DataProvider.Instance().DeletePortalDesktopModules(Null.NullInteger, desktopModuleId); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "DesktopModuleID", desktopModuleId.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -569,7 +356,7 @@ public static void RemoveDesktopModuleFromPortals(int desktopModuleId) public static void RemoveDesktopModulesFromPortal(int portalId) { DataProvider.Instance().DeletePortalDesktopModules(portalId, Null.NullInteger); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PortalID", portalId.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -595,14 +382,162 @@ public static void SerializePortalDesktopModules(XmlWriter writer, int portalId) writer.WriteElementString("rolename", permission.RoleName); writer.WriteEndElement(); } - + writer.WriteEndElement(); writer.WriteEndElement(); } - + writer.WriteEndElement(); - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } + + 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) + { + var desktopModuleID = desktopModule.DesktopModuleID; + if (desktopModuleID == Null.NullInteger) + { + CreateContentItem(desktopModule); + desktopModuleID = DataProvider.AddDesktopModule( + desktopModule.PackageID, + desktopModule.ModuleName, + desktopModule.FolderName, + desktopModule.FriendlyName, + desktopModule.Description, + desktopModule.Version, + desktopModule.IsPremium, + desktopModule.IsAdmin, + desktopModule.BusinessControllerClass, + desktopModule.SupportedFeatures, + (int)desktopModule.Shareable, + desktopModule.CompatibleVersions, + desktopModule.Dependencies, + desktopModule.Permissions, + desktopModule.ContentItemId, + UserController.Instance.GetCurrentUserInfo().UserID, + desktopModule.AdminPage, desktopModule.HostPage); + EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_CREATED); + } + else + { + // Update ContentItem If neccessary + if (desktopModule.ContentItemId == Null.NullInteger) + { + CreateContentItem(desktopModule); + } + + DataProvider.UpdateDesktopModule( + desktopModule.DesktopModuleID, + desktopModule.PackageID, + desktopModule.ModuleName, + desktopModule.FolderName, + desktopModule.FriendlyName, + desktopModule.Description, + desktopModule.Version, + desktopModule.IsPremium, + desktopModule.IsAdmin, + desktopModule.BusinessControllerClass, + desktopModule.SupportedFeatures, + (int)desktopModule.Shareable, + desktopModule.CompatibleVersions, + desktopModule.Dependencies, + desktopModule.Permissions, + desktopModule.ContentItemId, + UserController.Instance.GetCurrentUserInfo().UserID, + desktopModule.AdminPage, + desktopModule.HostPage); + + // Update Tags + if (saveTerms) + { + var termController = Util.GetTermController(); + termController.RemoveTermsFromContent(desktopModule); + foreach (var term in desktopModule.Terms) + { + termController.AddTermToContent(term, desktopModule); + } + } + + EventLogController.Instance.AddLog(desktopModule, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULE_UPDATED); + } + + if (saveChildren) + { + foreach (var definition in desktopModule.ModuleDefinitions.Values) + { + definition.DesktopModuleID = desktopModuleID; + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByDefinitionName(definition.DefinitionName, desktopModuleID); + if (moduleDefinition != null) + { + definition.ModuleDefID = moduleDefinition.ModuleDefID; + } + + ModuleDefinitionController.SaveModuleDefinition(definition, true, clearCache); + } + } + + if (clearCache) + { + DataCache.ClearHostCache(true); + } + + return desktopModuleID; + } + internal static void AddDesktopModulePageToPortal(DesktopModuleInfo desktopModule, string pageName, int portalId, ref bool createdNewPage, ref bool addedNewModule) { var tabPath = string.Format("//{0}//{1}", portalId == Null.NullInteger ? "Host" : "Admin", pageName); @@ -612,7 +547,7 @@ internal static void AddDesktopModulePageToPortal(DesktopModuleInfo desktopModul { if (portalId == Null.NullInteger) { - existTab = Upgrade.AddHostPage( + existTab = Upgrade.AddHostPage( pageName, desktopModule.Page.Description, desktopModule.Page.Icon, @@ -621,7 +556,7 @@ internal static void AddDesktopModulePageToPortal(DesktopModuleInfo desktopModul } else { - existTab = Upgrade.AddAdminPage( + existTab = Upgrade.AddAdminPage( PortalController.Instance.GetPortal(portalId), pageName, desktopModule.Page.Description, @@ -657,7 +592,7 @@ internal static void AddDesktopModuleToPage(DesktopModuleInfo desktopModule, Tab { if (tabModules.All(m => m.ModuleDefinition.ModuleDefID != moduleDefinition.ModuleDefID)) { - Upgrade.AddModuleToPage( + Upgrade.AddModuleToPage( tab, moduleDefinition.ModuleDefID, desktopModule.Page.Description, @@ -667,6 +602,71 @@ internal static void AddDesktopModuleToPage(DesktopModuleInfo desktopModule, Tab addedNewModule = true; } } - } + } + + 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); + } + + private void CheckInterfacesImplementation(ref DesktopModuleInfo desktopModuleInfo) + { + var businessController = Reflection.CreateType(desktopModuleInfo.BusinessControllerClass); + var controller = Reflection.CreateObject(desktopModuleInfo.BusinessControllerClass, desktopModuleInfo.BusinessControllerClass); + + desktopModuleInfo.IsPortable = businessController.GetInterfaces().Contains(typeof(IPortable)); +#pragma warning disable 0618 + desktopModuleInfo.IsSearchable = (controller is ModuleSearchBase) || businessController.GetInterfaces().Contains(typeof(ISearchable)); +#pragma warning restore 0618 + desktopModuleInfo.IsUpgradeable = businessController.GetInterfaces().Contains(typeof(IUpgradeable)); + } } } diff --git a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs index 7b6676d4d14..9abc70bd1a6 100644 --- a/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/DesktopModuleInfo.cs @@ -32,7 +32,7 @@ namespace DotNetNuke.Entities.Modules /// ----------------------------------------------------------------------------- [Serializable] public class DesktopModuleInfo : ContentItem, IXmlSerializable - { + { private Dictionary _moduleDefinitions; private PageInfo _pageInfo; @@ -45,114 +45,34 @@ public DesktopModuleInfo() this.DesktopModuleID = Null.NullInteger; this.SupportedFeatures = Null.NullInteger; this.Shareable = ModuleSharing.Unknown; - } - - [Serializable] - public class PageInfo : IXmlSerializable - { - [XmlAttribute("type")] - public string Type { get; set; } - - [XmlAttribute("common")] - public bool IsCommon { get; set; } - - [XmlElement("name")] - public string Name { get; set; } - - [XmlElement("icon")] - public string Icon { get; set; } - - [XmlElement("largeIcon")] - public string LargeIcon { get; set; } - - [XmlElement("description")] - public string Description { get; set; } - - public bool HasAdminPage() - { - return this.Type.IndexOf("admin", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; - } - - public bool HasHostPage() - { - return this.Type.IndexOf("host", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; - } - - public XmlSchema GetSchema() - { - return null; - } + } - public void ReadXml(XmlReader reader) + /// ----------------------------------------------------------------------------- + /// + /// Gets the Module Definitions for this Desktop Module. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public Dictionary ModuleDefinitions + { + get { - while (!reader.EOF) + if (this._moduleDefinitions == null) { - if (reader.NodeType == XmlNodeType.EndElement) - { - if (reader.Name == "page") - { - break; - } - - reader.Read(); - continue; - } - - if (reader.NodeType == XmlNodeType.Whitespace) + if (this.DesktopModuleID > Null.NullInteger) { - reader.Read(); - continue; + this._moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(this.DesktopModuleID); } - - switch (reader.Name) + else { - case "page": - this.Type = reader.GetAttribute("type"); - var commonValue = reader.GetAttribute("common"); - if (!string.IsNullOrEmpty(commonValue)) - { - this.IsCommon = commonValue.Equals("true", StringComparison.InvariantCultureIgnoreCase); - } - - reader.Read(); - break; - case "name": - this.Name = reader.ReadElementContentAsString(); - break; - case "icon": - this.Icon = reader.ReadElementContentAsString(); - break; - case "largeIcon": - this.LargeIcon = reader.ReadElementContentAsString(); - break; - case "description": - this.Description = reader.ReadElementContentAsString(); - break; - default: - reader.Read(); - break; + this._moduleDefinitions = new Dictionary(); } } - } - - public void WriteXml(XmlWriter writer) - { - // Write start of main elemenst - writer.WriteStartElement("page"); - writer.WriteAttributeString("type", this.Type); - writer.WriteAttributeString("common", this.IsCommon.ToString().ToLowerInvariant()); - // write out properties - writer.WriteElementString("name", this.Name); - writer.WriteElementString("icon", this.Icon); - writer.WriteElementString("largeIcon", this.LargeIcon); - writer.WriteElementString("description", this.Description); - - // Write end of main element - writer.WriteEndElement(); + return this._moduleDefinitions; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the ID of the Desktop Module. @@ -189,7 +109,7 @@ public string Category Term term = (from Term t in this.Terms select t).FirstOrDefault(); return (term != null) ? term.Name : string.Empty; } - + set { this.Terms.Clear(); @@ -279,7 +199,7 @@ public bool IsPortable { return this.GetFeature(DesktopModuleSupportedFeature.IsPortable); } - + set { this.UpdateFeature(DesktopModuleSupportedFeature.IsPortable, value); @@ -306,7 +226,7 @@ public bool IsSearchable { return this.GetFeature(DesktopModuleSupportedFeature.IsSearchable); } - + set { this.UpdateFeature(DesktopModuleSupportedFeature.IsSearchable, value); @@ -325,7 +245,7 @@ public bool IsUpgradeable { return this.GetFeature(DesktopModuleSupportedFeature.IsUpgradeable); } - + set { this.UpdateFeature(DesktopModuleSupportedFeature.IsUpgradeable, value); @@ -341,32 +261,6 @@ public ModuleSharing Shareable set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Module Definitions for this Desktop Module. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - public Dictionary ModuleDefinitions - { - get - { - if (this._moduleDefinitions == null) - { - if (this.DesktopModuleID > Null.NullInteger) - { - this._moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(this.DesktopModuleID); - } - else - { - this._moduleDefinitions = new Dictionary(); - } - } - - return this._moduleDefinitions; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Name of the Desktop Module. @@ -420,13 +314,13 @@ public PageInfo Page return this._pageInfo; } - + set { this._pageInfo = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a DesktopModuleInfo from a Data Reader. @@ -453,15 +347,15 @@ public override void Fill(IDataReader dr) this.Shareable = (ModuleSharing)Null.SetNullInteger(dr["Shareable"]); this.AdminPage = Null.SetNullString(dr["AdminPage"]); this.HostPage = Null.SetNullString(dr["HostPage"]); - + // Call the base classes fill method to populate base class proeprties this.FillInternal(dr); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the DesktopModule. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -483,12 +377,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + if (reader.NodeType == XmlNodeType.Element && reader.Name == "moduleDefinitions" && !reader.IsEmptyElement) { this.ReadModuleDefinitions(reader); @@ -535,7 +429,7 @@ public void ReadXml(XmlReader reader) { this.HostPage = this.Page.Name; } - + break; case "isAdmin": bool isAdmin; @@ -552,7 +446,7 @@ public void ReadXml(XmlReader reader) { reader.ReadElementContentAsString(); } - + break; } } @@ -587,14 +481,14 @@ public void WriteXml(XmlWriter writer) writer.WriteAttributeString("type", "Portable"); writer.WriteEndElement(); } - + if (this.IsSearchable) { writer.WriteStartElement("supportedFeature"); writer.WriteAttributeString("type", "Searchable"); writer.WriteEndElement(); } - + if (this.IsUpgradeable) { writer.WriteStartElement("supportedFeature"); @@ -624,7 +518,7 @@ public void WriteXml(XmlWriter writer) writer.WriteString("Unsupported"); break; } - + writer.WriteEndElement(); } @@ -636,14 +530,14 @@ public void WriteXml(XmlWriter writer) { definition.WriteXml(writer); } - + // Write end of Module Definitions writer.WriteEndElement(); // Write end of main element writer.WriteEndElement(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Clears a Feature from the Features. @@ -725,7 +619,7 @@ private void ReadSupportedFeatures(XmlReader reader) break; } } - } + } while (reader.ReadToNextSibling("supportedFeature")); } @@ -776,14 +670,14 @@ private void ReadModuleDefinitions(XmlReader reader) // Add to the collection this.ModuleDefinitions.Add(moduleDefinition.FriendlyName, moduleDefinition); - } + } while (reader.ReadToNextSibling("moduleDefinition")); } private void ReadPageInfo(XmlReader reader) { this.Page = new PageInfo(); - + // Load it from the Xml this.Page.ReadXml(reader.ReadSubtree()); @@ -796,6 +690,112 @@ private void ReadPageInfo(XmlReader reader) { this.HostPage = this.Page.Name; } - } + } + + [Serializable] + public class PageInfo : IXmlSerializable + { + [XmlAttribute("type")] + public string Type { get; set; } + + [XmlAttribute("common")] + public bool IsCommon { get; set; } + + [XmlElement("name")] + public string Name { get; set; } + + [XmlElement("icon")] + public string Icon { get; set; } + + [XmlElement("largeIcon")] + public string LargeIcon { get; set; } + + [XmlElement("description")] + public string Description { get; set; } + + public bool HasAdminPage() + { + return this.Type.IndexOf("admin", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; + } + + public bool HasHostPage() + { + return this.Type.IndexOf("host", StringComparison.InvariantCultureIgnoreCase) > Null.NullInteger; + } + + public XmlSchema GetSchema() + { + return null; + } + + public void ReadXml(XmlReader reader) + { + while (!reader.EOF) + { + if (reader.NodeType == XmlNodeType.EndElement) + { + if (reader.Name == "page") + { + break; + } + + reader.Read(); + continue; + } + + if (reader.NodeType == XmlNodeType.Whitespace) + { + reader.Read(); + continue; + } + + switch (reader.Name) + { + case "page": + this.Type = reader.GetAttribute("type"); + var commonValue = reader.GetAttribute("common"); + if (!string.IsNullOrEmpty(commonValue)) + { + this.IsCommon = commonValue.Equals("true", StringComparison.InvariantCultureIgnoreCase); + } + + reader.Read(); + break; + case "name": + this.Name = reader.ReadElementContentAsString(); + break; + case "icon": + this.Icon = reader.ReadElementContentAsString(); + break; + case "largeIcon": + this.LargeIcon = reader.ReadElementContentAsString(); + break; + case "description": + this.Description = reader.ReadElementContentAsString(); + break; + default: + reader.Read(); + break; + } + } + } + + public void WriteXml(XmlWriter writer) + { + // Write start of main elemenst + writer.WriteStartElement("page"); + writer.WriteAttributeString("type", this.Type); + writer.WriteAttributeString("common", this.IsCommon.ToString().ToLowerInvariant()); + + // write out properties + writer.WriteElementString("name", this.Name); + writer.WriteElementString("icon", this.Icon); + writer.WriteElementString("largeIcon", this.LargeIcon); + writer.WriteElementString("description", this.Description); + + // Write end of main element + writer.WriteEndElement(); + } + } } } diff --git a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs index bdb3fbd5839..ce0a51dd066 100644 --- a/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs +++ b/DNN Platform/Library/Entities/Modules/EventMessageProcessor.cs @@ -20,14 +20,14 @@ public class EventMessageProcessor : EventMessageProcessorBase 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", + 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 @@ -67,10 +67,10 @@ public override bool ProcessMessage(EventMessage message) message.ExceptionMessage = ex.Message; return false; } - + return true; } - + private static void ImportModule(EventMessage message) { try @@ -83,10 +83,10 @@ private static void ImportModule(EventMessage message) string Content = HttpUtility.HtmlDecode(message.Attributes["Content"]); string Version = message.Attributes["Version"]; int UserID = Convert.ToInt32(message.Attributes["UserId"]); - + // call the IPortable interface for the module/version ((IPortable)controller).ImportModule(ModuleId, Content, Version, UserID); - + // Synchronize Module Cache ModuleController.SynchronizeModule(ModuleId); } @@ -114,7 +114,7 @@ private static void UpgradeModule(EventMessage message) { // call the IUpgradeable interface for the module/version string Results = ((IUpgradeable)controller).UpgradeModule(Version); - + // log the upgrade results var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_UPDATED.ToString() }; log.AddProperty("Module Upgraded", BusinessControllerClass); @@ -123,11 +123,11 @@ private static void UpgradeModule(EventMessage message) { log.AddProperty("Results", Results); } - + LogController.Instance.AddLog(log); } } - + UpdateSupportedFeatures(controller, Convert.ToInt32(message.Attributes["DesktopModuleId"])); } catch (Exception exc) diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs index 105d66e4ed5..255ef4f4815 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlController.cs @@ -50,40 +50,11 @@ public static void DeleteModuleControl(int moduleControlID) DataCache.ClearHostCache(true); } - /// ----------------------------------------------------------------------------- - /// - /// GetModuleControls gets a Dictionary of Module Controls from - /// the Cache. - /// - /// ----------------------------------------------------------------------------- - private static Dictionary GetModuleControls() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.ModuleControlsCacheKey, - DataCache.ModuleControlsCacheTimeOut, - DataCache.ModuleControlsCachePriority), - GetModuleControlsCallBack); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetModuleControlsCallBack gets a Dictionary of Module Controls from - /// the Database. - /// - /// The CacheItemArgs object that contains the parameters - /// needed for the database call. - /// ----------------------------------------------------------------------------- - private static object GetModuleControlsCallBack(CacheItemArgs cacheItemArgs) - { - return CBO.FillDictionary(key, dataProvider.GetModuleControls(), new Dictionary()); - } - /// ----------------------------------------------------------------------------- /// /// GetModuleControl gets a single Module Control from the database. /// - /// The ID of the Module Control to fetch. + /// The ID of the Module Control to fetch. /// /// ----------------------------------------------------------------------------- public static ModuleControlInfo GetModuleControl(int moduleControlID) @@ -98,7 +69,7 @@ public static ModuleControlInfo GetModuleControl(int moduleControlID) /// /// GetModuleControl gets a Dictionary of Module Controls by Module Definition. /// - /// The ID of the Module Definition. + /// The ID of the Module Definition. /// /// ----------------------------------------------------------------------------- public static Dictionary GetModuleControlsByModuleDefinitionID(int moduleDefID) @@ -112,7 +83,7 @@ public static Dictionary GetModuleControlsByModuleDef /// GetModuleControlByControlKey gets a single Module Control from the database. /// /// The key for the control. - /// The ID of the Module Definition. + /// The ID of the Module Definition. /// /// ----------------------------------------------------------------------------- public static ModuleControlInfo GetModuleControlByControlKey(string controlKey, int moduleDefID) @@ -129,7 +100,7 @@ where kvp.Value.ControlKey.Equals(controlKey, StringComparison.InvariantCultureI /// SaveModuleControl updates a Module Control in the database. /// /// The Module Control to save. - /// A flag that determines whether to clear the host cache. + /// A flag that determines whether to clear the host cache. /// /// ----------------------------------------------------------------------------- public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearCache) @@ -138,7 +109,7 @@ public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearC if (moduleControlID == Null.NullInteger) { // Add new Module Definition - moduleControlID = dataProvider.AddModuleControl( + moduleControlID = dataProvider.AddModuleControl( moduleControl.ModuleDefID, moduleControl.ControlKey, moduleControl.ControlTitle, @@ -154,7 +125,7 @@ public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearC else { // Upgrade Module Control - dataProvider.UpdateModuleControl( + dataProvider.UpdateModuleControl( moduleControl.ModuleControlID, moduleControl.ModuleDefID, moduleControl.ControlKey, @@ -168,12 +139,12 @@ public static int SaveModuleControl(ModuleControlInfo moduleControl, bool clearC moduleControl.SupportsPopUps, UserController.Instance.GetCurrentUserInfo().UserID); } - + if (clearCache) { DataCache.ClearHostCache(true); } - + return moduleControlID; } @@ -187,5 +158,34 @@ public static void UpdateModuleControl(ModuleControlInfo objModuleControl) { SaveModuleControl(objModuleControl, true); } + + /// ----------------------------------------------------------------------------- + /// + /// GetModuleControls gets a Dictionary of Module Controls from + /// the Cache. + /// + /// ----------------------------------------------------------------------------- + private static Dictionary GetModuleControls() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.ModuleControlsCacheKey, + DataCache.ModuleControlsCacheTimeOut, + DataCache.ModuleControlsCachePriority), + GetModuleControlsCallBack); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetModuleControlsCallBack gets a Dictionary of Module Controls from + /// the Database. + /// + /// The CacheItemArgs object that contains the parameters + /// needed for the database call. + /// ----------------------------------------------------------------------------- + private static object GetModuleControlsCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillDictionary(key, dataProvider.GetModuleControls(), new Dictionary()); + } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs index deb8d88bb88..76753d8ae11 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleControlInfo.cs @@ -94,7 +94,7 @@ public ModuleControlInfo() /// /// An Integer. /// ----------------------------------------------------------------------------- - public int ViewOrder { get; set; } + public int ViewOrder { get; set; } /// ----------------------------------------------------------------------------- /// @@ -108,13 +108,13 @@ public int KeyID { return this.ModuleControlID; } - + set { this.ModuleControlID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a ModuleControlInfo from a Data Reader. @@ -132,15 +132,15 @@ public void Fill(IDataReader dr) this.ControlType = (SecurityAccessLevel)Enum.Parse(typeof(SecurityAccessLevel), Null.SetNullString(dr["ControlType"])); this.ViewOrder = Null.SetNullInteger(dr["ViewOrder"]); this.SupportsPopUps = Null.SetNullBoolean(dr["SupportsPopUps"]); - + // Call the base classes fill method to populate base class proeprties this.FillInternal(dr); } - + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the ModuleControlInfo. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -162,12 +162,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + this.ReadXmlInternal(reader); switch (reader.Name) { @@ -192,14 +192,14 @@ public void ReadXml(XmlReader reader) { this.ViewOrder = int.Parse(elementvalue); } - + break; default: if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } - + break; } } @@ -227,9 +227,9 @@ public void WriteXml(XmlWriter writer) { writer.WriteElementString("viewOrder", this.ViewOrder.ToString()); } - + // Write end of main element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleController.cs b/DNN Platform/Library/Entities/Modules/ModuleController.cs index b96d593cde3..f01b204f812 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleController.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleController.cs @@ -228,6 +228,140 @@ public static void DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int p } } + /// + /// SerializeModule. + /// + /// The Xml Document to use for the Module. + /// The ModuleInfo object to serialize. + /// A flak that determines whether the content of the module is serialised. + /// + public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, bool includeContent) + { + var serializer = new XmlSerializer(typeof(ModuleInfo)); + var sw = new StringWriter(); + serializer.Serialize(sw, module); + xmlModule.LoadXml(sw.GetStringBuilder().ToString()); + XmlNode moduleNode = xmlModule.SelectSingleNode("module"); + if (moduleNode != null) + { + // ReSharper disable AssignNullToNotNullAttribute + if (moduleNode.Attributes != null) + { + moduleNode.Attributes.Remove(moduleNode.Attributes["xmlns:xsd"]); + moduleNode.Attributes.Remove(moduleNode.Attributes["xmlns:xsi"]); + } + + // remove unwanted elements + moduleNode.RemoveChild(moduleNode.SelectSingleNode("portalid")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabid")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabmoduleid")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("moduleorder")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("panename")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("isdeleted")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("versionGuid")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("localizedVersionGuid")); + moduleNode.RemoveChild(moduleNode.SelectSingleNode("content")); + + // support for localized templates + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("uniqueId")); + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); + // moduleNode.RemoveChild(moduleNode.SelectSingleNode("cultureCode")); + if (Null.IsNull(module.DefaultLanguageGuid)) + { + moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); + } + + var xmlNodeList = moduleNode.SelectNodes("modulepermissions/permission"); + if (xmlNodeList != null) + { + foreach (XmlNode nodePermission in xmlNodeList) + { + nodePermission.RemoveChild(nodePermission.SelectSingleNode("modulepermissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("moduleid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); + } + } + + if (includeContent) + { + AddContent(moduleNode, module); + } + + // serialize ModuleSettings and TabModuleSettings + XmlUtils.SerializeHashtable(module.ModuleSettings, xmlModule, moduleNode, "modulesetting", "settingname", "settingvalue"); + XmlUtils.SerializeHashtable(module.TabModuleSettings, xmlModule, moduleNode, "tabmodulesetting", "settingname", "settingvalue"); + + // ReSharper restore AssignNullToNotNullAttribute + } + + XmlNode newNode = xmlModule.CreateElement("definition"); + ModuleDefinitionInfo objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(module.ModuleDefID); + newNode.InnerText = DesktopModuleController.GetDesktopModule(objModuleDef.DesktopModuleID, module.PortalID).ModuleName; + if (moduleNode != null) + { + moduleNode.AppendChild(newNode); + } + + // Add Module Definition Info + XmlNode definitionNode = xmlModule.CreateElement("moduledefinition"); + definitionNode.InnerText = objModuleDef.FriendlyName; + if (moduleNode != null) + { + moduleNode.AppendChild(definitionNode); + } + + return moduleNode; + } + + /// + /// Synchronizes the module content between cache and database. + /// + /// The module ID. + public static void SynchronizeModule(int moduleID) + { + var modules = Instance.GetTabModulesByModule(moduleID); + foreach (ModuleInfo module in modules) + { + Hashtable tabSettings = TabController.Instance.GetTabSettings(module.TabID); + if (tabSettings["CacheProvider"] != null && tabSettings["CacheProvider"].ToString().Length > 0) + { + var outputProvider = OutputCachingProvider.Instance(tabSettings["CacheProvider"].ToString()); + if (outputProvider != null) + { + outputProvider.Remove(module.TabID); + } + } + + if (module.CacheTime > 0) + { + var moduleProvider = ModuleCachingProvider.Instance(module.GetEffectiveCacheMethod()); + if (moduleProvider != null) + { + moduleProvider.Remove(module.TabModuleID); + } + } + + // Synchronize module is called when a module needs to indicate that the content + // has changed and the cache's should be refreshed. So we can update the Version + // and also the LastContentModificationDate + UpdateTabModuleVersion(module.TabModuleID); + dataProvider.UpdateModuleLastContentModifiedOnDate(module.ModuleID); + + // We should also indicate that the Transalation Status has changed + if (PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", module.PortalID, false)) + { + Instance.UpdateTranslationStatus(module, false); + } + + // and clear the cache + Instance.ClearCache(module.TabID); + } + } + /// /// Check if a ModuleInfo belongs to the referenced Tab or not. /// @@ -252,942 +386,1023 @@ public int GetMasterTabId(ModuleInfo module) 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) + /// + /// add a module to a page. + /// + /// moduleInfo for the module to create. + /// ID of the created module. + public int AddModule(ModuleInfo module) { - 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(); - } + // add module + this.AddModuleInternal(module); - protected override Func GetFactory() - { - return () => new ModuleController(); - } + var currentUser = UserController.Instance.GetCurrentUserInfo(); - private static void AddContent(XmlNode nodeModule, ModuleInfo module) - { - if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) + // Lets see if the module already exists + ModuleInfo tmpModule = this.GetModule(module.ModuleID, module.TabID, false); + if (tmpModule != null) { - try + // Module Exists already + if (tmpModule.IsDeleted) { - object businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); - var controller = businessController as IPortable; - if (controller != null) - { - string content = Convert.ToString(controller.ExportModule(module.ModuleID)); - if (!string.IsNullOrEmpty(content)) - { - content = XmlUtils.RemoveInvalidXmlCharacters(content); + var order = module.ModuleOrder; + var pane = module.PaneName; - // add attributes to XML document - if (nodeModule.OwnerDocument != null) - { - var existing = nodeModule.OwnerDocument.GetElementById("content"); - if (existing != null) - { - nodeModule.OwnerDocument.RemoveChild(existing); - } + // Restore Module + this.RestoreModule(module); - XmlNode newnode = nodeModule.OwnerDocument.CreateElement("content"); - XmlAttribute xmlattr = nodeModule.OwnerDocument.CreateAttribute("type"); - xmlattr.Value = Globals.CleanName(module.DesktopModule.ModuleName); - if (newnode.Attributes != null) - { - newnode.Attributes.Append(xmlattr); - } - - xmlattr = nodeModule.OwnerDocument.CreateAttribute("version"); - xmlattr.Value = module.DesktopModule.Version; - if (newnode.Attributes != null) - { - newnode.Attributes.Append(xmlattr); - } + TabChangeTracker.Instance.TrackModuleAddition(module, 1, currentUser.UserID); - content = HttpContext.Current.Server.HtmlEncode(content); - newnode.InnerXml = XmlUtils.XMLEncode(content); - nodeModule.AppendChild(newnode); - } - } - } - } - catch (Exception exc) - { - Logger.Error(exc); + // Set Module Order as expected + this.UpdateModuleOrder(module.TabID, module.ModuleID, order, pane); + this.UpdateTabModuleOrder(module.TabID); } } - } - - 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(); - if (permission != null && perm == null) + else { - var modulePermission = new ModulePermissionInfo(permission); - - // ReSharper disable ImplicitlyCapturedClosure - var role = RoleController.Instance.GetRole(portalId, r => (r.RoleName == roleName)); + // add tabmodule + dataProvider.AddTabModule( + module.TabID, + module.ModuleID, + module.ModuleTitle, + module.Header, + module.Footer, + module.ModuleOrder, + module.PaneName, + module.CacheTime, + module.CacheMethod, + module.Alignment, + module.Color, + module.Border, + module.IconFile, + (int)module.Visibility, + module.ContainerSrc, + module.DisplayTitle, + module.DisplayPrint, + module.DisplaySyndicate, + module.IsWebSlice, + module.WebSliceTitle, + module.WebSliceExpiryDate, + module.WebSliceTTL, + module.UniqueId, + module.VersionGuid, + module.DefaultLanguageGuid, + module.LocalizedVersionGuid, + module.CultureCode, + currentUser.UserID); - // ReSharper restore ImplicitlyCapturedClosure - if (role != null) + var log = new LogInfo { - modulePermission.RoleID = role.RoleID; - modulePermission.AllowAccess = true; + LogTypeKey = EventLogController.EventLogType.TABMODULE_CREATED.ToString(), + LogPortalID = module.PortalID, + }; + log.LogProperties.Add(new LogDetailInfo("TabPath", module.ParentTab.TabPath)); + log.LogProperties.Add(new LogDetailInfo("Module Type", module.ModuleDefinition.FriendlyName)); + log.LogProperties.Add(new LogDetailInfo("TabId", module.TabID.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("ModuleID", module.ModuleID.ToString(CultureInfo.InvariantCulture))); + LogController.Instance.AddLog(log); - module.ModulePermissions.Add(modulePermission); + TabChangeTracker.Instance.TrackModuleAddition(module, 1, currentUser.UserID); + + if (module.ModuleOrder == -1) + { + // position module at bottom of pane + this.UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); + } + else + { + // position module in pane + this.UpdateTabModuleOrder(module.TabID); } } - } - private static bool CheckIsInstance(int templateModuleID, Hashtable hModules) - { - // will be instance or module? - bool IsInstance = false; - if (templateModuleID > 0) + // Save ModuleSettings + if (module.TabModuleID == -1) { - if (hModules[templateModuleID] != null) + if (tmpModule == null) { - // this module has already been processed -> process as instance - IsInstance = true; + tmpModule = this.GetModule(module.ModuleID, module.TabID, false); } + + module.TabModuleID = tmpModule.TabModuleID; } - return IsInstance; + this.UpdateTabModuleSettings(module); + + this.ClearCache(module.TabID); + return module.ModuleID; } - private static void ClearModuleSettingsCache(int moduleId) + /// + /// Clears the cache. + /// + /// The tab id. + public void ClearCache(int tabId) { - foreach (var tab in TabController.Instance.GetTabsByModuleID(moduleId).Values) - { - string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tab.TabID); - DataCache.RemoveCache(cacheKey); - } + DataCache.ClearModuleCache(tabId); } - private void AddModuleInternal(ModuleInfo module) + /// + /// Copies the module to a new page. + /// + /// The source module. + /// The destination tab. + /// Name of to pane. + /// if set to true include settings. + public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string toPaneName, bool includeSettings) { - // 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); + PortalInfo portal = PortalController.Instance.GetPortal(destinationTab.PortalID); - // set module permissions - ModulePermissionController.SaveModulePermissions(module); + // Clone Module + ModuleInfo destinationModule = sourceModule.Clone(); + if (!string.IsNullOrEmpty(toPaneName)) + { + destinationModule.PaneName = toPaneName; } - // Save ModuleSettings - this.UpdateModuleSettings(module); + destinationModule.TabID = destinationTab.TabID; - EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); - } + // The new reference copy should have the same culture as the destination Tab + destinationModule.UniqueId = Guid.NewGuid(); + destinationModule.CultureCode = destinationTab.CultureCode; + destinationModule.VersionGuid = Guid.NewGuid(); + destinationModule.LocalizedVersionGuid = Guid.NewGuid(); - private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) - { - var modulePermission = new ModulePermissionInfo + // Figure out the DefaultLanguage Guid + if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode == portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && + !string.IsNullOrEmpty(destinationModule.CultureCode)) { - 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)) + // Tab is localized so set Default language Guid reference + destinationModule.DefaultLanguageGuid = sourceModule.UniqueId; + } + else if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode != portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && + !string.IsNullOrEmpty(destinationModule.CultureCode)) { - module.ModulePermissions.Add(modulePermission); + // tab is localized, but the source is not in the default language (it was on a single culture page) + // this wires up all the connections + sourceModule.DefaultLanguageGuid = destinationModule.UniqueId; + this.UpdateModule(sourceModule); } - - return modulePermission; - } - - private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) - { - var portalId = -1; - foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) + else if (sourceModule.AllTabs && sourceModule.CultureCode != portal.DefaultLanguage) { - var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); - DataCache.RemoveCache(cacheKey); - - if (portalId != tab.PortalID) + if (sourceModule.DefaultLanguageModule != null && destinationTab.DefaultLanguageTab != null) { - portalId = tab.PortalID; - cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); - DataCache.RemoveCache(cacheKey); + ModuleInfo defaultLanguageModule = this.GetModule(sourceModule.DefaultLanguageModule.ModuleID, destinationTab.DefaultLanguageTab.TabID, false); + + if (defaultLanguageModule != null) + { + destinationModule.DefaultLanguageGuid = defaultLanguageModule.UniqueId; + } } } - } - private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, int moduleDefId) - { - // Create New Module - var module = new ModuleInfo + // This will fail if the page already contains this module + try { - PortalID = portalId, - TabID = tabId, - ModuleOrder = -1, - ModuleTitle = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "title"), - PaneName = XmlUtils.GetNodeValue(nodePane.CreateNavigator(), "name"), - ModuleDefID = moduleDefId, - CacheTime = XmlUtils.GetNodeValueInt(nodeModule, "cachetime"), - CacheMethod = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "cachemethod"), - Alignment = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "alignment"), - IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "iconfile")), - AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs"), - CultureCode = XmlUtils.GetNodeValue(nodeModule, "cultureCode"), - }; + var userId = UserController.Instance.GetCurrentUserInfo().UserID; - // Localization - var oldGuid = XmlUtils.GetNodeValue(nodeModule, "defaultLanguageGuid"); - if (!string.IsNullOrEmpty(oldGuid)) - { - // get new default module language guid - if (ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) - { - module.DefaultLanguageGuid = new Guid(ParsedLocalizedModuleGuid[oldGuid].ToString()); - } - } + // Add a copy of the module to the bottom of the Pane for the new Tab + dataProvider.AddTabModule( + destinationModule.TabID, + destinationModule.ModuleID, + destinationModule.ModuleTitle, + destinationModule.Header, + destinationModule.Footer, + destinationModule.ModuleOrder, + destinationModule.PaneName, + destinationModule.CacheTime, + destinationModule.CacheMethod, + destinationModule.Alignment, + destinationModule.Color, + destinationModule.Border, + destinationModule.IconFile, + (int)destinationModule.Visibility, + destinationModule.ContainerSrc, + destinationModule.DisplayTitle, + destinationModule.DisplayPrint, + destinationModule.DisplaySyndicate, + destinationModule.IsWebSlice, + destinationModule.WebSliceTitle, + destinationModule.WebSliceExpiryDate, + destinationModule.WebSliceTTL, + destinationModule.UniqueId, + destinationModule.VersionGuid, + destinationModule.DefaultLanguageGuid, + destinationModule.LocalizedVersionGuid, + destinationModule.CultureCode, + userId); + TabChangeTracker.Instance.TrackModuleCopy(destinationModule, 1, sourceModule.TabID, userId); - switch (XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "visibility")) - { - case "Maximized": - module.Visibility = VisibilityState.Maximized; - break; - case "Minimized": - module.Visibility = VisibilityState.Minimized; - break; - case "None": - module.Visibility = VisibilityState.None; - break; + // Optionally copy the TabModuleSettings + if (includeSettings) + { + this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); + } } - - module.Color = XmlUtils.GetNodeValue(nodeModule, "color", string.Empty); - module.Border = XmlUtils.GetNodeValue(nodeModule, "border", string.Empty); - module.Header = XmlUtils.GetNodeValue(nodeModule, "header", string.Empty); - module.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", string.Empty); - module.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false); - module.IsShareable = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareable", true); - module.IsShareableViewOnly = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareableviewonly", true); - module.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate); - module.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty))) + catch (Exception exc) { - module.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty); + // module already in the page, ignore error + Logger.Error(exc); } - module.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true); - module.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true); - module.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false); - module.IsWebSlice = XmlUtils.GetNodeValueBoolean(nodeModule, "iswebslice", false); - if (module.IsWebSlice) + this.ClearCache(sourceModule.TabID); + this.ClearCache(destinationTab.TabID); + + // Optionally copy the TabModuleSettings + if (includeSettings) { - module.WebSliceTitle = XmlUtils.GetNodeValue(nodeModule, "webslicetitle", module.ModuleTitle); - module.WebSliceExpiryDate = XmlUtils.GetNodeValueDate(nodeModule, "websliceexpirydate", module.EndDate); - module.WebSliceTTL = XmlUtils.GetNodeValueInt(nodeModule, "webslicettl", module.CacheTime / 60); + destinationModule = this.GetModule(destinationModule.ModuleID, destinationModule.TabID, false); + this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); } + } - return module; + /// + /// Copies all modules in source page to a new page. + /// + /// The source tab. + /// The destination tab. + /// if set to true will use source module directly, else will create new module info by source module. + public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference) + { + this.CopyModules(sourceTab, destinationTab, asReference, false); } - private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissions, int portalId, ModuleInfo module) + /// + /// Copies all modules in source page to a new page. + /// + /// The source tab. + /// The destination tab. + /// if set to true will use source module directly, else will create new module info by source module. + /// if set to true will include modules which shown on all pages, this is used when create localized copy. + public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference, bool includeAllTabsMobules) { - var permissionController = new PermissionController(); - foreach (XmlNode node in nodeModulePermissions) + foreach (KeyValuePair kvp in this.GetTabModules(sourceTab.TabID)) { - string permissionKey = XmlUtils.GetNodeValue(node.CreateNavigator(), "permissionkey"); - string permissionCode = XmlUtils.GetNodeValue(node.CreateNavigator(), "permissioncode"); - string roleName = XmlUtils.GetNodeValue(node.CreateNavigator(), "rolename"); - 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 role = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); - if (role != null) - { - roleID = role.RoleID; - } - - break; - } + ModuleInfo sourceModule = kvp.Value; - if (roleID != int.MinValue) + // if the module shows on all pages does not need to be copied since it will + // be already added to this page + if ((includeAllTabsMobules || !sourceModule.AllTabs) && !sourceModule.IsDeleted) { - int permissionID = -1; - ArrayList permissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); - for (int i = 0; i <= permissions.Count - 1; i++) + if (!asReference) { - var permission = (PermissionInfo)permissions[i]; - permissionID = permission.PermissionID; + // Deep Copy + var newModule = sourceModule.Clone(); + newModule.ModuleID = Null.NullInteger; + newModule.TabID = destinationTab.TabID; + this.AddModule(newModule); } - - // if role was found add, otherwise ignore - if (permissionID != -1) + else { - var modulePermission = new ModulePermissionInfo - { - ModuleID = module.ModuleID, - PermissionID = permissionID, - RoleID = roleID, - AllowAccess = Convert.ToBoolean(XmlUtils.GetNodeValue(node.CreateNavigator(), "allowaccess")), - }; - - // do not add duplicate ModulePermissions - bool canAdd = !module.ModulePermissions.Cast() - .Any(mp => mp.ModuleID == modulePermission.ModuleID - && mp.PermissionID == modulePermission.PermissionID - && mp.RoleID == modulePermission.RoleID - && mp.UserID == modulePermission.UserID); - if (canAdd) - { - module.ModulePermissions.Add(modulePermission); - } + // Shallow (Reference Copy) + this.CopyModule(sourceModule, destinationTab, Null.NullString, true); } } } } - private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + /// + /// + /// + /// + /// + public void CreateContentItem(ModuleInfo module) { - // Copy each setting to the new TabModule instance - foreach (DictionaryEntry setting in fromModule.TabModuleSettings) + ContentType contentType = ContentType.Module; + + // This module does not have a valid ContentItem + // create ContentItem + IContentController contentController = Util.GetContentController(); + module.Content = module.ModuleTitle; + module.Indexed = false; + if (contentType != null) { - this.UpdateTabModuleSetting(toModule.TabModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + module.ContentTypeId = contentType.ContentTypeId; } + + module.ContentItemId = contentController.AddContentItem(module); } /// - /// Checks whether module VIEW permission is inherited from its tab. + /// DeleteAllModules deletes all instances of a Module (from a collection), optionally excluding the + /// current instance, and optionally including deleting the Module itself. /// - /// The module. - /// The module permission. - private bool IsModuleViewPermissionInherited(ModuleInfo module, ModulePermissionInfo permission) + /// + /// Note - the base module is not removed unless both the flags are set, indicating + /// to delete all instances AND to delete the Base Module. + /// + /// The Id of the module to copy. + /// The Id of the current tab. + /// A flag that determines whether the instance should be soft-deleted. + /// An ArrayList of TabItem objects. + /// A flag to indicate whether to delete from the current tab + /// as identified ny tabId. + /// A flag to indicate whether to delete the Module itself. + public void DeleteAllModules(int moduleId, int tabId, List fromTabs, bool softDelete, bool includeCurrent, bool deleteBaseModule) { - Requires.NotNull(module); - - Requires.NotNull(permission); - - var permissionViewKey = "VIEW"; + var moduleInfo = this.GetModule(moduleId, tabId, false); - if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) + // Iterate through collection deleting the module from each Tab (except the current) + foreach (TabInfo objTab in fromTabs) { - return false; + if (objTab.TabID != tabId || includeCurrent) + { + this.UncopyModule(objTab.TabID, moduleId, softDelete, tabId); // uncopy existing modules + } } - var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); + // Optionally delete the Module + if (includeCurrent && deleteBaseModule && !softDelete) + { + this.DeleteModule(moduleId); + this.ClearCache(tabId); + } + else + { + this.ClearCache(tabId); - return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; + // ModuleRemove is only raised when doing a soft delete of the module + if (softDelete) + { + EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); + } + } } /// - /// Checks whether given permission is granted for translator role. + /// Delete a module instance permanently from the database. /// - /// The module permission. - /// The portal ID. - /// The culture code. - private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) + /// ID of the module instance. + public void DeleteModule(int moduleId) { - Requires.NotNull(permission); + // Get the module + ModuleInfo module = this.GetModule(moduleId, Null.NullInteger, true); - if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) + // Delete Module + dataProvider.DeleteModule(moduleId); + + // Remove the Content Item + if (module != null && module.ContentItemId > Null.NullInteger) { - return false; + IContentController contentController = Util.GetContentController(); + contentController.DeleteContentItem(module); } - var translatorSettingKey = $"DefaultTranslatorRoles-{culture}"; + // Log deletion + EventLogController.Instance.AddLog("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.MODULE_DELETED); - var translatorSettingValue = - PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? - HostController.Instance.GetString(translatorSettingKey, null); + // queue remove module from search index + var document = new SearchDocumentToDelete + { + ModuleId = moduleId, + }; - var translatorRoles = - translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + DataProvider.Instance().AddSearchDeletedItems(document); - return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; + EventManager.Instance.OnModuleDeleted(new ModuleEventArgs { Module = module }); } /// - /// Copies permissions from source to new tab. + /// Delete a Setting of a module instance. /// - /// Source module. - /// New module. - private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) + /// ID of the affected module. + /// Name of the setting to be deleted. + public void DeleteModuleSetting(int moduleId, string settingName) { - 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); - } + dataProvider.DeleteModuleSetting(moduleId, settingName); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; + log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); + LogController.Instance.AddLog(log); + this.UpdateTabModuleVersionsByModuleID(moduleId); + ClearModuleSettingsCache(moduleId); } - private static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, ModuleInfo objModule) + /// + /// Delete a module reference permanently from the database. + /// if there are no other references, the module instance is deleted as well. + /// + /// ID of the page. + /// ID of the module instance. + /// A flag that determines whether the instance should be soft-deleted. + public void DeleteTabModule(int tabId, int moduleId, bool softDelete) { - foreach (XmlNode moduleSettingNode in nodeModuleSettings) + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); + this.DeleteTabModuleInternal(moduleInfo, softDelete); + var userId = UserController.Instance.GetCurrentUserInfo().UserID; + if (softDelete) { - string key = XmlUtils.GetNodeValue(moduleSettingNode.CreateNavigator(), "settingname"); - string value = XmlUtils.GetNodeValue(moduleSettingNode.CreateNavigator(), "settingvalue"); - objModule.ModuleSettings[key] = value; + TabChangeTracker.Instance.TrackModuleDeletion(moduleInfo, Null.NullInteger, userId); } } - private static void DeserializeTabModuleSettings(XmlNodeList nodeTabModuleSettings, ModuleInfo objModule) + /// + /// Delete a specific setting of a tabmodule reference. + /// + /// ID of the affected tabmodule. + /// Name of the setting to remove. + public void DeleteTabModuleSetting(int tabModuleId, string settingName) { - foreach (XmlNode tabModuleSettingNode in nodeTabModuleSettings) + dataProvider.DeleteTabModuleSetting(tabModuleId, settingName); + UpdateTabModuleVersion(tabModuleId); + var log = new LogInfo { - string key = XmlUtils.GetNodeValue(tabModuleSettingNode.CreateNavigator(), "settingname"); - string value = XmlUtils.GetNodeValue(tabModuleSettingNode.CreateNavigator(), "settingvalue"); - objModule.TabModuleSettings[key] = value; - } + LogTypeKey = EventLogController.EventLogType.TABMODULE_SETTING_DELETED.ToString(), + }; + log.LogProperties.Add(new LogDetailInfo("TabModuleId", tabModuleId.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); + LogController.Instance.AddLog(log); + ClearTabModuleSettingsCache(tabModuleId, settingName); } - private static bool FindModule(XmlNode nodeModule, int tabId, PortalTemplateModuleAction mergeTabs) + /// + /// Des the localize module. + /// + /// The source module. + /// new module id. + public int DeLocalizeModule(ModuleInfo sourceModule) { - var modules = Instance.GetTabModules(tabId); + int moduleId = Null.NullInteger; - bool moduleFound = false; - string modTitle = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "title"); - if (mergeTabs == PortalTemplateModuleAction.Merge) + if (sourceModule != null && sourceModule.DefaultLanguageModule != null) { - if (modules.Select(kvp => kvp.Value).Any(module => modTitle == module.ModuleTitle)) - { - moduleFound = true; - } - } + // clone the module object ( to avoid creating an object reference to the data cache ) + ModuleInfo newModule = sourceModule.Clone(); - return moduleFound; - } + // Get the Module ID of the default language instance + newModule.ModuleID = sourceModule.DefaultLanguageModule.ModuleID; - private static void GetModuleContent(XmlNode nodeModule, int ModuleId, int TabId, int PortalId) - { - ModuleInfo module = Instance.GetModule(ModuleId, TabId, true); - if (nodeModule != null) - { - // ReSharper disable PossibleNullReferenceException - string version = nodeModule.SelectSingleNode("content").Attributes["version"].Value; - string content = nodeModule.SelectSingleNode("content").InnerXml; - content = content.Substring(9, content.Length - 12); - if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && !string.IsNullOrEmpty(content)) + if (newModule.ModuleID != sourceModule.ModuleID) { - var portal = PortalController.Instance.GetPortal(PortalId); - - // Determine if the Module is copmpletely installed - // (ie are we running in the same request that installed the module). - if (module.DesktopModule.SupportedFeatures == Null.NullInteger) - { - // save content in eventqueue for processing after an app restart, - // as modules Supported Features are not updated yet so we - // cannot determine if the module supports IsPortable - EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); - } - else - { - if (module.DesktopModule.IsPortable) - { - try - { - object businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); - var controller = businessController as IPortable; - if (controller != null) - { - var decodedContent = HttpContext.Current.Server.HtmlDecode(content); - controller.ImportModule(module.ModuleID, decodedContent, version, portal.AdministratorId); - } - } - catch - { - // if there is an error then the type cannot be loaded at this time, so add to EventQueue - EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); - } - } - } - } - - // ReSharper restore PossibleNullReferenceException - } - } + // update tabmodule + dataProvider.UpdateTabModule( + newModule.TabModuleID, + newModule.TabID, + newModule.ModuleID, + newModule.ModuleTitle, + newModule.Header, + newModule.Footer, + newModule.ModuleOrder, + newModule.PaneName, + newModule.CacheTime, + newModule.CacheMethod, + newModule.Alignment, + newModule.Color, + newModule.Border, + newModule.IconFile, + (int)newModule.Visibility, + newModule.ContainerSrc, + newModule.DisplayTitle, + newModule.DisplayPrint, + newModule.DisplaySyndicate, + newModule.IsWebSlice, + newModule.WebSliceTitle, + newModule.WebSliceExpiryDate, + newModule.WebSliceTTL, + newModule.VersionGuid, + newModule.DefaultLanguageGuid, + newModule.LocalizedVersionGuid, + newModule.CultureCode, + UserController.Instance.GetCurrentUserInfo().UserID); - private static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) - { - ModuleDefinitionInfo moduleDefinition = null; + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); - // Templates prior to v4.3.5 only have the node to define the Module Type - // This node was populated with the DesktopModuleInfo.ModuleName property - // Thus there is no mechanism to determine to which module definition the module belongs. - // - // Template from v4.3.5 on also have the element that is populated - // with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies - // which Module Definition it belongs to. + // Update tab version details of old and new modules + var userId = UserController.Instance.GetCurrentUserInfo().UserID; + TabChangeTracker.Instance.TrackModuleDeletion(sourceModule, Null.NullInteger, userId); + TabChangeTracker.Instance.TrackModuleCopy(newModule, Null.NullInteger, newModule.TabID, userId); - // Get the DesktopModule defined by the element - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "definition"), Null.NullInteger); - if (desktopModule != null) - { - // Get the moduleDefinition from the element - string friendlyName = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "moduledefinition"); - if (string.IsNullOrEmpty(friendlyName)) - { - // Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) - foreach (ModuleDefinitionInfo md in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModule.DesktopModuleID).Values) + // check if all modules instances have been deleted + if (this.GetModule(sourceModule.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) { - moduleDefinition = md; - break; + // delete the deep copy "module info" + this.DeleteModule(sourceModule.ModuleID); } } - else - { - // Module is 4.3.5 or later so get the Module Defeinition by its friendly name - moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName, desktopModule.DesktopModuleID); - } - } - return moduleDefinition; - } + moduleId = newModule.ModuleID; - private static void SetCloneModuleContext(bool cloneModuleContext) - { - Thread.SetData( - Thread.GetNamedDataSlot("CloneModuleContext"), - cloneModuleContext ? bool.TrueString : bool.FalseString); + // Clear Caches + this.ClearCache(newModule.TabID); + this.ClearCache(sourceModule.TabID); + } + + return moduleId; } - private static void UpdateTabModuleVersion(int tabModuleId) + /// + /// get info of all modules in any portal of the installation. + /// + /// moduleInfo of all modules. + /// created for upgrade purposes. + public ArrayList GetAllModules() { - dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); + return CBO.FillCollection(dataProvider.GetAllModules(), typeof(ModuleInfo)); } - private int LocalizeModuleInternal(ModuleInfo sourceModule) - { - int moduleId = Null.NullInteger; - - if (sourceModule != null) - { - // clone the module object ( to avoid creating an object reference to the data cache ) - var newModule = sourceModule.Clone(); - newModule.ModuleID = Null.NullInteger; - - string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", sourceModule.CultureCode), sourceModule.PortalID, string.Empty).TrimEnd(';'); - - // Add the default translators for this language, view and edit permissions - var permissionController = new PermissionController(); - var viewPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); - var editPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "EDIT"); - PermissionInfo viewPermisison = null; - PermissionInfo editPermisison = null; + /// + /// get Module objects of a portal, either only those, to be placed on all tabs or not. + /// + /// ID of the portal. + /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs. + /// ArrayList of TabModuleInfo objects. + public ArrayList GetAllTabsModules(int portalID, bool allTabs) + { + return CBO.FillCollection(dataProvider.GetAllTabsModules(portalID, allTabs), typeof(ModuleInfo)); + } - // View - if (viewPermissionsList != null && viewPermissionsList.Count > 0) - { - viewPermisison = (PermissionInfo)viewPermissionsList[0]; - } + /// + /// get TabModule objects that are linked to a particular ModuleID. + /// + /// ID of the module. + /// ArrayList of TabModuleInfo objects. + public ArrayList GetAllTabsModulesByModuleID(int moduleID) + { + return CBO.FillCollection(dataProvider.GetAllTabsModulesByModuleID(moduleID), typeof(ModuleInfo)); + } - // Edit - if (editPermissionsList != null && editPermissionsList.Count > 0) - { - editPermisison = (PermissionInfo)editPermissionsList[0]; - } + /// + /// get a Module object. + /// + /// ID of the module. + /// ModuleInfo object. + /// This overload ignores any cached values and always retrieves the latest data + /// from the database. + public ModuleInfo GetModule(int moduleID) + { + return this.GetModule(moduleID, Null.NullInteger, true); + } - if (viewPermisison != null || editPermisison != null) - { - foreach (string translatorRole in translatorRoles.Split(';')) - { - AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, viewPermisison, "VIEW"); - AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, editPermisison, "EDIT"); - } - } + /// + /// get a Module object. + /// + /// ID of the module. + /// ID of the page. + /// ModuleInfo object. + public ModuleInfo GetModule(int moduleID, int tabID) + { + return this.GetModule(moduleID, tabID, false); + } - // copy permisions from source to new module - this.CopyModulePermisions(sourceModule, newModule); + /// + /// get a Module object. + /// + /// ID of the module. + /// ID of the page. + /// flag, if data shall not be taken from cache. + /// ModuleInfo object. + public ModuleInfo GetModule(int moduleID, int tabID, bool ignoreCache) + { + ModuleInfo modInfo = null; + bool bFound = false; + if (!ignoreCache) + { + // First try the cache + var dicModules = this.GetTabModules(tabID); + bFound = dicModules.TryGetValue(moduleID, out modInfo); + } - // Add Module - this.AddModuleInternal(newModule); + if (ignoreCache || !bFound) + { + modInfo = CBO.FillObject(dataProvider.GetModule(moduleID, tabID)); + } - // copy module settings - DataCache.RemoveCache(string.Format(DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); - var settings = this.GetModuleSettings(sourceModule.ModuleID, sourceModule.TabID); + return modInfo; + } - // update tabmodule - var currentUser = UserController.Instance.GetCurrentUserInfo(); - dataProvider.UpdateTabModule( - newModule.TabModuleID, - newModule.TabID, - newModule.ModuleID, - newModule.ModuleTitle, - newModule.Header, - newModule.Footer, - newModule.ModuleOrder, - newModule.PaneName, - newModule.CacheTime, - newModule.CacheMethod, - newModule.Alignment, - newModule.Color, - newModule.Border, - newModule.IconFile, - (int)newModule.Visibility, - newModule.ContainerSrc, - newModule.DisplayTitle, - newModule.DisplayPrint, - newModule.DisplaySyndicate, - newModule.IsWebSlice, - newModule.WebSliceTitle, - newModule.WebSliceExpiryDate, - newModule.WebSliceTTL, - newModule.VersionGuid, - newModule.DefaultLanguageGuid, - newModule.LocalizedVersionGuid, - newModule.CultureCode, - currentUser.UserID); + /// + /// get Module by specific locale. + /// + /// ID of the module. + /// ID of the tab. + /// ID of the portal. + /// The wanted locale. + /// ModuleInfo associated to submitted locale. + public ModuleInfo GetModuleByCulture(int ModuleId, int tabid, int portalId, Locale locale) + { + ModuleInfo localizedModule = null; - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); + // Get Module specified by Id + ModuleInfo originalModule = this.GetModule(ModuleId, tabid, false); - // Copy each setting to the new TabModule instance - foreach (DictionaryEntry setting in settings) + if (locale != null && originalModule != null) + { + // Check if tab is in the requested culture + if (string.IsNullOrEmpty(originalModule.CultureCode) || originalModule.CultureCode == locale.Code) { - this.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + localizedModule = originalModule; } - - if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) + else { - try + // See if tab exists for culture + if (originalModule.IsDefaultLanguage) { - object businessController = Reflection.CreateObject(newModule.DesktopModule.BusinessControllerClass, newModule.DesktopModule.BusinessControllerClass); - var portableModule = businessController as IPortable; - if (portableModule != null) + originalModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule); + } + else + { + if (originalModule.DefaultLanguageModule != null) { - try + if (originalModule.DefaultLanguageModule.CultureCode == locale.Code) { - SetCloneModuleContext(true); - string moduleContent = portableModule.ExportModule(sourceModule.ModuleID); - if (!string.IsNullOrEmpty(moduleContent)) - { - portableModule.ImportModule(newModule.ModuleID, moduleContent, newModule.DesktopModule.Version, currentUser.UserID); - } + localizedModule = originalModule.DefaultLanguageModule; } - finally + else { - SetCloneModuleContext(false); + if (!originalModule.DefaultLanguageModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule)) + { + localizedModule = originalModule.DefaultLanguageModule; + } } } } - catch (Exception ex) - { - Exceptions.LogException(ex); - } } - - moduleId = newModule.ModuleID; - - // Clear Caches - this.ClearCache(newModule.TabID); - this.ClearCache(sourceModule.TabID); } - return moduleId; + return localizedModule; } - private void UpdateModuleSettingInternal(int moduleId, string settingName, string settingValue, bool updateVersion) + /// + /// Get ModuleInfo object of first module instance with a given name of the module definition. + /// + /// ID of the portal, where to look for the module. + /// The name of module definition (NOTE: this looks at , not ). + /// ModuleInfo of first module instance. + /// preferably used for admin and host modules. + public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) { - IDataReader dr = null; - try - { - var currentUser = UserController.Instance.GetCurrentUserInfo(); - dr = dataProvider.GetModuleSetting(moduleId, settingName); + // declare return object + ModuleInfo module; - string existValue = null; - if (dr.Read()) + // format cache key + string key = string.Format(DataCache.ModuleCacheKey, portalId); + + // get module dictionary from cache + var modules = DataCache.GetCache>(key) ?? new Dictionary(); + if (modules.ContainsKey(definitionName)) + { + module = modules[definitionName]; + } + else + { + // clone the dictionary so that we have a local copy + var clonemodules = new Dictionary(); + foreach (ModuleInfo m in modules.Values) { - existValue = dr.GetString(1); + clonemodules[m.ModuleDefinition.DefinitionName] = m; } - dr.Close(); - - if (existValue == null) + // get from database + IDataReader dr = DataProvider.Instance().GetModuleByDefinition(portalId, definitionName); + try { - dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.MODULE_SETTING_CREATED, - "ModuleId", moduleId, settingName, settingValue, - currentUser.UserID); + // hydrate object + module = CBO.FillObject(dr); } - else if (existValue != settingValue) + finally { - dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.MODULE_SETTING_UPDATED, - "ModuleId", moduleId, settingName, settingValue, - currentUser.UserID); + // close connection + CBO.CloseDataReader(dr, true); } - if (updateVersion) - { - this.UpdateTabModuleVersionsByModuleID(moduleId); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - // Ensure DataReader is closed - if (dr != null && !dr.IsClosed) + if (module != null) { - CBO.CloseDataReader(dr, true); + // add the module to the dictionary + clonemodules[module.ModuleDefinition.FriendlyName] = module; + + // set module caching settings + int timeOut = DataCache.ModuleCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + + // cache module dictionary + if (timeOut > 0) + { + DataCache.SetCache(key, clonemodules, TimeSpan.FromMinutes(timeOut)); + } } } - ClearModuleSettingsCache(moduleId); + return module; } - private void UpdateModuleSettings(ModuleInfo updatedModule) + /// + /// get a Module object. + /// + /// + /// + /// + /// + public ModuleInfo GetModuleByUniqueID(Guid uniqueID) { - foreach (string key in updatedModule.ModuleSettings.Keys) - { - string sKey = key; - this.UpdateModuleSettingInternal(updatedModule.ModuleID, sKey, Convert.ToString(updatedModule.ModuleSettings[sKey]), false); - } + return CBO.FillObject(dataProvider.GetModuleByUniqueID(uniqueID)); + } - this.UpdateTabModuleVersionsByModuleID(updatedModule.ModuleID); + /// + /// get all Module objects of a portal. + /// + /// ID of the portal. + /// ArrayList of ModuleInfo objects. + public ArrayList GetModules(int portalID) + { + return CBO.FillCollection(dataProvider.GetModules(portalID), typeof(ModuleInfo)); } - private void UpdateTabModuleSettings(ModuleInfo updatedTabModule) + /// + /// Gets the modules by definition. + /// + /// The portal ID. + /// The name of the module definition. + /// module collection. + public ArrayList GetModulesByDefinition(int portalID, string definitionName) { - foreach (string sKey in updatedTabModule.TabModuleSettings.Keys) - { - this.UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey])); - } + return CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, definitionName), typeof(ModuleInfo)); } - private void UpdateTabModuleVersionsByModuleID(int moduleID) + /// + /// Gets the modules by DesktopModuleId. + /// + /// The Desktop Module Id. + /// module collection. + public ArrayList GetModulesByDesktopModuleId(int desktopModuleId) { - // Update the version guid of each TabModule linked to the updated module - foreach (ModuleInfo modInfo in this.GetAllTabsModulesByModuleID(moduleID)) + var moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId); + var modules = new ArrayList(); + foreach (var moduleDefinition in moduleDefinitions) { - this.ClearCache(modInfo.TabID); + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) + { + modules.AddRange(this.GetModulesByDefinition(portal.PortalID, moduleDefinition.Value.DefinitionName)); + } } - dataProvider.UpdateTabModuleVersionByModule(moduleID); + return modules; } - private bool HasModuleOrderOrPaneChanged(ModuleInfo module) + /// + /// For a portal get a list of all active module and tabmodule references that are Searchable + /// either by inheriting from ModuleSearchBase or implementing the older ISearchable interface. + /// + /// ID of the portal to be searched. + /// Arraylist of ModuleInfo for modules supporting search. + public ArrayList GetSearchModules(int portalID) { - var storedModuleInfo = this.GetTabModule(module.TabModuleID); - return storedModuleInfo == null || storedModuleInfo.ModuleOrder != module.ModuleOrder || storedModuleInfo.PaneName != module.PaneName; + return CBO.FillCollection(dataProvider.GetSearchModules(portalID), typeof(ModuleInfo)); } - private void UncopyModule(int tabId, int moduleId, bool softDelete, int originalTabId) + /// + /// get a Module object. + /// + /// ID of the tabmodule. + /// An ModuleInfo object. + public ModuleInfo GetTabModule(int tabModuleID) { - ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); - this.DeleteTabModuleInternal(moduleInfo, softDelete, true); - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - TabChangeTracker.Instance.TrackModuleUncopy(moduleInfo, Null.NullInteger, originalTabId, userId); + var cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, tabModuleID); + return CBO.GetCachedObject( + new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), + c => CBO.FillObject(dataProvider.GetTabModule(tabModuleID))); } - private void DeleteTabModuleInternal(ModuleInfo moduleInfo, bool softDelete, bool uncopy = false) + /// + /// Get all Module references on a tab. + /// + /// + /// Dictionary of ModuleID and ModuleInfo. + public Dictionary GetTabModules(int tabId) { - // save moduleinfo - if (moduleInfo != null) + var cacheKey = string.Format(DataCache.TabModuleCacheKey, tabId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabModuleCacheTimeOut, + DataCache.TabModuleCachePriority), + c => this.GetModulesCurrentPage(tabId)); + } + + /// + /// Get a list of all TabModule references of a module instance. + /// + /// ID of the Module. + /// ArrayList of ModuleInfo. + public IList GetTabModulesByModule(int moduleID) + { + return CBO.FillCollection(dataProvider.GetModule(moduleID, Null.NullInteger)); + } + + public void InitialModulePermission(ModuleInfo module, int tabId, int permissionType) + { + var tabPermissions = TabPermissionController.GetTabPermissions(tabId, module.PortalID); + var permissionController = new PermissionController(); + + module.InheritViewPermissions = permissionType == 0; + + // get the default module view permissions + ArrayList systemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); + + // get the permissions from the page + foreach (TabPermissionInfo tabPermission in tabPermissions) { - // delete the module instance for the tab - dataProvider.DeleteTabModule(moduleInfo.TabID, moduleInfo.ModuleID, softDelete, UserController.Instance.GetCurrentUserInfo().UserID); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TABMODULE_DELETED.ToString() }; - log.LogProperties.Add(new LogDetailInfo("tabId", moduleInfo.TabID.ToString(CultureInfo.InvariantCulture))); - log.LogProperties.Add(new LogDetailInfo("moduleId", moduleInfo.ModuleID.ToString(CultureInfo.InvariantCulture))); - LogController.Instance.AddLog(log); + if (tabPermission.PermissionKey == "VIEW" && permissionType == 0) + { + // Don't need to explicitly add View permisisons if "Same As Page" + continue; + } - // reorder all modules on tab - if (!uncopy) + // get the system module permissions for the permissionkey + ArrayList systemModulePermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", tabPermission.PermissionKey); + + // loop through the system module permissions + int j; + for (j = 0; j <= systemModulePermissions.Count - 1; j++) { - this.UpdateTabModuleOrder(moduleInfo.TabID); + // create the module permission + var systemModulePermission = (PermissionInfo)systemModulePermissions[j]; + if (systemModulePermission.PermissionKey == "VIEW" && permissionType == 1 && tabPermission.PermissionKey != "EDIT") + { + // Only Page Editors get View permissions if "Page Editors Only" + continue; + } - // ModuleRemove is only raised when doing a soft delete of the module - if (softDelete) + ModulePermissionInfo modulePermission = this.AddModulePermission(module, systemModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); + + // ensure that every EDIT permission which allows access also provides VIEW permission + if (modulePermission.PermissionKey == "EDIT" && modulePermission.AllowAccess) { - EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); + this.AddModulePermission(module, (PermissionInfo)systemModuleViewPermissions[0], modulePermission.RoleID, modulePermission.UserID, true); } } - // check if all modules instances have been deleted - if (this.GetModule(moduleInfo.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) + // Get the custom Module Permissions, Assume that roles with Edit Tab Permissions + // are automatically assigned to the Custom Module Permissions + if (tabPermission.PermissionKey == "EDIT") { - // hard delete the module - this.DeleteModule(moduleInfo.ModuleID); - } + ArrayList customModulePermissions = permissionController.GetPermissionsByModuleDefID(module.ModuleDefID); - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID)); - this.ClearCache(moduleInfo.TabID); - } - } + // loop through the custom module permissions + for (j = 0; j <= customModulePermissions.Count - 1; j++) + { + // create the module permission + var customModulePermission = (PermissionInfo)customModulePermissions[j]; - /// - /// Update content item when the module title changed. - /// - /// - private void UpdateContentItem(ModuleInfo module) - { - IContentController contentController = Util.GetContentController(); - if (module.Content != module.ModuleTitle) - { - module.Content = module.ModuleTitle; - contentController.UpdateContentItem(module); + this.AddModulePermission(module, customModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); + } + } } } - /// - /// add a module to a page. - /// - /// moduleInfo for the module to create. - /// ID of the created module. - public int AddModule(ModuleInfo module) + public void LocalizeModule(ModuleInfo sourceModule, Locale locale) { - // add module - this.AddModuleInternal(module); - - var currentUser = UserController.Instance.GetCurrentUserInfo(); - - // Lets see if the module already exists - ModuleInfo tmpModule = this.GetModule(module.ModuleID, module.TabID, false); - if (tmpModule != null) + try { - // Module Exists already - if (tmpModule.IsDeleted) + // we could be working from a single culture page that is not in the default language, + // so we need to test whether or not the module is going to be localized for the default locale + var defaultLocale = LocaleController.Instance.GetDefaultLocale(sourceModule.PortalID); + ModuleInfo defaultModule = locale.Code == defaultLocale.Code ? sourceModule : sourceModule.DefaultLanguageModule; + + if (defaultModule != null) { - var order = module.ModuleOrder; - var pane = module.PaneName; + ModuleInfo localizedModule; + var alreadyLocalized = defaultModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule) + && localizedModule.ModuleID != defaultModule.ModuleID; + var tabModules = this.GetTabModulesByModule(defaultModule.ModuleID); + if (tabModules.Count > 1) + { + // default language version is a reference copy - // Restore Module - this.RestoreModule(module); + // Localize first tabModule + var newModuleId = alreadyLocalized ? localizedModule.ModuleID : this.LocalizeModuleInternal(sourceModule); - TabChangeTracker.Instance.TrackModuleAddition(module, 1, currentUser.UserID); + // Update Reference Copies + foreach (ModuleInfo tm in tabModules) + { + if (tm.IsDefaultLanguage) + { + ModuleInfo localModule; + if (tm.LocalizedModules.TryGetValue(locale.Code, out localModule)) + { + localModule.ModuleID = newModuleId; + this.UpdateModule(localModule); + } + } + } + } + else if (!alreadyLocalized) + { + this.LocalizeModuleInternal(sourceModule); + } + } + } + catch (Exception ex) + { + Logger.ErrorFormat("Error localizing module, moduleId: {0}, full exception: {1}", sourceModule.ModuleID, ex); + } + } - // Set Module Order as expected - this.UpdateModuleOrder(module.TabID, module.ModuleID, order, pane); - this.UpdateTabModuleOrder(module.TabID); + /// + /// MoveModule moes a Module from one Tab to another including all the + /// TabModule settings. + /// + /// The Id of the module to move. + /// The Id of the source tab. + /// The Id of the destination tab. + /// The name of the Pane on the destination tab where the module will end up. + public void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneName) + { + // Move the module to the Tab + dataProvider.MoveTabModule(fromTabId, moduleId, toTabId, toPaneName, UserController.Instance.GetCurrentUserInfo().UserID); + + // Update the Tab reference for the module's ContentItems + var contentController = Util.GetContentController(); + var contentItems = contentController.GetContentItemsByModuleId(moduleId); + if (contentItems != null) + { + foreach (var item in contentItems) + { + if (item.TabID != toTabId) + { + item.TabID = toTabId; + contentController.UpdateContentItem(item); + } } } - else + + // Update Module Order for source tab, also updates the tabmodule version guid + this.UpdateTabModuleOrder(fromTabId); + + // Update Module Order for target tab, also updates the tabmodule version guid + this.UpdateTabModuleOrder(toTabId); + } + + /// + /// Restores the module. + /// + /// The module. + public void RestoreModule(ModuleInfo objModule) + { + dataProvider.RestoreTabModule(objModule.TabID, objModule.ModuleID); + var userId = UserController.Instance.GetCurrentUserInfo().UserID; + TabChangeTracker.Instance.TrackModuleAddition(objModule, 1, userId); + this.ClearCache(objModule.TabID); + } + + /// + /// Update module settings and permissions in database from ModuleInfo. + /// + /// ModuleInfo of the module to update. + public void UpdateModule(ModuleInfo module) + { + // Update ContentItem If neccessary + if (module.ModuleID != Null.NullInteger) { - // add tabmodule - dataProvider.AddTabModule( + if (module.ContentItemId == Null.NullInteger) + { + this.CreateContentItem(module); + } + else + { + this.UpdateContentItem(module); + } + } + + var currentUser = UserController.Instance.GetCurrentUserInfo(); + + // update module + dataProvider.UpdateModule( + module.ModuleID, + module.ModuleDefID, + module.ContentItemId, + module.AllTabs, + module.StartDate, + module.EndDate, + module.InheritViewPermissions, + module.IsShareable, + module.IsShareableViewOnly, + module.IsDeleted, + currentUser.UserID); + + // Update Tags + ITermController termController = Util.GetTermController(); + termController.RemoveTermsFromContent(module); + foreach (Term term in module.Terms) + { + termController.AddTermToContent(term, module); + } + + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_UPDATED); + + // save module permissions + ModulePermissionController.SaveModulePermissions(module); + this.UpdateModuleSettings(module); + module.VersionGuid = Guid.NewGuid(); + module.LocalizedVersionGuid = Guid.NewGuid(); + + if (!Null.IsNull(module.TabID)) + { + var hasModuleOrderOrPaneChanged = this.HasModuleOrderOrPaneChanged(module); + + // update tabmodule + dataProvider.UpdateTabModule( + module.TabModuleID, module.TabID, module.ModuleID, module.ModuleTitle, @@ -1210,1255 +1425,1086 @@ public int AddModule(ModuleInfo module) module.WebSliceTitle, module.WebSliceExpiryDate, module.WebSliceTTL, - module.UniqueId, module.VersionGuid, module.DefaultLanguageGuid, module.LocalizedVersionGuid, module.CultureCode, currentUser.UserID); - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.TABMODULE_CREATED.ToString(), - LogPortalID = module.PortalID, - }; - log.LogProperties.Add(new LogDetailInfo("TabPath", module.ParentTab.TabPath)); - log.LogProperties.Add(new LogDetailInfo("Module Type", module.ModuleDefinition.FriendlyName)); - log.LogProperties.Add(new LogDetailInfo("TabId", module.TabID.ToString(CultureInfo.InvariantCulture))); - log.LogProperties.Add(new LogDetailInfo("ModuleID", module.ModuleID.ToString(CultureInfo.InvariantCulture))); - LogController.Instance.AddLog(log); + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, module.TabModuleID)); - TabChangeTracker.Instance.TrackModuleAddition(module, 1, currentUser.UserID); + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.TABMODULE_UPDATED); - if (module.ModuleOrder == -1) + if (hasModuleOrderOrPaneChanged) { - // position module at bottom of pane + // update module order in pane this.UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); } - else + + // set the default module + if (PortalSettings.Current != null) { - // position module in pane - this.UpdateTabModuleOrder(module.TabID); + if (module.IsDefaultModule) + { + if (module.ModuleID != PortalSettings.Current.DefaultModuleId) + { + // Update Setting + PortalController.UpdatePortalSetting(module.PortalID, "defaultmoduleid", module.ModuleID.ToString(CultureInfo.InvariantCulture)); + } + + if (module.TabID != PortalSettings.Current.DefaultTabId) + { + // Update Setting + PortalController.UpdatePortalSetting(module.PortalID, "defaulttabid", module.TabID.ToString(CultureInfo.InvariantCulture)); + } + } + else + { + if (module.ModuleID == PortalSettings.Current.DefaultModuleId && module.TabID == PortalSettings.Current.DefaultTabId) + { + // Clear setting + PortalController.DeletePortalSetting(module.PortalID, "defaultmoduleid"); + PortalController.DeletePortalSetting(module.PortalID, "defaulttabid"); + } + } } - } - // Save ModuleSettings - if (module.TabModuleID == -1) - { - if (tmpModule == null) + // apply settings to all desktop modules in portal + if (module.AllModules) { - tmpModule = this.GetModule(module.ModuleID, module.TabID, false); - } + foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(module.PortalID)) + { + TabInfo tab = tabPair.Value; + foreach (KeyValuePair modulePair in this.GetTabModules(tab.TabID)) + { + var targetModule = modulePair.Value; + targetModule.VersionGuid = Guid.NewGuid(); + targetModule.LocalizedVersionGuid = Guid.NewGuid(); - module.TabModuleID = tmpModule.TabModuleID; + dataProvider.UpdateTabModule( + targetModule.TabModuleID, + targetModule.TabID, + targetModule.ModuleID, + targetModule.ModuleTitle, + targetModule.Header, + targetModule.Footer, + targetModule.ModuleOrder, + targetModule.PaneName, + targetModule.CacheTime, + targetModule.CacheMethod, + module.Alignment, + module.Color, + module.Border, + module.IconFile, + (int)module.Visibility, + module.ContainerSrc, + module.DisplayTitle, + module.DisplayPrint, + module.DisplaySyndicate, + module.IsWebSlice, + module.WebSliceTitle, + module.WebSliceExpiryDate, + module.WebSliceTTL, + targetModule.VersionGuid, + targetModule.DefaultLanguageGuid, + targetModule.LocalizedVersionGuid, + targetModule.CultureCode, + currentUser.UserID); + + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, targetModule.TabModuleID)); + this.ClearCache(targetModule.TabID); + } + } + } } - this.UpdateTabModuleSettings(module); + // Clear Cache for all TabModules + foreach (ModuleInfo tabModule in this.GetTabModulesByModule(module.ModuleID)) + { + this.ClearCache(tabModule.TabID); + } - this.ClearCache(module.TabID); - return module.ModuleID; + EventManager.Instance.OnModuleUpdated(new ModuleEventArgs { Module = module }); } /// - /// Clears the cache. + /// set/change the module position within a pane on a page. /// - /// The tab id. - public void ClearCache(int tabId) + /// ID of the page. + /// ID of the module on the page. + /// position within the controls list on page, -1 if to be added at the end. + /// name of the pane, the module is placed in on the page. + public void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string paneName) { - DataCache.ClearModuleCache(tabId); - } - - /// - /// Copies the module to a new page. - /// - /// The source module. - /// The destination tab. - /// Name of to pane. - /// if set to true include settings. - public void CopyModule(ModuleInfo sourceModule, TabInfo destinationTab, string toPaneName, bool includeSettings) - { - PortalInfo portal = PortalController.Instance.GetPortal(destinationTab.PortalID); - - // Clone Module - ModuleInfo destinationModule = sourceModule.Clone(); - if (!string.IsNullOrEmpty(toPaneName)) - { - destinationModule.PaneName = toPaneName; - } - - destinationModule.TabID = destinationTab.TabID; - - // The new reference copy should have the same culture as the destination Tab - destinationModule.UniqueId = Guid.NewGuid(); - destinationModule.CultureCode = destinationTab.CultureCode; - destinationModule.VersionGuid = Guid.NewGuid(); - destinationModule.LocalizedVersionGuid = Guid.NewGuid(); - - // Figure out the DefaultLanguage Guid - if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode == portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && - !string.IsNullOrEmpty(destinationModule.CultureCode)) - { - // Tab is localized so set Default language Guid reference - destinationModule.DefaultLanguageGuid = sourceModule.UniqueId; - } - else if (!string.IsNullOrEmpty(sourceModule.CultureCode) && sourceModule.CultureCode != portal.DefaultLanguage && destinationModule.CultureCode != sourceModule.CultureCode && - !string.IsNullOrEmpty(destinationModule.CultureCode)) - { - // tab is localized, but the source is not in the default language (it was on a single culture page) - // this wires up all the connections - sourceModule.DefaultLanguageGuid = destinationModule.UniqueId; - this.UpdateModule(sourceModule); - } - else if (sourceModule.AllTabs && sourceModule.CultureCode != portal.DefaultLanguage) + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); + if (moduleInfo != null) { - if (sourceModule.DefaultLanguageModule != null && destinationTab.DefaultLanguageTab != null) + // adding a module to a new pane - places the module at the bottom of the pane + if (moduleOrder == -1) { - ModuleInfo defaultLanguageModule = this.GetModule(sourceModule.DefaultLanguageModule.ModuleID, destinationTab.DefaultLanguageTab.TabID, false); - - if (defaultLanguageModule != null) + IDataReader dr = null; + try { - destinationModule.DefaultLanguageGuid = defaultLanguageModule.UniqueId; + dr = dataProvider.GetTabModuleOrder(tabId, paneName); + while (dr.Read()) + { + moduleOrder = Convert.ToInt32(dr["ModuleOrder"]); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); } - } - } - - // This will fail if the page already contains this module - try - { - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - - // Add a copy of the module to the bottom of the Pane for the new Tab - dataProvider.AddTabModule( - destinationModule.TabID, - destinationModule.ModuleID, - destinationModule.ModuleTitle, - destinationModule.Header, - destinationModule.Footer, - destinationModule.ModuleOrder, - destinationModule.PaneName, - destinationModule.CacheTime, - destinationModule.CacheMethod, - destinationModule.Alignment, - destinationModule.Color, - destinationModule.Border, - destinationModule.IconFile, - (int)destinationModule.Visibility, - destinationModule.ContainerSrc, - destinationModule.DisplayTitle, - destinationModule.DisplayPrint, - destinationModule.DisplaySyndicate, - destinationModule.IsWebSlice, - destinationModule.WebSliceTitle, - destinationModule.WebSliceExpiryDate, - destinationModule.WebSliceTTL, - destinationModule.UniqueId, - destinationModule.VersionGuid, - destinationModule.DefaultLanguageGuid, - destinationModule.LocalizedVersionGuid, - destinationModule.CultureCode, - userId); - TabChangeTracker.Instance.TrackModuleCopy(destinationModule, 1, sourceModule.TabID, userId); - // Optionally copy the TabModuleSettings - if (includeSettings) - { - this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); + moduleOrder += 2; } - } - catch (Exception exc) - { - // module already in the page, ignore error - Logger.Error(exc); - } - this.ClearCache(sourceModule.TabID); - this.ClearCache(destinationTab.TabID); + dataProvider.UpdateModuleOrder(tabId, moduleId, moduleOrder, paneName); + TabChangeTracker.Instance.TrackModuleModification(this.GetModule(moduleId, tabId, true), Null.NullInteger, UserController.Instance.GetCurrentUserInfo().UserID); - // Optionally copy the TabModuleSettings - if (includeSettings) - { - destinationModule = this.GetModule(destinationModule.ModuleID, destinationModule.TabID, false); - this.CopyTabModuleSettingsInternal(sourceModule, destinationModule); + // clear cache + this.ClearCache(tabId); } } /// - /// Copies all modules in source page to a new page. + /// Adds or updates a module's setting value. /// - /// The source tab. - /// The destination tab. - /// if set to true will use source module directly, else will create new module info by source module. - public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference) + /// ID of the module, the setting belongs to. + /// name of the setting property. + /// value of the setting (String). + /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. + public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) { - this.CopyModules(sourceTab, destinationTab, asReference, false); + this.UpdateModuleSettingInternal(moduleId, settingName, settingValue, true); } /// - /// Copies all modules in source page to a new page. + /// set/change all module's positions within a page. /// - /// The source tab. - /// The destination tab. - /// if set to true will use source module directly, else will create new module info by source module. - /// if set to true will include modules which shown on all pages, this is used when create localized copy. - public void CopyModules(TabInfo sourceTab, TabInfo destinationTab, bool asReference, bool includeAllTabsMobules) + /// ID of the page. + public void UpdateTabModuleOrder(int tabId) { - foreach (KeyValuePair kvp in this.GetTabModules(sourceTab.TabID)) + IDataReader dr = dataProvider.GetTabPanes(tabId); + try { - ModuleInfo sourceModule = kvp.Value; - - // if the module shows on all pages does not need to be copied since it will - // be already added to this page - if ((includeAllTabsMobules || !sourceModule.AllTabs) && !sourceModule.IsDeleted) + while (dr.Read()) { - if (!asReference) + int moduleCounter = 0; + IDataReader dr2 = dataProvider.GetTabModuleOrder(tabId, Convert.ToString(dr["PaneName"])); + try { - // Deep Copy - var newModule = sourceModule.Clone(); - newModule.ModuleID = Null.NullInteger; - newModule.TabID = destinationTab.TabID; - this.AddModule(newModule); + while (dr2.Read()) + { + moduleCounter += 1; + + var moduleId = Convert.ToInt32(dr2["ModuleID"]); + var paneName = Convert.ToString(dr["PaneName"]); + var isDeleted = Convert.ToBoolean(dr2["IsDeleted"]); + var existingOrder = Convert.ToInt32(dr2["ModuleOrder"]); + var newOrder = (moduleCounter * 2) - 1; + + if (existingOrder == newOrder) + { + continue; + } + + dataProvider.UpdateModuleOrder(tabId, moduleId, newOrder, paneName); + + if (!isDeleted) + { + var moduleInfo = this.GetModule(moduleId, tabId, true); + var userInfo = UserController.Instance.GetCurrentUserInfo(); + TabChangeTracker.Instance.TrackModuleModification(moduleInfo, Null.NullInteger, + userInfo.UserID); + } + } } - else + catch (Exception ex2) { - // Shallow (Reference Copy) - this.CopyModule(sourceModule, destinationTab, Null.NullString, true); + Exceptions.LogException(ex2); + } + finally + { + CBO.CloseDataReader(dr2, true); } } } - } - - /// - /// - /// - /// - /// - public void CreateContentItem(ModuleInfo module) - { - ContentType contentType = ContentType.Module; - - // This module does not have a valid ContentItem - // create ContentItem - IContentController contentController = Util.GetContentController(); - module.Content = module.ModuleTitle; - module.Indexed = false; - if (contentType != null) + catch (Exception ex) { - module.ContentTypeId = contentType.ContentTypeId; + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); } - module.ContentItemId = contentController.AddContentItem(module); + // clear module cache + this.ClearCache(tabId); } /// - /// DeleteAllModules deletes all instances of a Module (from a collection), optionally excluding the - /// current instance, and optionally including deleting the Module itself. + /// Adds or updates a module's setting value. /// - /// - /// Note - the base module is not removed unless both the flags are set, indicating - /// to delete all instances AND to delete the Base Module. - /// - /// The Id of the module to copy. - /// The Id of the current tab. - /// A flag that determines whether the instance should be soft-deleted. - /// An ArrayList of TabItem objects. - /// A flag to indicate whether to delete from the current tab - /// as identified ny tabId. - /// A flag to indicate whether to delete the Module itself. - public void DeleteAllModules(int moduleId, int tabId, List fromTabs, bool softDelete, bool includeCurrent, bool deleteBaseModule) + /// ID of the tabmodule, the setting belongs to. + /// name of the setting property. + /// value of the setting (String). + /// empty SettingValue will relove the setting. + public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) { - var moduleInfo = this.GetModule(moduleId, tabId, false); - - // Iterate through collection deleting the module from each Tab (except the current) - foreach (TabInfo objTab in fromTabs) + IDataReader dr = dataProvider.GetTabModuleSetting(tabModuleId, settingName); + try { - if (objTab.TabID != tabId || includeCurrent) + var currentUser = UserController.Instance.GetCurrentUserInfo(); + if (dr.Read()) { - this.UncopyModule(objTab.TabID, moduleId, softDelete, tabId); // uncopy existing modules + if (dr.GetString(1) != settingValue) + { + dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.MODULE_SETTING_UPDATED, + "TabModuleId", tabModuleId, settingName, settingValue, + currentUser.UserID); + UpdateTabModuleVersion(tabModuleId); + } + } + else + { + dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TABMODULE_SETTING_CREATED, + "TabModuleId", tabModuleId, settingName, settingValue, + currentUser.UserID); + UpdateTabModuleVersion(tabModuleId); } } - - // Optionally delete the Module - if (includeCurrent && deleteBaseModule && !softDelete) + catch (Exception ex) { - this.DeleteModule(moduleId); - this.ClearCache(tabId); + Exceptions.LogException(ex); } - else + finally { - this.ClearCache(tabId); - - // ModuleRemove is only raised when doing a soft delete of the module - if (softDelete) - { - EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); - } + // Ensure DataReader is closed + CBO.CloseDataReader(dr, true); } + + ClearTabModuleSettingsCache(tabModuleId, settingName); } /// - /// Delete a module instance permanently from the database. + /// Updates the translation status. /// - /// ID of the module instance. - public void DeleteModule(int moduleId) + /// The localized module. + /// if set to true will mark the module as translated]. + public void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslated) { - // Get the module - ModuleInfo module = this.GetModule(moduleId, Null.NullInteger, true); - - // Delete Module - dataProvider.DeleteModule(moduleId); - - // Remove the Content Item - if (module != null && module.ContentItemId > Null.NullInteger) + if (isTranslated && (localizedModule.DefaultLanguageModule != null)) { - IContentController contentController = Util.GetContentController(); - contentController.DeleteContentItem(module); + localizedModule.LocalizedVersionGuid = localizedModule.DefaultLanguageModule.LocalizedVersionGuid; } - - // Log deletion - EventLogController.Instance.AddLog("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.MODULE_DELETED); - - // queue remove module from search index - var document = new SearchDocumentToDelete + else { - ModuleId = moduleId, - }; + localizedModule.LocalizedVersionGuid = Guid.NewGuid(); + } - DataProvider.Instance().AddSearchDeletedItems(document); + DataProvider.Instance().UpdateTabModuleTranslationStatus(localizedModule.TabModuleID, localizedModule.LocalizedVersionGuid, UserController.Instance.GetCurrentUserInfo().UserID); - EventManager.Instance.OnModuleDeleted(new ModuleEventArgs { Module = module }); + // Clear Tab Caches + this.ClearCache(localizedModule.TabID); } - /// - /// Delete a Setting of a module instance. - /// - /// ID of the affected module. - /// Name of the setting to be deleted. - public void DeleteModuleSetting(int moduleId, string settingName) + internal Hashtable GetModuleSettings(int moduleId, int tabId) { - dataProvider.DeleteModuleSetting(moduleId, settingName); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.MODULE_SETTING_DELETED.ToString() }; - log.LogProperties.Add(new LogDetailInfo("ModuleId", moduleId.ToString(CultureInfo.InvariantCulture))); - log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); - LogController.Instance.AddLog(log); - this.UpdateTabModuleVersionsByModuleID(moduleId); - ClearModuleSettingsCache(moduleId); + 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(); } - /// - /// Delete a module reference permanently from the database. - /// if there are no other references, the module instance is deleted as well. - /// - /// ID of the page. - /// ID of the module instance. - /// A flag that determines whether the instance should be soft-deleted. - public void DeleteTabModule(int tabId, int moduleId, bool softDelete) + internal Hashtable GetTabModuleSettings(int tabmoduleId, int tabId) { - ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); - this.DeleteTabModuleInternal(moduleInfo, softDelete); - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - if (softDelete) - { - TabChangeTracker.Instance.TrackModuleDeletion(moduleInfo, Null.NullInteger, userId); - } + 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(); } - /// - /// Delete a specific setting of a tabmodule reference. - /// - /// ID of the affected tabmodule. - /// Name of the setting to remove. - public void DeleteTabModuleSetting(int tabModuleId, string settingName) + protected override Func GetFactory() { - dataProvider.DeleteTabModuleSetting(tabModuleId, settingName); - UpdateTabModuleVersion(tabModuleId); - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.TABMODULE_SETTING_DELETED.ToString(), - }; - log.LogProperties.Add(new LogDetailInfo("TabModuleId", tabModuleId.ToString(CultureInfo.InvariantCulture))); - log.LogProperties.Add(new LogDetailInfo("SettingName", settingName)); - LogController.Instance.AddLog(log); - ClearTabModuleSettingsCache(tabModuleId, settingName); + return () => new ModuleController(); } - /// - /// Des the localize module. - /// - /// The source module. - /// new module id. - public int DeLocalizeModule(ModuleInfo sourceModule) + private static void AddContent(XmlNode nodeModule, ModuleInfo module) { - int moduleId = Null.NullInteger; - - if (sourceModule != null && sourceModule.DefaultLanguageModule != null) + if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && module.DesktopModule.IsPortable) { - // clone the module object ( to avoid creating an object reference to the data cache ) - ModuleInfo newModule = sourceModule.Clone(); + try + { + object businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); + var controller = businessController as IPortable; + if (controller != null) + { + string content = Convert.ToString(controller.ExportModule(module.ModuleID)); + if (!string.IsNullOrEmpty(content)) + { + content = XmlUtils.RemoveInvalidXmlCharacters(content); - // Get the Module ID of the default language instance - newModule.ModuleID = sourceModule.DefaultLanguageModule.ModuleID; + // add attributes to XML document + if (nodeModule.OwnerDocument != null) + { + var existing = nodeModule.OwnerDocument.GetElementById("content"); + if (existing != null) + { + nodeModule.OwnerDocument.RemoveChild(existing); + } - if (newModule.ModuleID != sourceModule.ModuleID) + XmlNode newnode = nodeModule.OwnerDocument.CreateElement("content"); + XmlAttribute xmlattr = nodeModule.OwnerDocument.CreateAttribute("type"); + xmlattr.Value = Globals.CleanName(module.DesktopModule.ModuleName); + if (newnode.Attributes != null) + { + newnode.Attributes.Append(xmlattr); + } + + xmlattr = nodeModule.OwnerDocument.CreateAttribute("version"); + xmlattr.Value = module.DesktopModule.Version; + if (newnode.Attributes != null) + { + newnode.Attributes.Append(xmlattr); + } + + content = HttpContext.Current.Server.HtmlEncode(content); + newnode.InnerXml = XmlUtils.XMLEncode(content); + nodeModule.AppendChild(newnode); + } + } + } + } + catch (Exception exc) { - // update tabmodule - dataProvider.UpdateTabModule( - newModule.TabModuleID, - newModule.TabID, - newModule.ModuleID, - newModule.ModuleTitle, - newModule.Header, - newModule.Footer, - newModule.ModuleOrder, - newModule.PaneName, - newModule.CacheTime, - newModule.CacheMethod, - newModule.Alignment, - newModule.Color, - newModule.Border, - newModule.IconFile, - (int)newModule.Visibility, - newModule.ContainerSrc, - newModule.DisplayTitle, - newModule.DisplayPrint, - newModule.DisplaySyndicate, - newModule.IsWebSlice, - newModule.WebSliceTitle, - newModule.WebSliceExpiryDate, - newModule.WebSliceTTL, - newModule.VersionGuid, - newModule.DefaultLanguageGuid, - newModule.LocalizedVersionGuid, - newModule.CultureCode, - UserController.Instance.GetCurrentUserInfo().UserID); - - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); - - // Update tab version details of old and new modules - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - TabChangeTracker.Instance.TrackModuleDeletion(sourceModule, Null.NullInteger, userId); - TabChangeTracker.Instance.TrackModuleCopy(newModule, Null.NullInteger, newModule.TabID, userId); - - // check if all modules instances have been deleted - if (this.GetModule(sourceModule.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) - { - // delete the deep copy "module info" - this.DeleteModule(sourceModule.ModuleID); - } + Logger.Error(exc); } - - moduleId = newModule.ModuleID; - - // Clear Caches - this.ClearCache(newModule.TabID); - this.ClearCache(sourceModule.TabID); } - - return moduleId; - } - - /// - /// get info of all modules in any portal of the installation. - /// - /// moduleInfo of all modules. - /// created for upgrade purposes. - public ArrayList GetAllModules() - { - return CBO.FillCollection(dataProvider.GetAllModules(), typeof(ModuleInfo)); } - /// - /// get Module objects of a portal, either only those, to be placed on all tabs or not. - /// - /// ID of the portal. - /// specify, whether to return modules to be shown on all tabs or those to be shown on specified tabs. - /// ArrayList of TabModuleInfo objects. - public ArrayList GetAllTabsModules(int portalID, bool allTabs) + private static void AddModulePermission(ref ModuleInfo module, int portalId, string roleName, PermissionInfo permission, string permissionKey) { - return CBO.FillCollection(dataProvider.GetAllTabsModules(portalID, allTabs), typeof(ModuleInfo)); - } + var perm = module.ModulePermissions.Where(tp => tp.RoleName == roleName && tp.PermissionKey == permissionKey).SingleOrDefault(); + if (permission != null && perm == null) + { + var modulePermission = new ModulePermissionInfo(permission); - /// - /// get TabModule objects that are linked to a particular ModuleID. - /// - /// ID of the module. - /// ArrayList of TabModuleInfo objects. - public ArrayList GetAllTabsModulesByModuleID(int moduleID) - { - return CBO.FillCollection(dataProvider.GetAllTabsModulesByModuleID(moduleID), typeof(ModuleInfo)); - } + // ReSharper disable ImplicitlyCapturedClosure + var role = RoleController.Instance.GetRole(portalId, r => (r.RoleName == roleName)); - /// - /// get a Module object. - /// - /// ID of the module. - /// ModuleInfo object. - /// This overload ignores any cached values and always retrieves the latest data - /// from the database. - public ModuleInfo GetModule(int moduleID) - { - return this.GetModule(moduleID, Null.NullInteger, true); - } + // ReSharper restore ImplicitlyCapturedClosure + if (role != null) + { + modulePermission.RoleID = role.RoleID; + modulePermission.AllowAccess = true; - /// - /// get a Module object. - /// - /// ID of the module. - /// ID of the page. - /// ModuleInfo object. - public ModuleInfo GetModule(int moduleID, int tabID) - { - return this.GetModule(moduleID, tabID, false); + module.ModulePermissions.Add(modulePermission); + } + } } - /// - /// get a Module object. - /// - /// ID of the module. - /// ID of the page. - /// flag, if data shall not be taken from cache. - /// ModuleInfo object. - public ModuleInfo GetModule(int moduleID, int tabID, bool ignoreCache) + private static bool CheckIsInstance(int templateModuleID, Hashtable hModules) { - ModuleInfo modInfo = null; - bool bFound = false; - if (!ignoreCache) + // will be instance or module? + bool IsInstance = false; + if (templateModuleID > 0) { - // First try the cache - var dicModules = this.GetTabModules(tabID); - bFound = dicModules.TryGetValue(moduleID, out modInfo); + if (hModules[templateModuleID] != null) + { + // this module has already been processed -> process as instance + IsInstance = true; + } } - if (ignoreCache || !bFound) + return IsInstance; + } + + private static void ClearModuleSettingsCache(int moduleId) + { + foreach (var tab in TabController.Instance.GetTabsByModuleID(moduleId).Values) { - modInfo = CBO.FillObject(dataProvider.GetModule(moduleID, tabID)); + string cacheKey = string.Format(DataCache.ModuleSettingsCacheKey, tab.TabID); + DataCache.RemoveCache(cacheKey); } - - return modInfo; } - /// - /// get Module by specific locale. - /// - /// ID of the module. - /// ID of the tab. - /// ID of the portal. - /// The wanted locale. - /// ModuleInfo associated to submitted locale. - public ModuleInfo GetModuleByCulture(int ModuleId, int tabid, int portalId, Locale locale) + private static void ClearTabModuleSettingsCache(int tabModuleId, string settingName) { - ModuleInfo localizedModule = null; - - // Get Module specified by Id - ModuleInfo originalModule = this.GetModule(ModuleId, tabid, false); - - if (locale != null && originalModule != null) + var portalId = -1; + foreach (var tab in TabController.Instance.GetTabsByTabModuleID(tabModuleId).Values) { - // Check if tab is in the requested culture - if (string.IsNullOrEmpty(originalModule.CultureCode) || originalModule.CultureCode == locale.Code) - { - localizedModule = originalModule; - } - else + var cacheKey = string.Format(DataCache.TabModuleSettingsCacheKey, tab.TabID); + DataCache.RemoveCache(cacheKey); + + if (portalId != tab.PortalID) { - // See if tab exists for culture - if (originalModule.IsDefaultLanguage) - { - originalModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule); - } - else - { - if (originalModule.DefaultLanguageModule != null) - { - if (originalModule.DefaultLanguageModule.CultureCode == locale.Code) - { - localizedModule = originalModule.DefaultLanguageModule; - } - else - { - if (!originalModule.DefaultLanguageModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule)) - { - localizedModule = originalModule.DefaultLanguageModule; - } - } - } - } + portalId = tab.PortalID; + cacheKey = string.Format(DataCache.TabModuleSettingsNameCacheKey, portalId, settingName ?? string.Empty); + DataCache.RemoveCache(cacheKey); } } - - return localizedModule; } - /// - /// Get ModuleInfo object of first module instance with a given name of the module definition. - /// - /// ID of the portal, where to look for the module. - /// The name of module definition (NOTE: this looks at , not ). - /// ModuleInfo of first module instance. - /// preferably used for admin and host modules. - public ModuleInfo GetModuleByDefinition(int portalId, string definitionName) + private static ModuleInfo DeserializeModule(XmlNode nodeModule, XmlNode nodePane, int portalId, int tabId, int moduleDefId) { - // declare return object - ModuleInfo module; - - // format cache key - string key = string.Format(DataCache.ModuleCacheKey, portalId); - - // get module dictionary from cache - var modules = DataCache.GetCache>(key) ?? new Dictionary(); - if (modules.ContainsKey(definitionName)) + // Create New Module + var module = new ModuleInfo { - module = modules[definitionName]; - } - else + PortalID = portalId, + TabID = tabId, + ModuleOrder = -1, + ModuleTitle = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "title"), + PaneName = XmlUtils.GetNodeValue(nodePane.CreateNavigator(), "name"), + ModuleDefID = moduleDefId, + CacheTime = XmlUtils.GetNodeValueInt(nodeModule, "cachetime"), + CacheMethod = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "cachemethod"), + Alignment = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "alignment"), + IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "iconfile")), + AllTabs = XmlUtils.GetNodeValueBoolean(nodeModule, "alltabs"), + CultureCode = XmlUtils.GetNodeValue(nodeModule, "cultureCode"), + }; + + // Localization + var oldGuid = XmlUtils.GetNodeValue(nodeModule, "defaultLanguageGuid"); + if (!string.IsNullOrEmpty(oldGuid)) { - // clone the dictionary so that we have a local copy - var clonemodules = new Dictionary(); - foreach (ModuleInfo m in modules.Values) + // get new default module language guid + if (ParsedLocalizedModuleGuid.ContainsKey(oldGuid)) { - clonemodules[m.ModuleDefinition.DefinitionName] = m; + module.DefaultLanguageGuid = new Guid(ParsedLocalizedModuleGuid[oldGuid].ToString()); } + } - // get from database - IDataReader dr = DataProvider.Instance().GetModuleByDefinition(portalId, definitionName); - try - { - // hydrate object - module = CBO.FillObject(dr); - } - finally + switch (XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "visibility")) + { + case "Maximized": + module.Visibility = VisibilityState.Maximized; + break; + case "Minimized": + module.Visibility = VisibilityState.Minimized; + break; + case "None": + module.Visibility = VisibilityState.None; + break; + } + + module.Color = XmlUtils.GetNodeValue(nodeModule, "color", string.Empty); + module.Border = XmlUtils.GetNodeValue(nodeModule, "border", string.Empty); + module.Header = XmlUtils.GetNodeValue(nodeModule, "header", string.Empty); + module.Footer = XmlUtils.GetNodeValue(nodeModule, "footer", string.Empty); + module.InheritViewPermissions = XmlUtils.GetNodeValueBoolean(nodeModule, "inheritviewpermissions", false); + module.IsShareable = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareable", true); + module.IsShareableViewOnly = XmlUtils.GetNodeValueBoolean(nodeModule, "isshareableviewonly", true); + module.StartDate = XmlUtils.GetNodeValueDate(nodeModule, "startdate", Null.NullDate); + module.EndDate = XmlUtils.GetNodeValueDate(nodeModule, "enddate", Null.NullDate); + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty))) + { + module.ContainerSrc = XmlUtils.GetNodeValue(nodeModule, "containersrc", string.Empty); + } + + module.DisplayTitle = XmlUtils.GetNodeValueBoolean(nodeModule, "displaytitle", true); + module.DisplayPrint = XmlUtils.GetNodeValueBoolean(nodeModule, "displayprint", true); + module.DisplaySyndicate = XmlUtils.GetNodeValueBoolean(nodeModule, "displaysyndicate", false); + module.IsWebSlice = XmlUtils.GetNodeValueBoolean(nodeModule, "iswebslice", false); + if (module.IsWebSlice) + { + module.WebSliceTitle = XmlUtils.GetNodeValue(nodeModule, "webslicetitle", module.ModuleTitle); + module.WebSliceExpiryDate = XmlUtils.GetNodeValueDate(nodeModule, "websliceexpirydate", module.EndDate); + module.WebSliceTTL = XmlUtils.GetNodeValueInt(nodeModule, "webslicettl", module.CacheTime / 60); + } + + return module; + } + + private static void DeserializeModulePermissions(XmlNodeList nodeModulePermissions, int portalId, ModuleInfo module) + { + var permissionController = new PermissionController(); + foreach (XmlNode node in nodeModulePermissions) + { + string permissionKey = XmlUtils.GetNodeValue(node.CreateNavigator(), "permissionkey"); + string permissionCode = XmlUtils.GetNodeValue(node.CreateNavigator(), "permissioncode"); + string roleName = XmlUtils.GetNodeValue(node.CreateNavigator(), "rolename"); + int roleID = int.MinValue; + switch (roleName) { - // close connection - CBO.CloseDataReader(dr, true); + case Globals.glbRoleAllUsersName: + roleID = Convert.ToInt32(Globals.glbRoleAllUsers); + break; + case Globals.glbRoleUnauthUserName: + roleID = Convert.ToInt32(Globals.glbRoleUnauthUser); + break; + default: + var role = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); + if (role != null) + { + roleID = role.RoleID; + } + + break; } - if (module != null) + if (roleID != int.MinValue) { - // add the module to the dictionary - clonemodules[module.ModuleDefinition.FriendlyName] = module; - - // set module caching settings - int timeOut = DataCache.ModuleCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + int permissionID = -1; + ArrayList permissions = permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey); + for (int i = 0; i <= permissions.Count - 1; i++) + { + var permission = (PermissionInfo)permissions[i]; + permissionID = permission.PermissionID; + } - // cache module dictionary - if (timeOut > 0) + // if role was found add, otherwise ignore + if (permissionID != -1) { - DataCache.SetCache(key, clonemodules, TimeSpan.FromMinutes(timeOut)); + var modulePermission = new ModulePermissionInfo + { + ModuleID = module.ModuleID, + PermissionID = permissionID, + RoleID = roleID, + AllowAccess = Convert.ToBoolean(XmlUtils.GetNodeValue(node.CreateNavigator(), "allowaccess")), + }; + + // do not add duplicate ModulePermissions + bool canAdd = !module.ModulePermissions.Cast() + .Any(mp => mp.ModuleID == modulePermission.ModuleID + && mp.PermissionID == modulePermission.PermissionID + && mp.RoleID == modulePermission.RoleID + && mp.UserID == modulePermission.UserID); + if (canAdd) + { + module.ModulePermissions.Add(modulePermission); + } } } } - - return module; } - /// - /// get a Module object. - /// - /// - /// - /// - /// - public ModuleInfo GetModuleByUniqueID(Guid uniqueID) + private static void DeserializeModuleSettings(XmlNodeList nodeModuleSettings, ModuleInfo objModule) { - return CBO.FillObject(dataProvider.GetModuleByUniqueID(uniqueID)); + foreach (XmlNode moduleSettingNode in nodeModuleSettings) + { + string key = XmlUtils.GetNodeValue(moduleSettingNode.CreateNavigator(), "settingname"); + string value = XmlUtils.GetNodeValue(moduleSettingNode.CreateNavigator(), "settingvalue"); + objModule.ModuleSettings[key] = value; + } } - /// - /// get all Module objects of a portal. - /// - /// ID of the portal. - /// ArrayList of ModuleInfo objects. - public ArrayList GetModules(int portalID) + private static void DeserializeTabModuleSettings(XmlNodeList nodeTabModuleSettings, ModuleInfo objModule) { - return CBO.FillCollection(dataProvider.GetModules(portalID), typeof(ModuleInfo)); + foreach (XmlNode tabModuleSettingNode in nodeTabModuleSettings) + { + string key = XmlUtils.GetNodeValue(tabModuleSettingNode.CreateNavigator(), "settingname"); + string value = XmlUtils.GetNodeValue(tabModuleSettingNode.CreateNavigator(), "settingvalue"); + objModule.TabModuleSettings[key] = value; + } } - /// - /// Gets the modules by definition. - /// - /// The portal ID. - /// The name of the module definition. - /// module collection. - public ArrayList GetModulesByDefinition(int portalID, string definitionName) + private static bool FindModule(XmlNode nodeModule, int tabId, PortalTemplateModuleAction mergeTabs) { - return CBO.FillCollection(DataProvider.Instance().GetModuleByDefinition(portalID, definitionName), typeof(ModuleInfo)); - } + var modules = Instance.GetTabModules(tabId); - /// - /// Gets the modules by DesktopModuleId. - /// - /// The Desktop Module Id. - /// module collection. - public ArrayList GetModulesByDesktopModuleId(int desktopModuleId) - { - var moduleDefinitions = ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModuleId); - var modules = new ArrayList(); - foreach (var moduleDefinition in moduleDefinitions) + bool moduleFound = false; + string modTitle = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "title"); + if (mergeTabs == PortalTemplateModuleAction.Merge) { - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + if (modules.Select(kvp => kvp.Value).Any(module => modTitle == module.ModuleTitle)) { - modules.AddRange(this.GetModulesByDefinition(portal.PortalID, moduleDefinition.Value.DefinitionName)); + moduleFound = true; } } - return modules; + return moduleFound; } - /// - /// For a portal get a list of all active module and tabmodule references that are Searchable - /// either by inheriting from ModuleSearchBase or implementing the older ISearchable interface. - /// - /// ID of the portal to be searched. - /// Arraylist of ModuleInfo for modules supporting search. - public ArrayList GetSearchModules(int portalID) + private static void GetModuleContent(XmlNode nodeModule, int ModuleId, int TabId, int PortalId) { - return CBO.FillCollection(dataProvider.GetSearchModules(portalID), typeof(ModuleInfo)); - } + ModuleInfo module = Instance.GetModule(ModuleId, TabId, true); + if (nodeModule != null) + { + // ReSharper disable PossibleNullReferenceException + string version = nodeModule.SelectSingleNode("content").Attributes["version"].Value; + string content = nodeModule.SelectSingleNode("content").InnerXml; + content = content.Substring(9, content.Length - 12); + if (!string.IsNullOrEmpty(module.DesktopModule.BusinessControllerClass) && !string.IsNullOrEmpty(content)) + { + var portal = PortalController.Instance.GetPortal(PortalId); - /// - /// get a Module object. - /// - /// ID of the tabmodule. - /// An ModuleInfo object. - public ModuleInfo GetTabModule(int tabModuleID) - { - var cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, tabModuleID); - return CBO.GetCachedObject( - new CacheItemArgs(cacheKey, DataCache.TabModuleCacheTimeOut, DataCache.TabModuleCachePriority), - c => CBO.FillObject(dataProvider.GetTabModule(tabModuleID))); - } + // Determine if the Module is copmpletely installed + // (ie are we running in the same request that installed the module). + if (module.DesktopModule.SupportedFeatures == Null.NullInteger) + { + // save content in eventqueue for processing after an app restart, + // as modules Supported Features are not updated yet so we + // cannot determine if the module supports IsPortable + EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); + } + else + { + if (module.DesktopModule.IsPortable) + { + try + { + object businessController = Reflection.CreateObject(module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); + var controller = businessController as IPortable; + if (controller != null) + { + var decodedContent = HttpContext.Current.Server.HtmlDecode(content); + controller.ImportModule(module.ModuleID, decodedContent, version, portal.AdministratorId); + } + } + catch + { + // if there is an error then the type cannot be loaded at this time, so add to EventQueue + EventMessageProcessor.CreateImportModuleMessage(module, content, version, portal.AdministratorId); + } + } + } + } - /// - /// Get all Module references on a tab. - /// - /// - /// Dictionary of ModuleID and ModuleInfo. - public Dictionary GetTabModules(int tabId) - { - var cacheKey = string.Format(DataCache.TabModuleCacheKey, tabId); - return CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.TabModuleCacheTimeOut, - DataCache.TabModuleCachePriority), - c => this.GetModulesCurrentPage(tabId)); + // ReSharper restore PossibleNullReferenceException + } } - /// - /// Get a list of all TabModule references of a module instance. - /// - /// ID of the Module. - /// ArrayList of ModuleInfo. - public IList GetTabModulesByModule(int moduleID) + private static ModuleDefinitionInfo GetModuleDefinition(XmlNode nodeModule) { - return CBO.FillCollection(dataProvider.GetModule(moduleID, Null.NullInteger)); - } - - public void InitialModulePermission(ModuleInfo module, int tabId, int permissionType) - { - var tabPermissions = TabPermissionController.GetTabPermissions(tabId, module.PortalID); - var permissionController = new PermissionController(); - - module.InheritViewPermissions = permissionType == 0; + ModuleDefinitionInfo moduleDefinition = null; - // get the default module view permissions - ArrayList systemModuleViewPermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); + // Templates prior to v4.3.5 only have the node to define the Module Type + // This node was populated with the DesktopModuleInfo.ModuleName property + // Thus there is no mechanism to determine to which module definition the module belongs. + // + // Template from v4.3.5 on also have the element that is populated + // with the ModuleDefinitionInfo.FriendlyName. Therefore the module Instance identifies + // which Module Definition it belongs to. - // get the permissions from the page - foreach (TabPermissionInfo tabPermission in tabPermissions) + // Get the DesktopModule defined by the element + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "definition"), Null.NullInteger); + if (desktopModule != null) { - if (tabPermission.PermissionKey == "VIEW" && permissionType == 0) - { - // Don't need to explicitly add View permisisons if "Same As Page" - continue; - } - - // get the system module permissions for the permissionkey - ArrayList systemModulePermissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", tabPermission.PermissionKey); - - // loop through the system module permissions - int j; - for (j = 0; j <= systemModulePermissions.Count - 1; j++) + // Get the moduleDefinition from the element + string friendlyName = XmlUtils.GetNodeValue(nodeModule.CreateNavigator(), "moduledefinition"); + if (string.IsNullOrEmpty(friendlyName)) { - // create the module permission - var systemModulePermission = (PermissionInfo)systemModulePermissions[j]; - if (systemModulePermission.PermissionKey == "VIEW" && permissionType == 1 && tabPermission.PermissionKey != "EDIT") - { - // Only Page Editors get View permissions if "Page Editors Only" - continue; - } - - ModulePermissionInfo modulePermission = this.AddModulePermission(module, systemModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); - - // ensure that every EDIT permission which allows access also provides VIEW permission - if (modulePermission.PermissionKey == "EDIT" && modulePermission.AllowAccess) + // Module is pre 4.3.5 so get the first Module Definition (at least it won't throw an error then) + foreach (ModuleDefinitionInfo md in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModule.DesktopModuleID).Values) { - this.AddModulePermission(module, (PermissionInfo)systemModuleViewPermissions[0], modulePermission.RoleID, modulePermission.UserID, true); + moduleDefinition = md; + break; } } - - // Get the custom Module Permissions, Assume that roles with Edit Tab Permissions - // are automatically assigned to the Custom Module Permissions - if (tabPermission.PermissionKey == "EDIT") + else { - ArrayList customModulePermissions = permissionController.GetPermissionsByModuleDefID(module.ModuleDefID); - - // loop through the custom module permissions - for (j = 0; j <= customModulePermissions.Count - 1; j++) - { - // create the module permission - var customModulePermission = (PermissionInfo)customModulePermissions[j]; - - this.AddModulePermission(module, customModulePermission, tabPermission.RoleID, tabPermission.UserID, tabPermission.AllowAccess); - } + // Module is 4.3.5 or later so get the Module Defeinition by its friendly name + moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName, desktopModule.DesktopModuleID); } } + + return moduleDefinition; } - private Dictionary GetModulesCurrentPage(int tabId) + private static void SetCloneModuleContext(bool cloneModuleContext) { - var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); - - var dictionary = new Dictionary(); - foreach (var module in modules) - { - dictionary[module.ModuleID] = module; - } + Thread.SetData( + Thread.GetNamedDataSlot("CloneModuleContext"), + cloneModuleContext ? bool.TrueString : bool.FalseString); + } - return dictionary; + private static void UpdateTabModuleVersion(int tabModuleId) + { + dataProvider.UpdateTabModuleVersion(tabModuleId, Guid.NewGuid()); } - public void LocalizeModule(ModuleInfo sourceModule, Locale locale) + private void AddModuleInternal(ModuleInfo module) { - try + // add module + if (Null.IsNull(module.ModuleID)) { - // we could be working from a single culture page that is not in the default language, - // so we need to test whether or not the module is going to be localized for the default locale - var defaultLocale = LocaleController.Instance.GetDefaultLocale(sourceModule.PortalID); - ModuleInfo defaultModule = locale.Code == defaultLocale.Code ? sourceModule : sourceModule.DefaultLanguageModule; - - if (defaultModule != null) - { - ModuleInfo localizedModule; - var alreadyLocalized = defaultModule.LocalizedModules.TryGetValue(locale.Code, out localizedModule) - && localizedModule.ModuleID != defaultModule.ModuleID; - var tabModules = this.GetTabModulesByModule(defaultModule.ModuleID); - if (tabModules.Count > 1) - { - // default language version is a reference copy + var currentUser = UserController.Instance.GetCurrentUserInfo(); + this.CreateContentItem(module); - // Localize first tabModule - var newModuleId = alreadyLocalized ? localizedModule.ModuleID : this.LocalizeModuleInternal(sourceModule); + // 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); - // Update Reference Copies - foreach (ModuleInfo tm in tabModules) - { - if (tm.IsDefaultLanguage) - { - ModuleInfo localModule; - if (tm.LocalizedModules.TryGetValue(locale.Code, out localModule)) - { - localModule.ModuleID = newModuleId; - this.UpdateModule(localModule); - } - } - } - } - else if (!alreadyLocalized) - { - this.LocalizeModuleInternal(sourceModule); - } - } - } - catch (Exception ex) - { - Logger.ErrorFormat("Error localizing module, moduleId: {0}, full exception: {1}", sourceModule.ModuleID, ex); - } - } + // Now we have the ModuleID - update the contentItem + var contentController = Util.GetContentController(); + contentController.UpdateContentItem(module); - /// - /// MoveModule moes a Module from one Tab to another including all the - /// TabModule settings. - /// - /// The Id of the module to move. - /// The Id of the source tab. - /// The Id of the destination tab. - /// The name of the Pane on the destination tab where the module will end up. - public void MoveModule(int moduleId, int fromTabId, int toTabId, string toPaneName) - { - // Move the module to the Tab - dataProvider.MoveTabModule(fromTabId, moduleId, toTabId, toPaneName, UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_CREATED); - // Update the Tab reference for the module's ContentItems - var contentController = Util.GetContentController(); - var contentItems = contentController.GetContentItemsByModuleId(moduleId); - if (contentItems != null) - { - foreach (var item in contentItems) - { - if (item.TabID != toTabId) - { - item.TabID = toTabId; - contentController.UpdateContentItem(item); - } - } + // set module permissions + ModulePermissionController.SaveModulePermissions(module); } - // Update Module Order for source tab, also updates the tabmodule version guid - this.UpdateTabModuleOrder(fromTabId); - - // Update Module Order for target tab, also updates the tabmodule version guid - this.UpdateTabModuleOrder(toTabId); - } + // Save ModuleSettings + this.UpdateModuleSettings(module); - /// - /// Restores the module. - /// - /// The module. - public void RestoreModule(ModuleInfo objModule) - { - dataProvider.RestoreTabModule(objModule.TabID, objModule.ModuleID); - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - TabChangeTracker.Instance.TrackModuleAddition(objModule, 1, userId); - this.ClearCache(objModule.TabID); + EventManager.Instance.OnModuleCreated(new ModuleEventArgs { Module = module }); } - /// - /// Update module settings and permissions in database from ModuleInfo. - /// - /// ModuleInfo of the module to update. - public void UpdateModule(ModuleInfo module) + private ModulePermissionInfo AddModulePermission(ModuleInfo module, PermissionInfo permission, int roleId, int userId, bool allowAccess) { - // Update ContentItem If neccessary - if (module.ModuleID != Null.NullInteger) + var modulePermission = new ModulePermissionInfo { - if (module.ContentItemId == Null.NullInteger) - { - this.CreateContentItem(module); - } - else - { - this.UpdateContentItem(module); - } - } - - var currentUser = UserController.Instance.GetCurrentUserInfo(); - - // update module - dataProvider.UpdateModule( - module.ModuleID, - module.ModuleDefID, - module.ContentItemId, - module.AllTabs, - module.StartDate, - module.EndDate, - module.InheritViewPermissions, - module.IsShareable, - module.IsShareableViewOnly, - module.IsDeleted, - currentUser.UserID); + ModuleID = module.ModuleID, + PermissionID = permission.PermissionID, + RoleID = roleId, + UserID = userId, + PermissionKey = permission.PermissionKey, + AllowAccess = allowAccess, + }; - // Update Tags - ITermController termController = Util.GetTermController(); - termController.RemoveTermsFromContent(module); - foreach (Term term in module.Terms) + // add the permission to the collection + if (!module.ModulePermissions.Contains(modulePermission)) { - termController.AddTermToContent(term, module); + module.ModulePermissions.Add(modulePermission); } - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.MODULE_UPDATED); - - // save module permissions - ModulePermissionController.SaveModulePermissions(module); - this.UpdateModuleSettings(module); - module.VersionGuid = Guid.NewGuid(); - module.LocalizedVersionGuid = Guid.NewGuid(); + return modulePermission; + } - if (!Null.IsNull(module.TabID)) + private void CopyTabModuleSettingsInternal(ModuleInfo fromModule, ModuleInfo toModule) + { + // Copy each setting to the new TabModule instance + foreach (DictionaryEntry setting in fromModule.TabModuleSettings) { - var hasModuleOrderOrPaneChanged = this.HasModuleOrderOrPaneChanged(module); - - // update tabmodule - dataProvider.UpdateTabModule( - module.TabModuleID, - module.TabID, - module.ModuleID, - module.ModuleTitle, - module.Header, - module.Footer, - module.ModuleOrder, - module.PaneName, - module.CacheTime, - module.CacheMethod, - module.Alignment, - module.Color, - module.Border, - module.IconFile, - (int)module.Visibility, - module.ContainerSrc, - module.DisplayTitle, - module.DisplayPrint, - module.DisplaySyndicate, - module.IsWebSlice, - module.WebSliceTitle, - module.WebSliceExpiryDate, - module.WebSliceTTL, - module.VersionGuid, - module.DefaultLanguageGuid, - module.LocalizedVersionGuid, - module.CultureCode, - currentUser.UserID); - - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, module.TabModuleID)); - - EventLogController.Instance.AddLog(module, PortalController.Instance.GetCurrentPortalSettings(), currentUser.UserID, string.Empty, EventLogController.EventLogType.TABMODULE_UPDATED); - - if (hasModuleOrderOrPaneChanged) - { - // update module order in pane - this.UpdateModuleOrder(module.TabID, module.ModuleID, module.ModuleOrder, module.PaneName); - } - - // set the default module - if (PortalSettings.Current != null) - { - if (module.IsDefaultModule) - { - if (module.ModuleID != PortalSettings.Current.DefaultModuleId) - { - // Update Setting - PortalController.UpdatePortalSetting(module.PortalID, "defaultmoduleid", module.ModuleID.ToString(CultureInfo.InvariantCulture)); - } - - if (module.TabID != PortalSettings.Current.DefaultTabId) - { - // Update Setting - PortalController.UpdatePortalSetting(module.PortalID, "defaulttabid", module.TabID.ToString(CultureInfo.InvariantCulture)); - } - } - else - { - if (module.ModuleID == PortalSettings.Current.DefaultModuleId && module.TabID == PortalSettings.Current.DefaultTabId) - { - // Clear setting - PortalController.DeletePortalSetting(module.PortalID, "defaultmoduleid"); - PortalController.DeletePortalSetting(module.PortalID, "defaulttabid"); - } - } - } - - // apply settings to all desktop modules in portal - if (module.AllModules) - { - foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(module.PortalID)) - { - TabInfo tab = tabPair.Value; - foreach (KeyValuePair modulePair in this.GetTabModules(tab.TabID)) - { - var targetModule = modulePair.Value; - targetModule.VersionGuid = Guid.NewGuid(); - targetModule.LocalizedVersionGuid = Guid.NewGuid(); - - dataProvider.UpdateTabModule( - targetModule.TabModuleID, - targetModule.TabID, - targetModule.ModuleID, - targetModule.ModuleTitle, - targetModule.Header, - targetModule.Footer, - targetModule.ModuleOrder, - targetModule.PaneName, - targetModule.CacheTime, - targetModule.CacheMethod, - module.Alignment, - module.Color, - module.Border, - module.IconFile, - (int)module.Visibility, - module.ContainerSrc, - module.DisplayTitle, - module.DisplayPrint, - module.DisplaySyndicate, - module.IsWebSlice, - module.WebSliceTitle, - module.WebSliceExpiryDate, - module.WebSliceTTL, - targetModule.VersionGuid, - targetModule.DefaultLanguageGuid, - targetModule.LocalizedVersionGuid, - targetModule.CultureCode, - currentUser.UserID); - - DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, targetModule.TabModuleID)); - this.ClearCache(targetModule.TabID); - } - } - } + 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); - // Clear Cache for all TabModules - foreach (ModuleInfo tabModule in this.GetTabModulesByModule(module.ModuleID)) + Requires.NotNull(permission); + + var permissionViewKey = "VIEW"; + + if (!module.InheritViewPermissions || permission.PermissionKey != permissionViewKey) { - this.ClearCache(tabModule.TabID); + return false; } - EventManager.Instance.OnModuleUpdated(new ModuleEventArgs { Module = module }); + var tabPermissions = TabPermissionController.GetTabPermissions(module.TabID, module.PortalID); + + return tabPermissions?.Where(x => x.RoleID == permission.RoleID && x.PermissionKey == permissionViewKey).Any() == true; } /// - /// set/change the module position within a pane on a page. + /// Checks whether given permission is granted for translator role. /// - /// ID of the page. - /// ID of the module on the page. - /// position within the controls list on page, -1 if to be added at the end. - /// name of the pane, the module is placed in on the page. - public void UpdateModuleOrder(int tabId, int moduleId, int moduleOrder, string paneName) + /// The module permission. + /// The portal ID. + /// The culture code. + private bool IsTranslatorRolePermission(ModulePermissionInfo permission, int portalId, string culture) { - ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); - if (moduleInfo != null) + Requires.NotNull(permission); + + if (string.IsNullOrWhiteSpace(culture) || portalId == Null.NullInteger) { - // adding a module to a new pane - places the module at the bottom of the pane - if (moduleOrder == -1) - { - IDataReader dr = null; - try - { - dr = dataProvider.GetTabModuleOrder(tabId, paneName); - while (dr.Read()) - { - moduleOrder = Convert.ToInt32(dr["ModuleOrder"]); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } + return false; + } - moduleOrder += 2; - } + var translatorSettingKey = $"DefaultTranslatorRoles-{culture}"; - dataProvider.UpdateModuleOrder(tabId, moduleId, moduleOrder, paneName); - TabChangeTracker.Instance.TrackModuleModification(this.GetModule(moduleId, tabId, true), Null.NullInteger, UserController.Instance.GetCurrentUserInfo().UserID); + var translatorSettingValue = + PortalController.GetPortalSetting(translatorSettingKey, portalId, null) ?? + HostController.Instance.GetString(translatorSettingKey, null); - // clear cache - this.ClearCache(tabId); - } + var translatorRoles = + translatorSettingValue?.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); + + return translatorRoles?.Any(r => r.Equals(permission.RoleName, StringComparison.OrdinalIgnoreCase)) == true; } /// - /// Adds or updates a module's setting value. + /// Copies permissions from source to new tab. /// - /// ID of the module, the setting belongs to. - /// name of the setting property. - /// value of the setting (String). - /// empty SettingValue will remove the setting, if not preserveIfEmpty is true. - public void UpdateModuleSetting(int moduleId, string settingName, string settingValue) + /// Source module. + /// New module. + private void CopyModulePermisions(ModuleInfo sourceModule, ModuleInfo newModule) { - this.UpdateModuleSettingInternal(moduleId, settingName, settingValue, true); + 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); + } } - /// - /// set/change all module's positions within a page. - /// - /// ID of the page. - public void UpdateTabModuleOrder(int tabId) + private int LocalizeModuleInternal(ModuleInfo sourceModule) { - IDataReader dr = dataProvider.GetTabPanes(tabId); - try + int moduleId = Null.NullInteger; + + if (sourceModule != null) { - while (dr.Read()) + // clone the module object ( to avoid creating an object reference to the data cache ) + var newModule = sourceModule.Clone(); + newModule.ModuleID = Null.NullInteger; + + string translatorRoles = PortalController.GetPortalSetting(string.Format("DefaultTranslatorRoles-{0}", sourceModule.CultureCode), sourceModule.PortalID, string.Empty).TrimEnd(';'); + + // Add the default translators for this language, view and edit permissions + var permissionController = new PermissionController(); + var viewPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "VIEW"); + var editPermissionsList = permissionController.GetPermissionByCodeAndKey("SYSTEM_MODULE_DEFINITION", "EDIT"); + PermissionInfo viewPermisison = null; + PermissionInfo editPermisison = null; + + // View + if (viewPermissionsList != null && viewPermissionsList.Count > 0) { - int moduleCounter = 0; - IDataReader dr2 = dataProvider.GetTabModuleOrder(tabId, Convert.ToString(dr["PaneName"])); - try + viewPermisison = (PermissionInfo)viewPermissionsList[0]; + } + + // Edit + if (editPermissionsList != null && editPermissionsList.Count > 0) + { + editPermisison = (PermissionInfo)editPermissionsList[0]; + } + + if (viewPermisison != null || editPermisison != null) + { + foreach (string translatorRole in translatorRoles.Split(';')) { - while (dr2.Read()) - { - moduleCounter += 1; + AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, viewPermisison, "VIEW"); + AddModulePermission(ref newModule, sourceModule.PortalID, translatorRole, editPermisison, "EDIT"); + } + } - var moduleId = Convert.ToInt32(dr2["ModuleID"]); - var paneName = Convert.ToString(dr["PaneName"]); - var isDeleted = Convert.ToBoolean(dr2["IsDeleted"]); - var existingOrder = Convert.ToInt32(dr2["ModuleOrder"]); - var newOrder = (moduleCounter * 2) - 1; + // copy permisions from source to new module + this.CopyModulePermisions(sourceModule, newModule); - if (existingOrder == newOrder) - { - continue; - } + // Add Module + this.AddModuleInternal(newModule); - dataProvider.UpdateModuleOrder(tabId, moduleId, newOrder, paneName); + // copy module settings + DataCache.RemoveCache(string.Format(DataCache.ModuleSettingsCacheKey, sourceModule.TabID)); + var settings = this.GetModuleSettings(sourceModule.ModuleID, sourceModule.TabID); - if (!isDeleted) + // update tabmodule + var currentUser = UserController.Instance.GetCurrentUserInfo(); + dataProvider.UpdateTabModule( + newModule.TabModuleID, + newModule.TabID, + newModule.ModuleID, + newModule.ModuleTitle, + newModule.Header, + newModule.Footer, + newModule.ModuleOrder, + newModule.PaneName, + newModule.CacheTime, + newModule.CacheMethod, + newModule.Alignment, + newModule.Color, + newModule.Border, + newModule.IconFile, + (int)newModule.Visibility, + newModule.ContainerSrc, + newModule.DisplayTitle, + newModule.DisplayPrint, + newModule.DisplaySyndicate, + newModule.IsWebSlice, + newModule.WebSliceTitle, + newModule.WebSliceExpiryDate, + newModule.WebSliceTTL, + newModule.VersionGuid, + newModule.DefaultLanguageGuid, + newModule.LocalizedVersionGuid, + newModule.CultureCode, + currentUser.UserID); + + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, newModule.TabModuleID)); + + // Copy each setting to the new TabModule instance + foreach (DictionaryEntry setting in settings) + { + this.UpdateModuleSetting(newModule.ModuleID, Convert.ToString(setting.Key), Convert.ToString(setting.Value)); + } + + if (!string.IsNullOrEmpty(newModule.DesktopModule.BusinessControllerClass)) + { + try + { + object businessController = Reflection.CreateObject(newModule.DesktopModule.BusinessControllerClass, newModule.DesktopModule.BusinessControllerClass); + var portableModule = businessController as IPortable; + if (portableModule != null) + { + try { - var moduleInfo = this.GetModule(moduleId, tabId, true); - var userInfo = UserController.Instance.GetCurrentUserInfo(); - TabChangeTracker.Instance.TrackModuleModification(moduleInfo, Null.NullInteger, - userInfo.UserID); + SetCloneModuleContext(true); + string moduleContent = portableModule.ExportModule(sourceModule.ModuleID); + if (!string.IsNullOrEmpty(moduleContent)) + { + portableModule.ImportModule(newModule.ModuleID, moduleContent, newModule.DesktopModule.Version, currentUser.UserID); + } + } + finally + { + SetCloneModuleContext(false); } } } - catch (Exception ex2) - { - Exceptions.LogException(ex2); - } - finally + catch (Exception ex) { - CBO.CloseDataReader(dr2, true); + Exceptions.LogException(ex); } } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); + + moduleId = newModule.ModuleID; + + // Clear Caches + this.ClearCache(newModule.TabID); + this.ClearCache(sourceModule.TabID); } - // clear module cache - this.ClearCache(tabId); + return moduleId; } - /// - /// Adds or updates a module's setting value. - /// - /// ID of the tabmodule, the setting belongs to. - /// name of the setting property. - /// value of the setting (String). - /// empty SettingValue will relove the setting. - public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) + private void UpdateModuleSettingInternal(int moduleId, string settingName, string settingValue, bool updateVersion) { - IDataReader dr = dataProvider.GetTabModuleSetting(tabModuleId, settingName); + IDataReader dr = null; try { var currentUser = UserController.Instance.GetCurrentUserInfo(); + dr = dataProvider.GetModuleSetting(moduleId, settingName); + + string existValue = null; if (dr.Read()) { - if (dr.GetString(1) != settingValue) - { - dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.MODULE_SETTING_UPDATED, - "TabModuleId", tabModuleId, settingName, settingValue, - currentUser.UserID); - UpdateTabModuleVersion(tabModuleId); - } + existValue = dr.GetString(1); } - else + + dr.Close(); + + if (existValue == null) { - dataProvider.UpdateTabModuleSetting(tabModuleId, settingName, settingValue, currentUser.UserID); + dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); EventLogController.AddSettingLog( - EventLogController.EventLogType.TABMODULE_SETTING_CREATED, - "TabModuleId", tabModuleId, settingName, settingValue, + EventLogController.EventLogType.MODULE_SETTING_CREATED, + "ModuleId", moduleId, settingName, settingValue, currentUser.UserID); - UpdateTabModuleVersion(tabModuleId); + } + else if (existValue != settingValue) + { + dataProvider.UpdateModuleSetting(moduleId, settingName, settingValue, currentUser.UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.MODULE_SETTING_UPDATED, + "ModuleId", moduleId, settingName, settingValue, + currentUser.UserID); + } + + if (updateVersion) + { + this.UpdateTabModuleVersionsByModuleID(moduleId); } } catch (Exception ex) @@ -2468,166 +2514,120 @@ public void UpdateTabModuleSetting(int tabModuleId, string settingName, string s finally { // Ensure DataReader is closed - CBO.CloseDataReader(dr, true); + if (dr != null && !dr.IsClosed) + { + CBO.CloseDataReader(dr, true); + } } - ClearTabModuleSettingsCache(tabModuleId, settingName); + ClearModuleSettingsCache(moduleId); } - /// - /// Updates the translation status. - /// - /// The localized module. - /// if set to true will mark the module as translated]. - public void UpdateTranslationStatus(ModuleInfo localizedModule, bool isTranslated) + private void UpdateModuleSettings(ModuleInfo updatedModule) { - if (isTranslated && (localizedModule.DefaultLanguageModule != null)) + foreach (string key in updatedModule.ModuleSettings.Keys) { - localizedModule.LocalizedVersionGuid = localizedModule.DefaultLanguageModule.LocalizedVersionGuid; + string sKey = key; + this.UpdateModuleSettingInternal(updatedModule.ModuleID, sKey, Convert.ToString(updatedModule.ModuleSettings[sKey]), false); } - else + + this.UpdateTabModuleVersionsByModuleID(updatedModule.ModuleID); + } + + private void UpdateTabModuleSettings(ModuleInfo updatedTabModule) + { + foreach (string sKey in updatedTabModule.TabModuleSettings.Keys) { - localizedModule.LocalizedVersionGuid = Guid.NewGuid(); + this.UpdateTabModuleSetting(updatedTabModule.TabModuleID, sKey, Convert.ToString(updatedTabModule.TabModuleSettings[sKey])); } + } - DataProvider.Instance().UpdateTabModuleTranslationStatus(localizedModule.TabModuleID, localizedModule.LocalizedVersionGuid, UserController.Instance.GetCurrentUserInfo().UserID); + private void UpdateTabModuleVersionsByModuleID(int moduleID) + { + // Update the version guid of each TabModule linked to the updated module + foreach (ModuleInfo modInfo in this.GetAllTabsModulesByModuleID(moduleID)) + { + this.ClearCache(modInfo.TabID); + } - // Clear Tab Caches - this.ClearCache(localizedModule.TabID); + dataProvider.UpdateTabModuleVersionByModule(moduleID); } - /// - /// SerializeModule. - /// - /// The Xml Document to use for the Module. - /// The ModuleInfo object to serialize. - /// A flak that determines whether the content of the module is serialised. - /// - public static XmlNode SerializeModule(XmlDocument xmlModule, ModuleInfo module, bool includeContent) + private bool HasModuleOrderOrPaneChanged(ModuleInfo module) { - var serializer = new XmlSerializer(typeof(ModuleInfo)); - var sw = new StringWriter(); - serializer.Serialize(sw, module); - xmlModule.LoadXml(sw.GetStringBuilder().ToString()); - XmlNode moduleNode = xmlModule.SelectSingleNode("module"); - if (moduleNode != null) - { - // ReSharper disable AssignNullToNotNullAttribute - if (moduleNode.Attributes != null) - { - moduleNode.Attributes.Remove(moduleNode.Attributes["xmlns:xsd"]); - moduleNode.Attributes.Remove(moduleNode.Attributes["xmlns:xsi"]); - } + var storedModuleInfo = this.GetTabModule(module.TabModuleID); + return storedModuleInfo == null || storedModuleInfo.ModuleOrder != module.ModuleOrder || storedModuleInfo.PaneName != module.PaneName; + } - // remove unwanted elements - moduleNode.RemoveChild(moduleNode.SelectSingleNode("portalid")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabid")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("tabmoduleid")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("moduleorder")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("panename")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("isdeleted")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("versionGuid")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("localizedVersionGuid")); - moduleNode.RemoveChild(moduleNode.SelectSingleNode("content")); + private void UncopyModule(int tabId, int moduleId, bool softDelete, int originalTabId) + { + ModuleInfo moduleInfo = this.GetModule(moduleId, tabId, false); + this.DeleteTabModuleInternal(moduleInfo, softDelete, true); + var userId = UserController.Instance.GetCurrentUserInfo().UserID; + TabChangeTracker.Instance.TrackModuleUncopy(moduleInfo, Null.NullInteger, originalTabId, userId); + } - // support for localized templates - // moduleNode.RemoveChild(moduleNode.SelectSingleNode("uniqueId")); - // moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); - // moduleNode.RemoveChild(moduleNode.SelectSingleNode("cultureCode")); - if (Null.IsNull(module.DefaultLanguageGuid)) - { - moduleNode.RemoveChild(moduleNode.SelectSingleNode("defaultLanguageGuid")); - } + private void DeleteTabModuleInternal(ModuleInfo moduleInfo, bool softDelete, bool uncopy = false) + { + // save moduleinfo + if (moduleInfo != null) + { + // delete the module instance for the tab + dataProvider.DeleteTabModule(moduleInfo.TabID, moduleInfo.ModuleID, softDelete, UserController.Instance.GetCurrentUserInfo().UserID); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.TABMODULE_DELETED.ToString() }; + log.LogProperties.Add(new LogDetailInfo("tabId", moduleInfo.TabID.ToString(CultureInfo.InvariantCulture))); + log.LogProperties.Add(new LogDetailInfo("moduleId", moduleInfo.ModuleID.ToString(CultureInfo.InvariantCulture))); + LogController.Instance.AddLog(log); - var xmlNodeList = moduleNode.SelectNodes("modulepermissions/permission"); - if (xmlNodeList != null) + // reorder all modules on tab + if (!uncopy) { - foreach (XmlNode nodePermission in xmlNodeList) + this.UpdateTabModuleOrder(moduleInfo.TabID); + + // ModuleRemove is only raised when doing a soft delete of the module + if (softDelete) { - nodePermission.RemoveChild(nodePermission.SelectSingleNode("modulepermissionid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("moduleid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); + EventManager.Instance.OnModuleRemoved(new ModuleEventArgs { Module = moduleInfo }); } } - if (includeContent) + // check if all modules instances have been deleted + if (this.GetModule(moduleInfo.ModuleID, Null.NullInteger, true).TabID == Null.NullInteger) { - AddContent(moduleNode, module); + // hard delete the module + this.DeleteModule(moduleInfo.ModuleID); } - // serialize ModuleSettings and TabModuleSettings - XmlUtils.SerializeHashtable(module.ModuleSettings, xmlModule, moduleNode, "modulesetting", "settingname", "settingvalue"); - XmlUtils.SerializeHashtable(module.TabModuleSettings, xmlModule, moduleNode, "tabmodulesetting", "settingname", "settingvalue"); - - // ReSharper restore AssignNullToNotNullAttribute - } - - XmlNode newNode = xmlModule.CreateElement("definition"); - ModuleDefinitionInfo objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(module.ModuleDefID); - newNode.InnerText = DesktopModuleController.GetDesktopModule(objModuleDef.DesktopModuleID, module.PortalID).ModuleName; - if (moduleNode != null) - { - moduleNode.AppendChild(newNode); - } - - // Add Module Definition Info - XmlNode definitionNode = xmlModule.CreateElement("moduledefinition"); - definitionNode.InnerText = objModuleDef.FriendlyName; - if (moduleNode != null) - { - moduleNode.AppendChild(definitionNode); + DataCache.RemoveCache(string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID)); + this.ClearCache(moduleInfo.TabID); } - - return moduleNode; } /// - /// Synchronizes the module content between cache and database. + /// Update content item when the module title changed. /// - /// The module ID. - public static void SynchronizeModule(int moduleID) + /// + private void UpdateContentItem(ModuleInfo module) { - var modules = Instance.GetTabModulesByModule(moduleID); - foreach (ModuleInfo module in modules) + IContentController contentController = Util.GetContentController(); + if (module.Content != module.ModuleTitle) { - Hashtable tabSettings = TabController.Instance.GetTabSettings(module.TabID); - if (tabSettings["CacheProvider"] != null && tabSettings["CacheProvider"].ToString().Length > 0) - { - var outputProvider = OutputCachingProvider.Instance(tabSettings["CacheProvider"].ToString()); - if (outputProvider != null) - { - outputProvider.Remove(module.TabID); - } - } - - if (module.CacheTime > 0) - { - var moduleProvider = ModuleCachingProvider.Instance(module.GetEffectiveCacheMethod()); - if (moduleProvider != null) - { - moduleProvider.Remove(module.TabModuleID); - } - } - - // Synchronize module is called when a module needs to indicate that the content - // has changed and the cache's should be refreshed. So we can update the Version - // and also the LastContentModificationDate - UpdateTabModuleVersion(module.TabModuleID); - dataProvider.UpdateModuleLastContentModifiedOnDate(module.ModuleID); + module.Content = module.ModuleTitle; + contentController.UpdateContentItem(module); + } + } - // We should also indicate that the Transalation Status has changed - if (PortalController.GetPortalSettingAsBoolean("ContentLocalizationEnabled", module.PortalID, false)) - { - Instance.UpdateTranslationStatus(module, false); - } + private Dictionary GetModulesCurrentPage(int tabId) + { + var modules = CBO.FillCollection(DataProvider.Instance().GetTabModules(tabId)); - // and clear the cache - Instance.ClearCache(module.TabID); + var dictionary = new Dictionary(); + foreach (var module in modules) + { + dictionary[module.ModuleID] = module; } + + return dictionary; } } } diff --git a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs index b2437dedddd..5fa42d6a9bd 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleInfo.cs @@ -53,7 +53,7 @@ public class ModuleInfo : ContentItem, IPropertyAccess private TabInfo _parentTab; private Hashtable _moduleSettings; private Hashtable _tabModuleSettings; - + public ModuleInfo() { // initialize the properties that can be null @@ -89,33 +89,6 @@ public ModuleInfo() this._defaultLanguageGuid = Null.NullGuid; } - [XmlElement("alignment")] - public string Alignment { get; set; } - - [XmlIgnore] - public bool AllModules { get; set; } - - [XmlElement("alltabs")] - public bool AllTabs { get; set; } - - [XmlElement("border")] - public string Border { get; set; } - - [XmlElement("cachemethod")] - public string CacheMethod { get; set; } - - [XmlElement("cachetime")] - public int CacheTime { get; set; } - - [XmlElement("color")] - public string Color { get; set; } - - [XmlIgnore] - public string ContainerPath { get; set; } - - [XmlElement("containersrc")] - public string ContainerSrc { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets the Associated Desktop Module. @@ -125,7 +98,7 @@ public ModuleInfo() [XmlIgnore] public DesktopModuleInfo DesktopModule { - get + get { return this._desktopModule ?? (this._desktopModule = this.DesktopModuleID > Null.NullInteger @@ -134,33 +107,6 @@ public DesktopModuleInfo DesktopModule } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the ID of the Associated Desktop Module. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public int DesktopModuleID { get; set; } - - [XmlElement("displayprint")] - public bool DisplayPrint { get; set; } - - [XmlElement("displaysyndicate")] - public bool DisplaySyndicate { get; set; } - - [XmlElement("displaytitle")] - public bool DisplayTitle { get; set; } - - [XmlElement("enddate")] - public DateTime EndDate { get; set; } - - [XmlElement("footer")] - public string Footer { get; set; } - - [XmlElement("header")] - public string Header { get; set; } - [XmlIgnore] public bool HideAdminBorder { @@ -178,39 +124,15 @@ public bool HideAdminBorder } } - [XmlElement("iconfile")] - public string IconFile { get; set; } - - [XmlElement("inheritviewpermissions")] - public bool InheritViewPermissions { get; set; } - - [XmlIgnore] - public bool IsDefaultModule { get; set; } - - [XmlElement("isdeleted")] - public bool IsDeleted { get; set; } - - [XmlIgnore] - public bool IsShareable { get; set; } - [XmlIgnore] public bool IsShared { get { return this.OwnerPortalID != this.PortalID; } } - [XmlIgnore] - public bool IsShareableViewOnly { get; set; } - - [XmlElement("iswebslice")] - public bool IsWebSlice { get; set; } - - [XmlIgnore] - public DateTime LastContentModifiedOnDate { get; set; } - public ModuleControlInfo ModuleControl { - get + get { return this._moduleControl ?? (this._moduleControl = this.ModuleControlId > Null.NullInteger @@ -219,18 +141,6 @@ public ModuleControlInfo ModuleControl } } - [XmlIgnore] - public int ModuleControlId { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the ID of the Associated Module Definition. - /// - /// An Integer. - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public int ModuleDefID { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets the Associated Module Definition. @@ -240,7 +150,7 @@ public ModuleControlInfo ModuleControl [XmlIgnore] public ModuleDefinitionInfo ModuleDefinition { - get + get { return this._moduleDefinition ?? (this._moduleDefinition = this.ModuleDefID > Null.NullInteger @@ -249,34 +159,6 @@ public ModuleDefinitionInfo ModuleDefinition } } - [XmlElement("moduleorder")] - public int ModuleOrder { get; set; } - - /// - /// Gets or sets get the ModulePermissions for the Module DO NOT USE THE SETTTER. - /// - /// Since 5.0 the setter has been obsolete, directly setting the ModulePermissionCollection is likely an error, change the contenst of the collection instead. - /// The setter still exists to preserve binary compatibility without the obsolete attribute since c# will not allow only a setter to be obsolete. - /// - /// - [XmlArray("modulepermissions")] - [XmlArrayItem("permission")] - public ModulePermissionCollection ModulePermissions - { - get - { - return this._modulePermissions ?? - (this._modulePermissions = this.ModuleID > 0 - ? new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabID)) - : new ModulePermissionCollection()); - } - - set - { - this._modulePermissions = value; - } - } - [XmlIgnore] public Hashtable ModuleSettings { @@ -293,38 +175,11 @@ public Hashtable ModuleSettings this._moduleSettings = new ModuleController().GetModuleSettings(this.ModuleID, this.TabID); } } - + return this._moduleSettings; } } - [XmlElement("title")] - public string ModuleTitle { get; set; } - - [XmlIgnore] - public int ModuleVersion { get; set; } - - [XmlIgnore] - public int OwnerPortalID { get; set; } - - [XmlIgnore] - public int PaneModuleCount { get; set; } - - [XmlIgnore] - public int PaneModuleIndex { get; set; } - - [XmlElement("panename")] - public string PaneName { get; set; } - - [XmlElement("portalid")] - public int PortalID { get; set; } - - [XmlElement("startdate")] - public DateTime StartDate { get; set; } - - [XmlElement("tabmoduleid")] - public int TabModuleID { get; set; } - [XmlIgnore] public Hashtable TabModuleSettings { @@ -346,52 +201,6 @@ public Hashtable TabModuleSettings } } - [XmlElement("uniqueId")] - public Guid UniqueId { get; set; } - - [XmlElement("versionGuid")] - public Guid VersionGuid { get; set; } - - [XmlElement("visibility")] - public VisibilityState Visibility { get; set; } - - [XmlElement("websliceexpirydate")] - public DateTime WebSliceExpiryDate { get; set; } - - [XmlElement("webslicetitle")] - public string WebSliceTitle { get; set; } - - [XmlElement("webslicettl")] - public int WebSliceTTL { get; set; } - - [XmlElement("cultureCode")] - public string CultureCode - { - get - { - return this._cultureCode; - } - - set - { - this._cultureCode = value; - } - } - - [XmlElement("defaultLanguageGuid")] - public Guid DefaultLanguageGuid - { - get - { - return this._defaultLanguageGuid; - } - - set - { - this._defaultLanguageGuid = value; - } - } - [XmlIgnore] public ModuleInfo DefaultLanguageModule { @@ -402,7 +211,7 @@ public ModuleInfo DefaultLanguageModule { this._defaultLanguageModule = (from kvp in this.ParentTab.DefaultLanguageTab.ChildModules where kvp.Value.UniqueId == this.DefaultLanguageGuid select kvp.Value).SingleOrDefault(); } - + return this._defaultLanguageModule; } } @@ -425,7 +234,7 @@ public bool IsLocalized // Child language isLocalized = this.ModuleID != this.DefaultLanguageModule.ModuleID; } - + return isLocalized; } } @@ -449,7 +258,7 @@ public bool IsTranslated // Child language isTranslated = this.LocalizedVersionGuid == this.DefaultLanguageModule.LocalizedVersionGuid; } - + return isTranslated; } } @@ -475,25 +284,11 @@ public Dictionary LocalizedModules } } } - + return this._localizedModules; } } - [XmlElement("localizedVersionGuid")] - public Guid LocalizedVersionGuid - { - get - { - return this._localizedVersionGuid; - } - - set - { - this._localizedVersionGuid = value; - } - } - public TabInfo ParentTab { get @@ -510,39 +305,244 @@ public TabInfo ParentTab this._parentTab = TabController.Instance.GetTabByCulture(this.TabID, this.PortalID, locale); } } - + return this._parentTab; } - } - + } + + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + + [XmlElement("alignment")] + public string Alignment { get; set; } + + [XmlIgnore] + public bool AllModules { get; set; } + + [XmlElement("alltabs")] + public bool AllTabs { get; set; } + + [XmlElement("border")] + public string Border { get; set; } + + [XmlElement("cachemethod")] + public string CacheMethod { get; set; } + + [XmlElement("cachetime")] + public int CacheTime { get; set; } + + [XmlElement("color")] + public string Color { get; set; } + + [XmlIgnore] + public string ContainerPath { get; set; } + + [XmlElement("containersrc")] + public string ContainerSrc { get; set; } + /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the Key ID. + /// Gets or sets and sets the ID of the Associated Desktop Module. /// /// An Integer. /// ----------------------------------------------------------------------------- [XmlIgnore] - public override int KeyID + public int DesktopModuleID { get; set; } + + [XmlElement("displayprint")] + public bool DisplayPrint { get; set; } + + [XmlElement("displaysyndicate")] + public bool DisplaySyndicate { get; set; } + + [XmlElement("displaytitle")] + public bool DisplayTitle { get; set; } + + [XmlElement("enddate")] + public DateTime EndDate { get; set; } + + [XmlElement("footer")] + public string Footer { get; set; } + + [XmlElement("header")] + public string Header { get; set; } + + [XmlElement("iconfile")] + public string IconFile { get; set; } + + [XmlElement("inheritviewpermissions")] + public bool InheritViewPermissions { get; set; } + + [XmlIgnore] + public bool IsDefaultModule { get; set; } + + [XmlElement("isdeleted")] + public bool IsDeleted { get; set; } + + [XmlIgnore] + public bool IsShareable { get; set; } + + [XmlIgnore] + public bool IsShareableViewOnly { get; set; } + + [XmlElement("iswebslice")] + public bool IsWebSlice { get; set; } + + [XmlIgnore] + public DateTime LastContentModifiedOnDate { get; set; } + + [XmlIgnore] + public int ModuleControlId { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the ID of the Associated Module Definition. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public int ModuleDefID { get; set; } + + [XmlElement("moduleorder")] + public int ModuleOrder { get; set; } + + /// + /// Gets or sets get the ModulePermissions for the Module DO NOT USE THE SETTTER. + /// + /// Since 5.0 the setter has been obsolete, directly setting the ModulePermissionCollection is likely an error, change the contenst of the collection instead. + /// The setter still exists to preserve binary compatibility without the obsolete attribute since c# will not allow only a setter to be obsolete. + /// + /// + [XmlArray("modulepermissions")] + [XmlArrayItem("permission")] + public ModulePermissionCollection ModulePermissions { get { - return this.ModuleID; + return this._modulePermissions ?? + (this._modulePermissions = this.ModuleID > 0 + ? new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabID)) + : new ModulePermissionCollection()); } - + set { - this.ModuleID = value; + this._modulePermissions = value; } - } + } - public CacheLevel Cacheability + [XmlElement("title")] + public string ModuleTitle { get; set; } + + [XmlIgnore] + public int ModuleVersion { get; set; } + + [XmlIgnore] + public int OwnerPortalID { get; set; } + + [XmlIgnore] + public int PaneModuleCount { get; set; } + + [XmlIgnore] + public int PaneModuleIndex { get; set; } + + [XmlElement("panename")] + public string PaneName { get; set; } + + [XmlElement("portalid")] + public int PortalID { get; set; } + + [XmlElement("startdate")] + public DateTime StartDate { get; set; } + + [XmlElement("tabmoduleid")] + public int TabModuleID { get; set; } + + [XmlElement("uniqueId")] + public Guid UniqueId { get; set; } + + [XmlElement("versionGuid")] + public Guid VersionGuid { get; set; } + + [XmlElement("visibility")] + public VisibilityState Visibility { get; set; } + + [XmlElement("websliceexpirydate")] + public DateTime WebSliceExpiryDate { get; set; } + + [XmlElement("webslicetitle")] + public string WebSliceTitle { get; set; } + + [XmlElement("webslicettl")] + public int WebSliceTTL { get; set; } + + [XmlElement("cultureCode")] + public string CultureCode { get { - return CacheLevel.fullyCacheable; + return this._cultureCode; } - } - + + set + { + this._cultureCode = value; + } + } + + [XmlElement("defaultLanguageGuid")] + public Guid DefaultLanguageGuid + { + get + { + return this._defaultLanguageGuid; + } + + set + { + this._defaultLanguageGuid = value; + } + } + + [XmlElement("localizedVersionGuid")] + public Guid LocalizedVersionGuid + { + get + { + return this._localizedVersionGuid; + } + + set + { + this._localizedVersionGuid = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Key ID. + /// + /// An Integer. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public override int KeyID + { + get + { + return this.ModuleID; + } + + set + { + this.ModuleID = value; + } + } + /// ----------------------------------------------------------------------------- /// /// Fills a ModuleInfo from a Data Reader. @@ -618,7 +618,7 @@ public override void Fill(IDataReader dr) break; } } - + this.ContainerSrc = Null.SetNullString(dr["ContainerSrc"]); this.DisplayTitle = Null.SetNullBoolean(dr["DisplayTitle"]); this.DisplayPrint = Null.SetNullBoolean(dr["DisplayPrint"]); @@ -630,7 +630,7 @@ public override void Fill(IDataReader dr) this.WebSliceExpiryDate = Null.SetNullDateTime(dr["WebSliceExpiryDate"]); this.WebSliceTTL = Null.SetNullInteger(dr["WebSliceTTL"]); } - + this.DesktopModuleID = Null.SetNullInteger(dr["DesktopModuleID"]); this.ModuleControlId = Null.SetNullInteger(dr["ModuleControlID"]); } @@ -639,7 +639,7 @@ public override void Fill(IDataReader dr) Logger.Error(exc); } } - + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -647,13 +647,13 @@ public string GetProperty(string propertyName, string format, CultureInfo format { outputFormat = "g"; } - + if (currentScope == Scope.NoSettings) { propertyNotFound = true; return PropertyAccess.ContentLocked; } - + propertyNotFound = true; string result = string.Empty; bool isPublic = true; @@ -943,65 +943,65 @@ public string GetProperty(string propertyName, string format, CultureInfo format result = PropertyAccess.FormatString(this.DesktopModule.HostPage, format); break; } - + if (!isPublic && currentScope != Scope.Debug) { propertyNotFound = true; result = PropertyAccess.ContentLocked; } - + return result; } - + 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 @@ -1025,12 +1025,12 @@ public string GetEffectiveCacheMethod() var defaultModuleCache = ComponentFactory.GetComponent(); effectiveCacheMethod = (from provider in ModuleCachingProvider.GetProviderList() where provider.Value.Equals(defaultModuleCache) select provider.Key).SingleOrDefault(); } - + if (string.IsNullOrEmpty(effectiveCacheMethod)) { throw new InvalidOperationException(Localization.GetString("EXCEPTION_ModuleCacheMissing")); } - + return effectiveCacheMethod; } diff --git a/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs b/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs index 1e4a98cda04..3c8dc693433 100644 --- a/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs +++ b/DNN Platform/Library/Entities/Modules/ModuleSettingsBase.cs @@ -26,14 +26,14 @@ public Hashtable TabModuleSettings { return this.ModuleContext.Configuration.TabModuleSettings; } - } - + } + public virtual void LoadSettings() { } public virtual void UpdateSettings() { - } + } } } diff --git a/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs b/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs index 623973496ea..f53b478ee95 100644 --- a/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs +++ b/DNN Platform/Library/Entities/Modules/PortalDesktopModuleInfo.cs @@ -15,9 +15,6 @@ public class PortalDesktopModuleInfo : BaseEntityInfo private DesktopModuleInfo _desktopModule; private DesktopModulePermissionCollection _permissions; - [XmlIgnore] - public int PortalDesktopModuleID { get; set; } - [XmlIgnore] public DesktopModuleInfo DesktopModule { @@ -27,15 +24,10 @@ public DesktopModuleInfo DesktopModule { this._desktopModule = this.DesktopModuleID > Null.NullInteger ? DesktopModuleController.GetDesktopModule(this.DesktopModuleID, this.PortalID) : new DesktopModuleInfo(); } - + return this._desktopModule; } } - - [XmlIgnore] - public int DesktopModuleID { get; set; } - - public string FriendlyName { get; set; } public DesktopModulePermissionCollection Permissions { @@ -45,11 +37,19 @@ public DesktopModulePermissionCollection Permissions { this._permissions = new DesktopModulePermissionCollection(DesktopModulePermissionController.GetDesktopModulePermissions(this.PortalDesktopModuleID)); } - + return this._permissions; } } + [XmlIgnore] + public int PortalDesktopModuleID { get; set; } + + [XmlIgnore] + public int DesktopModuleID { get; set; } + + public string FriendlyName { get; set; } + [XmlIgnore] public int PortalID { get; set; } diff --git a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs index 05e5eac65d7..ed0830264f2 100644 --- a/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/PortalModuleBase.cs @@ -50,22 +50,7 @@ public PortalModuleBase() this.DependencyProvider = Globals.DependencyProvider; } - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ModuleActionCollection Actions - { - get - { - return this.ModuleContext.Actions; - } - - set - { - this.ModuleContext.Actions = value; - } - } - - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Control ContainerControl { @@ -75,15 +60,6 @@ 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 @@ -101,20 +77,7 @@ public bool EditMode } } - public string HelpURL - { - get - { - return this.ModuleContext.HelpURL; - } - - set - { - this.ModuleContext.HelpURL = value; - } - } - - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsEditable { @@ -124,22 +87,7 @@ public bool IsEditable } } - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ModuleInfo ModuleConfiguration - { - get - { - return this.ModuleContext.Configuration; - } - - set - { - this.ModuleContext.Configuration = value; - } - } - - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int PortalId { @@ -149,7 +97,7 @@ public int PortalId } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int TabId { @@ -159,37 +107,7 @@ public int TabId } } - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public int TabModuleId - { - get - { - return this.ModuleContext.TabModuleId; - } - - set - { - this.ModuleContext.TabModuleId = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public int ModuleId - { - get - { - return this.ModuleContext.ModuleId; - } - - set - { - this.ModuleContext.ModuleId = value; - } - } - - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UserInfo UserInfo { @@ -199,7 +117,7 @@ public UserInfo UserInfo } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int UserId { @@ -209,7 +127,7 @@ public int UserId } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalAliasInfo PortalAlias { @@ -219,7 +137,7 @@ public PortalAliasInfo PortalAlias } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Hashtable Settings { @@ -227,8 +145,8 @@ public Hashtable Settings { return this.ModuleContext.Settings; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the underlying base control for this ModuleControl. @@ -271,35 +189,6 @@ public string ControlName } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the local resource file for this control. - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string LocalResourceFile - { - get - { - string fileRoot; - if (string.IsNullOrEmpty(this._localResourceFile)) - { - fileRoot = Path.Combine(this.ControlPath, Localization.LocalResourceDirectory + "/" + this.ID); - } - else - { - fileRoot = this._localResourceFile; - } - - return fileRoot; - } - - set - { - this._localResourceFile = value; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the Module Context for this control. @@ -314,13 +203,13 @@ public ModuleInstanceContext ModuleContext { this._moduleContext = new ModuleInstanceContext(this); } - + return this._moduleContext; } - } - - // CONVERSION: Remove obsoleted methods (FYI some core modules use these, such as Links) - + } + + // 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" @@ -370,80 +259,215 @@ public string CacheKey } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string EditUrl() + public ModuleActionCollection Actions { - return this.ModuleContext.EditUrl(); + get + { + return this.ModuleContext.Actions; + } + + set + { + this.ModuleContext.Actions = value; + } + } + + public string HelpURL + { + get + { + return this.ModuleContext.HelpURL; + } + + set + { + this.ModuleContext.HelpURL = value; + } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string EditUrl(string ControlKey) + public ModuleInfo ModuleConfiguration { - return this.ModuleContext.EditUrl(ControlKey); + get + { + return this.ModuleContext.Configuration; + } + + set + { + this.ModuleContext.Configuration = value; + } } - - protected override void OnInit(EventArgs e) + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int TabModuleId { - if (this._tracelLogger.IsDebugEnabled) - { - this._tracelLogger.Debug($"PortalModuleBase.OnInit Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); - } - - base.OnInit(e); - if (this._tracelLogger.IsDebugEnabled) - { - this._tracelLogger.Debug($"PortalModuleBase.OnInit End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); - } + get + { + return this.ModuleContext.TabModuleId; + } + + set + { + this.ModuleContext.TabModuleId = value; + } } - - protected override void OnLoad(EventArgs e) + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public int ModuleId { - if (this._tracelLogger.IsDebugEnabled) - { - this._tracelLogger.Debug($"PortalModuleBase.OnLoad Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); - } - - base.OnLoad(e); - if (this._tracelLogger.IsDebugEnabled) - { - this._tracelLogger.Debug($"PortalModuleBase.OnLoad End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); - } + get + { + return this.ModuleContext.ModuleId; + } + + set + { + this.ModuleContext.ModuleId = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the local resource file for this control. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string LocalResourceFile + { + get + { + string fileRoot; + if (string.IsNullOrEmpty(this._localResourceFile)) + { + fileRoot = Path.Combine(this.ControlPath, Localization.LocalResourceDirectory + "/" + this.ID); + } + else + { + fileRoot = this._localResourceFile; + } + + return fileRoot; + } + + set + { + this._localResourceFile = value; + } + } + + /// + /// Gets the Dependency Provider to resolve registered + /// services with the container. + /// + /// + /// The Dependency Service. + /// + protected IServiceProvider DependencyProvider { get; } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string EditUrl() + { + return this.ModuleContext.EditUrl(); } - [Browsable(false)] + [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) { return this.ModuleContext.EditUrl(KeyName, KeyValue); } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue, string ControlKey) { return this.ModuleContext.EditUrl(KeyName, KeyValue, ControlKey); } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(string KeyName, string KeyValue, string ControlKey, params string[] AdditionalParameters) { return this.ModuleContext.EditUrl(KeyName, KeyValue, ControlKey, AdditionalParameters); } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string EditUrl(int TabID, string ControlKey, bool PageRedirect, params string[] AdditionalParameters) { return this.ModuleContext.NavigateUrl(TabID, ControlKey, PageRedirect, AdditionalParameters); } - + public int GetNextActionID() { return this.ModuleContext.GetNextActionID(); - } + } + + [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] + public string GetCacheFileName(int tabModuleId) + { + string strCacheKey = "TabModule:"; + strCacheKey += 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 GetCacheKey(int tabModuleId) + { + string strCacheKey = "TabModule:"; + strCacheKey += tabModuleId + ":"; + strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); + return strCacheKey; + } + + [Obsolete("This method is deprecated. Plaese use ModuleController.SynchronizeModule(ModuleId). Scheduled removal in v11.0.0.")] + public void SynchronizeModule() + { + ModuleController.SynchronizeModule(this.ModuleId); + } + + protected override void OnInit(EventArgs e) + { + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnInit Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + + base.OnInit(e); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnInit End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + } + + protected override void OnLoad(EventArgs e) + { + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnLoad Start (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + + base.OnLoad(e); + if (this._tracelLogger.IsDebugEnabled) + { + this._tracelLogger.Debug($"PortalModuleBase.OnLoad End (TabId:{this.PortalSettings.ActiveTab.TabID},ModuleId:{this.ModuleId}): {this.GetType()}"); + } + } /// ----------------------------------------------------------------------------- /// @@ -471,29 +495,5 @@ protected string LocalizeSafeJsString(string key) { return Localization.GetSafeJSString(key, this.LocalResourceFile); } - - [Obsolete("This property is deprecated. Please use ModuleController.CacheFileName(TabModuleID). Scheduled removal in v11.0.0.")] - public string GetCacheFileName(int tabModuleId) - { - string strCacheKey = "TabModule:"; - strCacheKey += 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 GetCacheKey(int tabModuleId) - { - string strCacheKey = "TabModule:"; - strCacheKey += tabModuleId + ":"; - strCacheKey += Thread.CurrentThread.CurrentUICulture.ToString(); - return strCacheKey; - } - - [Obsolete("This method is deprecated. Plaese use ModuleController.SynchronizeModule(ModuleId). Scheduled removal in v11.0.0.")] - public void SynchronizeModule() - { - ModuleController.SynchronizeModule(this.ModuleId); - } } } diff --git a/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs b/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs index 4a353dce7d3..53619f03acb 100644 --- a/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/ProfileUserControlBase.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Entities.Modules public class ProfileUserControlBase : UserModuleBase { public event EventHandler ProfileUpdated; - + public event EventHandler ProfileUpdateCompleted; /// ----------------------------------------------------------------------------- diff --git a/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs b/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs index 640b2153c19..994df7093ea 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ISettingsRepository.cs @@ -8,7 +8,7 @@ public interface ISettingsRepository where T : class { T GetSettings(ModuleInfo moduleContext); - + void SaveSettings(ModuleInfo moduleContext, T settings); } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs index aac1d7d9175..7c5b24cfc35 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ModuleSettingAttribute.cs @@ -12,6 +12,5 @@ namespace DotNetNuke.Entities.Modules.Settings [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] [Serializable] public class ModuleSettingAttribute : ParameterAttributeBase - { - } + {} } diff --git a/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs b/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs index 58ac981c7ce..63e57833eca 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/ParameterMapping.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Modules.Settings [Serializable] public class ParameterMapping - { + { /// /// Initializes a new instance of the class. /// @@ -36,12 +36,12 @@ public ParameterMapping(ParameterAttributeBase attribute, PropertyInfo property) } this.FullParameterName = parameterName; - } - + } + public ParameterAttributeBase Attribute { get; set; } public string FullParameterName { get; set; } - public PropertyInfo Property { get; set; } + public PropertyInfo Property { get; set; } } } diff --git a/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs index ccdda747885..b6f4af02d0f 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/PortalSettingAttribute.cs @@ -11,6 +11,5 @@ namespace DotNetNuke.Entities.Modules.Settings /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class PortalSettingAttribute : ParameterAttributeBase - { - } + {} } diff --git a/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs b/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs index 9640a1de105..fdd16699a79 100644 --- a/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs +++ b/DNN Platform/Library/Entities/Modules/Settings/TabModuleSettingAttribute.cs @@ -11,6 +11,5 @@ namespace DotNetNuke.Entities.Modules.Settings /// [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class TabModuleSettingAttribute : ParameterAttributeBase - { - } + {} } diff --git a/DNN Platform/Library/Entities/Modules/SkinControlController.cs b/DNN Platform/Library/Entities/Modules/SkinControlController.cs index 6dfb050fbcc..3d416b32512 100644 --- a/DNN Platform/Library/Entities/Modules/SkinControlController.cs +++ b/DNN Platform/Library/Entities/Modules/SkinControlController.cs @@ -40,7 +40,7 @@ public static void DeleteSkinControl(SkinControlInfo skinControl) /// /// GetSkinControl gets a single Skin Control from the database. /// - /// The ID of the SkinControl. + /// The ID of the SkinControl. /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControl(int skinControlID) @@ -52,7 +52,7 @@ public static SkinControlInfo GetSkinControl(int skinControlID) /// /// GetSkinControlByPackageID gets a single Skin Control from the database. /// - /// The ID of the Package. + /// The ID of the Package. /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControlByPackageID(int packageID) @@ -64,7 +64,7 @@ public static SkinControlInfo GetSkinControlByPackageID(int packageID) /// /// GetSkinControlByKey gets a single Skin Control from the database. /// - /// The key of the Control. + /// The key of the Control. /// /// ----------------------------------------------------------------------------- public static SkinControlInfo GetSkinControlByKey(string key) @@ -75,7 +75,7 @@ public static SkinControlInfo GetSkinControlByKey(string key) /// ----------------------------------------------------------------------------- /// /// GetSkinControls gets all the Skin Controls from the database. - /// + /// /// /// ----------------------------------------------------------------------------- public static Dictionary GetSkinControls() @@ -87,7 +87,7 @@ public static Dictionary GetSkinControls() /// /// SaveSkinControl updates a Skin Control in the database. /// - /// The Skin Control to save. + /// The Skin Control to save. /// /// ----------------------------------------------------------------------------- public static int SaveSkinControl(SkinControlInfo skinControl) @@ -96,7 +96,7 @@ public static int SaveSkinControl(SkinControlInfo skinControl) if (skinControlID == Null.NullInteger) { // Add new Skin Control - skinControlID = dataProvider.AddSkinControl( + skinControlID = dataProvider.AddSkinControl( skinControl.PackageID, skinControl.ControlKey, skinControl.ControlSrc, @@ -107,7 +107,7 @@ public static int SaveSkinControl(SkinControlInfo skinControl) else { // Upgrade Skin Control - dataProvider.UpdateSkinControl( + dataProvider.UpdateSkinControl( skinControl.SkinControlID, skinControl.PackageID, skinControl.ControlKey, @@ -116,7 +116,7 @@ public static int SaveSkinControl(SkinControlInfo skinControl) UserController.Instance.GetCurrentUserInfo().UserID); EventLogController.Instance.AddLog(skinControl, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.SKINCONTROL_UPDATED); } - + return skinControlID; } } diff --git a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs index 3911d5f537e..f08964702cf 100644 --- a/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs +++ b/DNN Platform/Library/Entities/Modules/SkinControlInfo.cs @@ -43,7 +43,7 @@ public SkinControlInfo() /// /// An Integer. /// ----------------------------------------------------------------------------- - public int PackageID { get; set; } + public int PackageID { get; set; } /// ----------------------------------------------------------------------------- /// @@ -57,13 +57,13 @@ public int KeyID { return this.SkinControlID; } - + set { this.SkinControlID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a SkinControlInfo from a Data Reader. @@ -76,11 +76,11 @@ public void Fill(IDataReader dr) this.PackageID = Null.SetNullInteger(dr["PackageID"]); this.FillInternal(dr); } - + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the SkinControlInfo. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -102,12 +102,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + this.ReadXmlInternal(reader); } } @@ -128,6 +128,6 @@ public void WriteXml(XmlWriter writer) // Write end of main element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs index bfc0c6d5947..1366776bdb4 100644 --- a/DNN Platform/Library/Entities/Modules/UserModuleBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserModuleBase.cs @@ -58,7 +58,7 @@ public UserInfo User { return this._User ?? (this._User = this.AddUser ? this.InitialiseUser() : UserController.GetUserById(this.UserPortalID, this.UserId)); } - + set { this._User = value; @@ -82,7 +82,7 @@ public UserInfo User 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; @@ -92,10 +92,10 @@ public UserInfo User { _UserId = Convert.ToInt32(this.ViewState["UserId"]); } - + return _UserId; } - + set { this.ViewState["UserId"] = value; @@ -127,8 +127,8 @@ protected bool IsAdmin /// /// Gets a value indicating whether gets whether this is the current user or admin. /// - /// - /// gets whether this is the current user or admin + /// + /// gets whether this is the current user or admin /// /// /// @@ -167,7 +167,7 @@ protected bool IsEdit _IsEdit = true; } } - + return _IsEdit; } } @@ -203,7 +203,7 @@ protected bool IsProfile } } } - + return _IsProfile; } } @@ -245,7 +245,7 @@ protected int UserPortalID /// Gets a Setting for the Module. /// /// - /// + /// /// public static object GetSetting(int portalId, string settingKey) { @@ -254,7 +254,7 @@ public static object GetSetting(int portalId, string settingKey) { settings = UserController.GetUserSettings(portalId, settings); } - + return settings[settingKey]; } @@ -311,6 +311,77 @@ protected void AddModuleMessage(string message, ModuleMessage.ModuleMessageType this.AddLocalizedModuleMessage(Localization.GetString(message, this.LocalResourceFile), type, display); } + protected string CompleteUserCreation(UserCreateStatus createStatus, UserInfo newUser, bool notify, bool register) + { + var strMessage = string.Empty; + var message = ModuleMessage.ModuleMessageType.RedError; + if (register) + { + // send notification to portal administrator of new user registration + // check the receive notification setting first, but if register type is Private, we will always send the notification email. + // because the user need administrators to do the approve action so that he can continue use the website. + if (this.PortalSettings.EnableRegisterNotification || this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration) + { + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, this.PortalSettings); + this.SendAdminNotification(newUser, this.PortalSettings); + } + + var loginStatus = UserLoginStatus.LOGIN_FAILURE; + + // complete registration + switch (this.PortalSettings.UserRegistration) + { + case (int)Globals.PortalRegistrationType.PrivateRegistration: + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPrivate, this.PortalSettings); + + // show a message that a portal administrator has to verify the user credentials + if (string.IsNullOrEmpty(strMessage)) + { + strMessage += Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile); + message = ModuleMessage.ModuleMessageType.GreenSuccess; + } + + break; + case (int)Globals.PortalRegistrationType.PublicRegistration: + Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); + UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); + break; + case (int)Globals.PortalRegistrationType.VerifiedRegistration: + Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); + UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); + break; + } + + // store preferredlocale in cookie + Localization.SetLanguage(newUser.Profile.PreferredLocale); + if (this.IsRegister && message == ModuleMessage.ModuleMessageType.RedError) + { + this.AddLocalizedModuleMessage(string.Format(Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, !string.IsNullOrEmpty(strMessage)); + } + else + { + this.AddLocalizedModuleMessage(strMessage, message, !string.IsNullOrEmpty(strMessage)); + } + } + else + { + if (notify) + { + // Send Notification to User + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) + { + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); + } + else + { + strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); + } + } + } + + return strMessage; + } + /// /// InitialiseUser initialises a "new" user. /// @@ -348,14 +419,14 @@ private UserInfo InitialiseUser() newUser.Profile.Country = country; } - + // Set AffiliateId int AffiliateId = Null.NullInteger; if (this.Request.Cookies["AffiliateId"] != null) { AffiliateId = int.Parse(this.Request.Cookies["AffiliateId"].Value); } - + newUser.AffiliateID = AffiliateId; return newUser; } @@ -371,7 +442,7 @@ private string LookupCountry() { // 'The country cannot be detected because the user is local. IsLocal = true; - + // Set the IP address in case they didn't specify LocalhostCountryCode IP = this.Page.Request.UserHostAddress; } @@ -380,7 +451,7 @@ private string LookupCountry() // Set the IP address so we can find the country IP = this.Page.Request.UserHostAddress; } - + // Check to see if we need to generate the Cache for the GeoIPData file if (this.Context.Cache.Get("GeoIPData") == null && _CacheGeoIPData) { @@ -411,7 +482,7 @@ private string LookupCountry() // No, get it from file _CountryLookup = new CountryLookup(this.Context.Server.MapPath(_GeoIPFile)); } - + // Get the country code based on the IP address string country = Null.NullString; try @@ -422,81 +493,10 @@ private string LookupCountry() { Exceptions.LogException(ex); } - + return country; } - protected string CompleteUserCreation(UserCreateStatus createStatus, UserInfo newUser, bool notify, bool register) - { - var strMessage = string.Empty; - var message = ModuleMessage.ModuleMessageType.RedError; - if (register) - { - // send notification to portal administrator of new user registration - // check the receive notification setting first, but if register type is Private, we will always send the notification email. - // because the user need administrators to do the approve action so that he can continue use the website. - if (this.PortalSettings.EnableRegisterNotification || this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.PrivateRegistration) - { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationAdmin, this.PortalSettings); - this.SendAdminNotification(newUser, this.PortalSettings); - } - - var loginStatus = UserLoginStatus.LOGIN_FAILURE; - - // complete registration - switch (this.PortalSettings.UserRegistration) - { - case (int)Globals.PortalRegistrationType.PrivateRegistration: - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPrivate, this.PortalSettings); - - // show a message that a portal administrator has to verify the user credentials - if (string.IsNullOrEmpty(strMessage)) - { - strMessage += Localization.GetString("PrivateConfirmationMessage", Localization.SharedResourceFile); - message = ModuleMessage.ModuleMessageType.GreenSuccess; - } - - break; - case (int)Globals.PortalRegistrationType.PublicRegistration: - Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); - UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); - break; - case (int)Globals.PortalRegistrationType.VerifiedRegistration: - Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); - UserController.UserLogin(this.PortalSettings.PortalId, newUser.Username, newUser.Membership.Password, string.Empty, this.PortalSettings.PortalName, string.Empty, ref loginStatus, false); - break; - } - - // store preferredlocale in cookie - Localization.SetLanguage(newUser.Profile.PreferredLocale); - if (this.IsRegister && message == ModuleMessage.ModuleMessageType.RedError) - { - this.AddLocalizedModuleMessage(string.Format(Localization.GetString("SendMail.Error", Localization.SharedResourceFile), strMessage), message, !string.IsNullOrEmpty(strMessage)); - } - else - { - this.AddLocalizedModuleMessage(strMessage, message, !string.IsNullOrEmpty(strMessage)); - } - } - else - { - if (notify) - { - // Send Notification to User - if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) - { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationVerified, this.PortalSettings); - } - else - { - strMessage += Mail.SendMail(newUser, MessageType.UserRegistrationPublic, this.PortalSettings); - } - } - } - - return strMessage; - } - private void SendAdminNotification(UserInfo newUser, PortalSettings portalSettings) { var notificationType = newUser.Membership.Approved ? "NewUserRegistration" : "NewUnauthorizedUserRegistration"; @@ -531,6 +531,6 @@ private string GetNotificationSubject(string locale, UserInfo newUser, PortalSet { const string text = "EMAIL_USER_REGISTRATION_ADMINISTRATOR_SUBJECT"; return this.LocalizeNotificationText(text, locale, newUser, portalSettings); - } + } } } diff --git a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs index 7265adeccfb..ea522cf3528 100644 --- a/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs +++ b/DNN Platform/Library/Entities/Modules/UserUserControlBase.cs @@ -20,41 +20,41 @@ namespace DotNetNuke.Entities.Modules /// /// ----------------------------------------------------------------------------- public class UserUserControlBase : UserModuleBase - { + { public delegate void UserCreatedEventHandler(object sender, UserCreatedEventArgs e); - + public delegate void UserDeletedEventHandler(object sender, UserDeletedEventArgs e); - + public delegate void UserRestoredEventHandler(object sender, UserRestoredEventArgs e); - + public delegate void UserRemovedEventHandler(object sender, UserRemovedEventArgs e); - - public delegate void UserUpdateErrorEventHandler(object sender, UserUpdateErrorArgs e); - + + public delegate void UserUpdateErrorEventHandler(object sender, UserUpdateErrorArgs e); + public event UserCreatedEventHandler UserCreated; - + public event UserCreatedEventHandler UserCreateCompleted; - + public event UserDeletedEventHandler UserDeleted; - + public event UserUpdateErrorEventHandler UserDeleteError; - + public event UserRestoredEventHandler UserRestored; - + public event UserUpdateErrorEventHandler UserRestoreError; - + public event UserRemovedEventHandler UserRemoved; - + public event UserUpdateErrorEventHandler UserRemoveError; - + public event EventHandler UserUpdated; - + public event EventHandler UserUpdateCompleted; - - public event UserUpdateErrorEventHandler UserUpdateError; - - protected override bool AddUser => !this.Request.IsAuthenticated || base.AddUser; - + + public event UserUpdateErrorEventHandler UserUpdateError; + + protected override bool AddUser => !this.Request.IsAuthenticated || base.AddUser; + /// ----------------------------------------------------------------------------- /// /// Raises the UserCreateCompleted Event. @@ -176,8 +176,8 @@ public void OnUserUpdateError(UserUpdateErrorArgs e) { this.UserUpdateError(this, e); } - } - + } + /// ----------------------------------------------------------------------------- /// /// The BaseUserEventArgs class provides a base for User EventArgs classes. @@ -198,8 +198,8 @@ public class BaseUserEventArgs /// /// ----------------------------------------------------------------------------- public string UserName { get; set; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The UserCreatedEventArgs class provides a customised EventArgs class for @@ -208,10 +208,10 @@ public class BaseUserEventArgs /// ----------------------------------------------------------------------------- public class UserCreatedEventArgs { - private UserCreateStatus _createStatus = UserCreateStatus.Success; - + private UserCreateStatus _createStatus = UserCreateStatus.Success; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new UserCreatedEventArgs. /// @@ -233,7 +233,7 @@ public UserCreateStatus CreateStatus { return this._createStatus; } - + set { this._createStatus = value; @@ -253,8 +253,8 @@ public UserCreateStatus CreateStatus /// /// ----------------------------------------------------------------------------- public bool Notify { get; set; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The UserDeletedEventArgs class provides a customised EventArgs class for @@ -262,9 +262,9 @@ public UserCreateStatus CreateStatus /// /// ----------------------------------------------------------------------------- public class UserDeletedEventArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new UserDeletedEventArgs. /// @@ -276,8 +276,8 @@ public UserDeletedEventArgs(int id, string name) this.UserId = id; this.UserName = name; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The UserRestoredEventArgs class provides a customised EventArgs class for @@ -285,9 +285,9 @@ public UserDeletedEventArgs(int id, string name) /// /// ----------------------------------------------------------------------------- public class UserRestoredEventArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new UserRestoredEventArgs. /// @@ -299,8 +299,8 @@ public UserRestoredEventArgs(int id, string name) this.UserId = id; this.UserName = name; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The UserRemovedEventArgs class provides a customised EventArgs class for @@ -308,9 +308,9 @@ public UserRestoredEventArgs(int id, string name) /// /// ----------------------------------------------------------------------------- public class UserRemovedEventArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new UserRemovedEventArgs. /// @@ -322,8 +322,8 @@ public UserRemovedEventArgs(int id, string name) this.UserId = id; this.UserName = name; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The UserUpdateErrorArgs class provides a customised EventArgs class for @@ -331,9 +331,9 @@ public UserRemovedEventArgs(int id, string name) /// /// ----------------------------------------------------------------------------- public class UserUpdateErrorArgs : BaseUserEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new UserUpdateErrorArgs. /// @@ -354,6 +354,6 @@ public UserUpdateErrorArgs(int id, string name, string message) /// /// ----------------------------------------------------------------------------- public string Message { get; set; } - } + } } } diff --git a/DNN Platform/Library/Entities/Portals/Data/DataService.cs b/DNN Platform/Library/Entities/Portals/Data/DataService.cs index 5084175e0fe..0e0ee58b818 100644 --- a/DNN Platform/Library/Entities/Portals/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Portals/Data/DataService.cs @@ -14,7 +14,7 @@ public class DataService : ComponentBase, IDataServic public int AddPortalGroup(PortalGroupInfo portalGroup, int createdByUserId) { - return this._provider.ExecuteScalar( + return this._provider.ExecuteScalar( "AddPortalGroup", portalGroup.PortalGroupName, portalGroup.PortalGroupDescription, @@ -35,7 +35,7 @@ public IDataReader GetPortalGroups() public void UpdatePortalGroup(PortalGroupInfo portalGroup, int lastModifiedByUserId) { - this._provider.ExecuteNonQuery( + this._provider.ExecuteNonQuery( "UpdatePortalGroup", portalGroup.PortalGroupId, portalGroup.PortalGroupName, diff --git a/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs index 5349061bbd7..677167ceb05 100644 --- a/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Internal/IPortalTemplateIO.cs @@ -11,13 +11,13 @@ namespace DotNetNuke.Entities.Portals.Internal public interface IPortalTemplateIO { IEnumerable EnumerateTemplates(); - + IEnumerable EnumerateLanguageFiles(); - + string GetResourceFilePath(string templateFilePath); - + string GetLanguageFilePath(string templateFilePath, string cultureCode); - + TextReader OpenTextReader(string filePath); } } diff --git a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs index 64c02e67441..c881a7985ce 100644 --- a/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs +++ b/DNN Platform/Library/Entities/Portals/Internal/PortalTemplateIO.cs @@ -36,11 +36,6 @@ public IEnumerable EnumerateLanguageFiles() return new string[0]; } - - protected override Func GetFactory() - { - return () => new PortalTemplateIO(); - } public string GetResourceFilePath(string templateFilePath) { @@ -64,9 +59,14 @@ public TextReader OpenTextReader(string filePath) return reader; } + protected override Func GetFactory() + { + return () => new PortalTemplateIO(); + } + private static string CheckFilePath(string path) { return File.Exists(path) ? path : string.Empty; - } + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs index d16205619d6..74173de8aae 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasCollection.cs @@ -35,7 +35,7 @@ public ICollection Values return this.Dictionary.Values; } } - + /// /// Gets or sets the value associated with the specified key. /// @@ -45,7 +45,7 @@ public PortalAliasInfo this[string key] { return (PortalAliasInfo)this.Dictionary[key]; } - + set { this.Dictionary[key] = value; diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs index 10605964014..7c18ed79823 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasController.cs @@ -67,7 +67,7 @@ public static string GetPortalAliasByPortal(int portalId, string portalAlias) 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) { @@ -76,7 +76,7 @@ public static string GetPortalAliasByPortal(int portalId, string portalAlias) } } } - + return retValue; } @@ -101,7 +101,7 @@ public static string GetPortalAliasByTab(int tabId, string portalAlias) intPortalId = tab.PortalID; } } - + switch (intPortalId) { case -2: // tab does not exist @@ -114,15 +114,38 @@ public static string GetPortalAliasByTab(int tabId, string portalAlias) retValue = GetPortalAliasByPortal(intPortalId, portalAlias); break; } - + return retValue; } - + + /// + /// Validates the alias. + /// + /// The portal alias. + /// if set to true [ischild]. + /// true if the alias is a valid url format; otherwise return false. + public static bool ValidateAlias(string portalAlias, bool ischild) + { + if (ischild) + { + return ValidateAlias(portalAlias, true, false); + } + + // validate the domain + Uri result; + if (Uri.TryCreate(Globals.AddHTTP(portalAlias), UriKind.Absolute, out result)) + { + return ValidateAlias(result.Host, false, true) && ValidateAlias(portalAlias, false, false); + } + + return false; + } + public int AddPortalAlias(PortalAliasInfo portalAlias) { // Add Alias var dataProvider = DataProvider.Instance(); - int Id = dataProvider.AddPortalAlias( + int Id = dataProvider.AddPortalAlias( portalAlias.PortalID, portalAlias.HTTPAlias.ToLowerInvariant().Trim('/'), portalAlias.CultureCode, @@ -151,12 +174,101 @@ public void DeletePortalAlias(PortalAliasInfo portalAlias) // clear portal alias cache ClearCache(false, portalAlias.PortalID); } - + + public PortalAliasInfo GetPortalAlias(string alias) + { + return this.GetPortalAliasInternal(alias); + } + + /// + /// Gets the portal alias. + /// + /// The portal alias. + /// The portal ID. + /// Portal Alias Info. + public PortalAliasInfo GetPortalAlias(string alias, int portalId) + { + return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key.Equals(alias, StringComparison.InvariantCultureIgnoreCase) && pa.Value.PortalID == portalId).Value; + } + + /// + /// Gets the portal alias by portal alias ID. + /// + /// The portal alias ID. + /// Portal alias info. + 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(); + } + + /// + /// Gets the portal by portal alias ID. + /// + /// The portal alias id. + /// Portal info. + public PortalInfo GetPortalByPortalAliasID(int PortalAliasId) + { + return CBO.FillObject(DataProvider.Instance().GetPortalByPortalAliasID(PortalAliasId)); + } + + public void UpdatePortalAlias(PortalAliasInfo portalAlias) + { + // Update Alias + DataProvider.Instance().UpdatePortalAliasInfo( + portalAlias.PortalAliasID, + 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_UPDATED); + + // clear portal alias cache + ClearCache(false); + } + + internal Dictionary GetPortalAliasesInternal() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PortalAliasCacheKey, + DataCache.PortalAliasCacheTimeOut, + DataCache.PortalAliasCachePriority), + c => + { + var dic = CBO.FillDictionary( + "HTTPAlias", + DataProvider.Instance().GetPortalAliases()); + return dic.Keys.ToDictionary(key => key.ToLowerInvariant(), key => dic[key]); + }, + true); + } + protected override Func GetFactory() { return () => new PortalAliasController(); - } - + } + private static void ClearCache(bool refreshServiceRoutes, int portalId = -1) { DataCache.RemoveCache(DataCache.PortalAliasCacheKey); @@ -193,7 +305,7 @@ private static bool ValidateAlias(string portalAlias, bool ischild, bool isDomai } return portalAlias.All(c => validChars.Contains(c.ToString())); - } + } private PortalAliasInfo GetPortalAliasLookupInternal(string alias) { @@ -219,11 +331,11 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) { strPortalAlias = string.Concat("www.", httpAlias); } - + // perform the lookup portalAlias = this.GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); } - + // allow domain wildcards if (portalAlias == null) { @@ -236,7 +348,7 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) { strPortalAlias = httpAlias; } - + // try an explicit lookup using the wildcard entry ( ie. *.domain.com ) portalAlias = this.GetPortalAliasLookupInternal("*." + strPortalAlias.ToLowerInvariant()) ?? this.GetPortalAliasLookupInternal(strPortalAlias.ToLowerInvariant()); @@ -247,7 +359,7 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) portalAlias = this.GetPortalAliasLookupInternal("www." + strPortalAlias.ToLowerInvariant()); } } - + if (portalAlias == null) { // check if this is a fresh install ( no alias values in collection ) @@ -257,7 +369,7 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) { // relate the PortalAlias to the default portal on a fresh database installation DataProvider.Instance().UpdatePortalAlias(httpAlias.ToLowerInvariant().Trim('/'), UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PortalAlias", httpAlias, PortalController.Instance.GetCurrentPortalSettings(), @@ -266,125 +378,13 @@ private PortalAliasInfo GetPortalAliasInternal(string httpAlias) // clear the cachekey "GetPortalByAlias" otherwise portalalias "_default" stays in cache after first install DataCache.RemoveCache("GetPortalByAlias"); - + // try again portalAlias = this.GetPortalAliasLookupInternal(httpAlias.ToLowerInvariant()); } } - - return portalAlias; - } - public PortalAliasInfo GetPortalAlias(string alias) - { - return this.GetPortalAliasInternal(alias); - } - - /// - /// Gets the portal alias. - /// - /// The portal alias. - /// The portal ID. - /// Portal Alias Info. - public PortalAliasInfo GetPortalAlias(string alias, int portalId) - { - return this.GetPortalAliasesInternal().SingleOrDefault(pa => pa.Key.Equals(alias, StringComparison.InvariantCultureIgnoreCase) && pa.Value.PortalID == portalId).Value; - } - - /// - /// Gets the portal alias by portal alias ID. - /// - /// The portal alias ID. - /// Portal alias info. - 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>( - new CacheItemArgs( - DataCache.PortalAliasCacheKey, - DataCache.PortalAliasCacheTimeOut, - DataCache.PortalAliasCachePriority), - c => - { - var dic = CBO.FillDictionary( - "HTTPAlias", - DataProvider.Instance().GetPortalAliases()); - return dic.Keys.ToDictionary(key => key.ToLowerInvariant(), key => dic[key]); - }, - true); - } - - /// - /// Gets the portal by portal alias ID. - /// - /// The portal alias id. - /// Portal info. - public PortalInfo GetPortalByPortalAliasID(int PortalAliasId) - { - return CBO.FillObject(DataProvider.Instance().GetPortalByPortalAliasID(PortalAliasId)); + return portalAlias; } - - public void UpdatePortalAlias(PortalAliasInfo portalAlias) - { - // Update Alias - DataProvider.Instance().UpdatePortalAliasInfo( - portalAlias.PortalAliasID, - 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_UPDATED); - - // clear portal alias cache - ClearCache(false); - } - - /// - /// Validates the alias. - /// - /// The portal alias. - /// if set to true [ischild]. - /// true if the alias is a valid url format; otherwise return false. - public static bool ValidateAlias(string portalAlias, bool ischild) - { - if (ischild) - { - return ValidateAlias(portalAlias, true, false); - } - - // validate the domain - Uri result; - if (Uri.TryCreate(Globals.AddHTTP(portalAlias), UriKind.Absolute, out result)) - { - return ValidateAlias(result.Host, false, true) && ValidateAlias(portalAlias, false, false); - } - - return false; - } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs index 4bc9bfb4e88..4ff612c25ff 100644 --- a/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs +++ b/DNN Platform/Library/Entities/Portals/PortalAliasExtensions.cs @@ -35,7 +35,7 @@ public static Dictionary GetAliasesAndCulturesForPortalId(this I aliasCultures.Add(cpa.HTTPAlias.ToLowerInvariant(), cpa.CultureCode); } } - + return aliasCultures; } @@ -50,7 +50,7 @@ public static Dictionary GetAliasesAndCulturesForPortalId(this I public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable aliases, int portalId, UrlAction result, string cultureCode, FriendlyUrlSettings settings) { var browserType = BrowserTypes.Normal; - + // if required, and possible, detect browser type if (HttpContext.Current != null && settings != null) { @@ -58,7 +58,7 @@ public static PortalAliasInfo GetAliasByPortalIdAndSettings(this IEnumerable a.CultureCode) .FirstOrDefault(); } - + // END DNN-4882 if (foundAlias != null) { @@ -187,7 +187,7 @@ public static List GetAliasesForPortalId(this IEnumerable /// Adds the portal dictionary. /// @@ -123,3561 +123,3561 @@ public static string CreateChildPortalFolder(string ChildPath) } /// - /// Creates a new portal alias. + /// Deletes all expired portals. /// - /// Id of the portal. - /// Portal Alias to be created. - public void AddPortalAlias(int portalId, string portalAlias) + /// The server path. + public static void DeleteExpiredPortals(string serverPath) { - // Check if the Alias exists - PortalAliasInfo portalAliasInfo = PortalAliasController.Instance.GetPortalAlias(portalAlias, portalId); - - // If alias does not exist add new - if (portalAliasInfo == null) + foreach (PortalInfo portal in GetExpiredPortals()) { - portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; - PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); + DeletePortal(portal, serverPath); } } /// - /// Copies the page template. + /// Deletes the portal. /// - /// The template file. - /// The mapped home directory. - public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) + /// The portal. + /// The server path. + /// If the method executed successful, it will return NullString, otherwise return error message. + public static string DeletePortal(PortalInfo portal, string serverPath) { - string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); - if (File.Exists(hostTemplateFile)) + string message = string.Empty; + + // check if this is the last portal + var portals = Instance.GetPortals(); + if (portals.Count > 1) { - string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); - if (!Directory.Exists(portalTemplateFolder)) + if (portal != null) { - // Create Portal Templates folder - Directory.CreateDirectory(portalTemplateFolder); - } + // delete custom resource files + Globals.DeleteFilesRecursive(serverPath, ".Portal-" + portal.PortalID + ".resx"); - string portalTemplateFile = portalTemplateFolder + templateFile; - if (!File.Exists(portalTemplateFile)) - { - File.Copy(hostTemplateFile, portalTemplateFile); - } - } - } + // If child portal delete child folder + var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); + if (arr.Count > 0) + { + var portalAliasInfo = arr[0]; + string portalName = Globals.GetPortalDomainName(portalAliasInfo.HTTPAlias, null, true); + if (portalAliasInfo.HTTPAlias.IndexOf("/", StringComparison.Ordinal) > -1) + { + portalName = GetPortalFolder(portalAliasInfo.HTTPAlias); + } - 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); + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) + { + DeletePortalFolder(serverPath, portalName); + } + } - // 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); - } + // delete upload directory + if (!string.IsNullOrEmpty(portal.HomeDirectory)) + { + var homeDirectory = portal.HomeDirectoryMapPath; - 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); + // check whether home directory is not used by other portal + // it happens when new portal creation failed, but home directory defined by user is already in use with other portal + var homeDirectoryInUse = portals.OfType().Any(x => + x.PortalID != portal.PortalID && + x.HomeDirectoryMapPath.Equals(homeDirectory, StringComparison.OrdinalIgnoreCase)); - // 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 (!homeDirectoryInUse) + { + if (Directory.Exists(homeDirectory)) + { + Globals.DeleteFolderRecursive(homeDirectory); + } + } + } - if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) + // remove database references + DeletePortalInternal(portal.PortalID); + } + } + else { - 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); + message = Localization.GetString("LastPortal"); + } - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; - LogController.Instance.AddLogType(logTypeInfo); + return message; + } - // 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); + /// + /// Get the portal folder froma child portal alias. + /// + /// portal alias. + /// folder path of the child portal. + public static string GetPortalFolder(string alias) + { + alias = alias.ToLowerInvariant().Replace("http://", string.Empty).Replace("https://", string.Empty); + var appPath = Globals.ApplicationPath + "/"; + if (string.IsNullOrEmpty(Globals.ApplicationPath) || alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) == Null.NullInteger) + { + return alias.Contains("/") ? alias.Substring(alias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1) : string.Empty; + } - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); + return alias.Substring(alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) + appPath.Length); + } - logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); - } + /// Delete the child portal folder and try to remove its parent when parent folder is empty. + /// the server path. + /// the child folder path. + public static void DeletePortalFolder(string serverPath, string portalFolder) + { + var physicalPath = serverPath + portalFolder; + Globals.DeleteFolderRecursive(physicalPath); - if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) + // remove parent folder if its empty. + var parentFolder = Directory.GetParent(physicalPath); + while (parentFolder != null && !parentFolder.FullName.Equals(serverPath.TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase)) { - // Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo + if (parentFolder.GetDirectories().Length + parentFolder.GetFiles().Length == 0) { - 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 + parentFolder.Delete(); + parentFolder = parentFolder.Parent; + } + else { - 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); + break; + } } } - protected override Func GetFactory() + /// + /// Gets the portal dictionary. + /// + /// portal dictionary. the dictionary's Key -> Value is: TabId -> PortalId. + public static Dictionary GetPortalDictionary() { - return () => new PortalController(); + string cacheKey = string.Format(DataCache.PortalDictionaryCacheKey); + return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.PortalDictionaryTimeOut, DataCache.PortalDictionaryCachePriority), GetPortalDictionaryCallback); } - 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) + /// ----------------------------------------------------------------------------- + /// + /// GetPortalsByName gets all the portals whose name matches a provided filter expression. + /// + /// + /// + /// The email address to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of PortalInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetPortalsByName(string nameToMatch, int pageIndex, int pageSize, ref int totalRecords) + { + if (pageIndex == -1) { - subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); + pageIndex = 0; + pageSize = int.MaxValue; } - if (unverifiedRoleId == -1) - { - CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); - } + Type type = typeof(PortalInfo); + return CBO.FillCollection(DataProvider.Instance().GetPortalsByName(nameToMatch, pageIndex, pageSize), ref type, ref totalRecords); + } - 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); + public static ArrayList GetPortalsByUser(int userId) + { + Type type = typeof(PortalInfo); + return CBO.FillCollection(DataProvider.Instance().GetPortalsByUser(userId), type); } - private static string CreateProfileDefinitions(int portalId, string templateFilePath) + public static int GetEffectivePortalId(int portalId) { - string strMessage = Null.NullString; - try + if (portalId > Null.NullInteger && Globals.Status != Globals.UpgradeStatus.Upgrade) { - // add profile definitions - XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; + var portal = Instance.GetPortal(portalId); + var portalGroup = (from p in PortalGroupController.Instance.GetPortalGroups() + where p.PortalGroupId == portal.PortalGroupID + select p) + .SingleOrDefault(); - // open the XML template file - try - { - xmlDoc.Load(templateFilePath); - } - catch (Exception ex) + if (portalGroup != null) { - Logger.Error(ex); + portalId = portalGroup.MasterPortalId; } + } - // parse profile definitions if available - var node = xmlDoc.SelectSingleNode("//portal/profiledefinitions"); - if (node != null) + return portalId; + } + + /// + /// Gets all expired portals. + /// + /// all expired portals as array list. + public static ArrayList GetExpiredPortals() + { + return CBO.FillCollection(DataProvider.Instance().GetExpiredPortals(), typeof(PortalInfo)); + } + + /// + /// Determines whether the portal is child portal. + /// + /// The portal. + /// The server path. + /// + /// true if the portal is child portal; otherwise, false. + /// + public static bool IsChildPortal(PortalInfo portal, string serverPath) + { + bool isChild = Null.NullBoolean; + var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); + if (arr.Count > 0) + { + PortalAliasInfo portalAlias = arr[0]; + var portalName = Globals.GetPortalDomainName(portalAlias.HTTPAlias, null, true); + if (portalAlias.HTTPAlias.IndexOf("/") > -1) { - ParseProfileDefinitions(node, portalId); + portalName = GetPortalFolder(portalAlias.HTTPAlias); } - else // template does not contain profile definitions ( ie. was created prior to DNN 3.3.0 ) + + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { - ProfileController.AddDefaultDefinitions(portalId); + isChild = true; } } - catch (Exception ex) - { - strMessage = Localization.GetString("CreateProfileDefinitions.Error"); - Exceptions.LogException(ex); - } - return strMessage; + return isChild; } - private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) + public static bool IsMemberOfPortalGroup(int portalId) { - // 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; + var portal = Instance.GetPortal(portalId); - 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); + return portal != null && portal.PortalGroupID > Null.NullInteger; + } - // clear portal cache - DataCache.ClearHostCache(true); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } + /// + /// Deletes the portal setting (neutral and for all languages). + /// + /// The portal ID. + /// Name of the setting. + public static void DeletePortalSetting(int portalID, string settingName) + { + DeletePortalSetting(portalID, settingName, Null.NullString); + } - try - { - EnsureRequiredEventLogTypesExist(); - } - catch (Exception) - { - // should be no exception, but suppress just in case - } + /// + /// Deletes the portal setting in this language. + /// + /// The portal ID. + /// Name of the setting. + /// The culture code. + public static void DeletePortalSetting(int portalID, string settingName, string cultureCode) + { + DataProvider.Instance().DeletePortalSetting(portalID, settingName, cultureCode.ToLowerInvariant()); + EventLogController.Instance.AddLog("SettingName", settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); + DataCache.ClearHostCache(true); + } - return PortalId; + /// + /// Deletes all portal settings by portal id. + /// + /// The portal ID. + public static void DeletePortalSettings(int portalID) + { + DeletePortalSettings(portalID, Null.NullString); } - private void AddFolderPermissions(int portalId, int folderId) + /// + /// Deletes all portal settings by portal id and for a given language (Null: all languages and neutral settings). + /// + /// The portal ID. + public static void DeletePortalSettings(int portalID, string cultureCode) { - var portal = this.GetPortal(portalId); - var folderManager = FolderManager.Instance; - var folder = folderManager.GetFolder(folderId); - var permissionController = new PermissionController(); - foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", string.Empty)) - { - var folderPermission = new FolderPermissionInfo(permission) - { - FolderID = folder.FolderID, - RoleID = portal.AdministratorRoleId, - AllowAccess = true, - }; + DataProvider.Instance().DeletePortalSettings(portalID, cultureCode); + EventLogController.Instance.AddLog("PortalID", portalID.ToString() + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); + DataCache.ClearHostCache(true); + } - folder.FolderPermissions.Add(folderPermission); - if (permission.PermissionKey == "READ") - { - // add READ permissions to the All Users Role - folderManager.AddAllUserReadPermission(folder, permission); - } - } + /// + /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value. + /// + /// the setting to read. + /// the pass phrase used for encryption/decryption. + /// + public static string GetEncryptedString(string settingName, int portalID, string passPhrase) + { + Requires.NotNullOrEmpty("key", settingName); + Requires.NotNullOrEmpty("passPhrase", passPhrase); - FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + var cipherText = GetPortalSetting(settingName, portalID, string.Empty); + + return Security.FIPSCompliant.DecryptAES(cipherText, passPhrase, Host.Host.GUID); } - 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) + /// + /// Gets the portal setting. + /// + /// Name of the setting. + /// The portal ID. + /// The default value. + /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. + public static string GetPortalSetting(string settingName, int portalID, string defaultValue) { - // Add default workflows + var retValue = Null.NullString; try { - SystemWorkflowManager.Instance.CreateSystemWorkflows(portalId); - } - catch (Exception ex) - { - Exceptions.LogException(ex); + string setting; + Instance.GetPortalSettings(portalID).TryGetValue(settingName, out setting); + retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; } - - string templatePath, templateFile; - this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); - string mergedTemplatePath = Path.Combine(templatePath, templateFile); - - if (string.IsNullOrEmpty(homeDirectory)) + catch (Exception exc) { - homeDirectory = "Portals/" + portalId; + Logger.Error(exc); } - string mappedHomeDirectory = string.Format(Globals.ApplicationMapPath + "\\" + homeDirectory + "\\").Replace("/", "\\"); + return retValue; + } - if (Directory.Exists(mappedHomeDirectory)) - { - message += string.Format(Localization.GetString("CreatePortalHomeFolderExists.Error"), homeDirectory); - throw new Exception(message); + /// + /// Gets the portal setting for a specific language (or neutral). + /// + /// Name of the setting. + /// The portal ID. + /// The default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. + public static string GetPortalSetting(string settingName, int portalID, string defaultValue, string cultureCode) + { + var retValue = Null.NullString; + try + { + string setting; + Instance.GetPortalSettings(portalID, cultureCode).TryGetValue(settingName, out setting); + retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; + } + catch (Exception exc) + { + Logger.Error(exc); } - message += CreateProfileDefinitions(portalId, mergedTemplatePath); + return retValue; + } - if (string.IsNullOrEmpty(message)) + /// + /// Gets the portal setting as boolean. + /// + /// The key. + /// The portal ID. + /// default value. + /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. + public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue) + { + bool retValue = Null.NullBoolean; + try { - try + string setting; + Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); + if (string.IsNullOrEmpty(setting)) { - // the upload directory may already exist if this is a new DB working with a previously installed application - if (Directory.Exists(mappedHomeDirectory)) - { - Globals.DeleteFolderRecursive(mappedHomeDirectory); - } + retValue = defaultValue; } - catch (Exception Exc) + else { - Logger.Error(Exc); - message += Localization.GetString("DeleteUploadFolder.Error") + Exc.Message + Exc.StackTrace; + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } + } + catch (Exception exc) + { + Logger.Error(exc); + } - // Set up Child Portal - if (message == Null.NullString) + return retValue; + } + + /// + /// Gets the portal setting as boolean for a specific language (or neutral). + /// + /// The key. + /// The portal ID. + /// default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. + public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue, string cultureCode) + { + bool retValue = Null.NullBoolean; + try + { + string setting; + GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); + if (string.IsNullOrEmpty(setting)) { - if (isChildPortal) - { - message = CreateChildPortalFolder(childPath); - } + retValue = defaultValue; } else { - throw new Exception(message); + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } + } + catch (Exception exc) + { + Logger.Error(exc); + } - if (message == Null.NullString) - { - try - { - // create the upload directory for the new portal - Directory.CreateDirectory(mappedHomeDirectory); - - // ensure that the Templates folder exists - string templateFolder = string.Format("{0}Templates", mappedHomeDirectory); - if (!Directory.Exists(templateFolder)) - { - Directory.CreateDirectory(templateFolder); - } - - // ensure that the Users folder exists - string usersFolder = string.Format("{0}Users", mappedHomeDirectory); - if (!Directory.Exists(usersFolder)) - { - Directory.CreateDirectory(usersFolder); - } - - // copy the default page template - this.CopyPageTemplate("Default.page.template", mappedHomeDirectory); + return retValue; + } - // process zip resource file if present - if (File.Exists(template.ResourceFilePath)) - { - this.ProcessResourceFileExplicit(mappedHomeDirectory, template.ResourceFilePath); - } - } - catch (Exception Exc) - { - Logger.Error(Exc); - message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; - } + /// + /// Gets the portal setting as integer. + /// + /// The key. + /// The portal ID. + /// The default value. + /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. + public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue) + { + int retValue = Null.NullInteger; + try + { + string setting; + Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); + if (string.IsNullOrEmpty(setting)) + { + retValue = defaultValue; } else { - throw new Exception(message); + retValue = Convert.ToInt32(setting); } + } + catch (Exception exc) + { + Logger.Error(exc); + } - if (message == Null.NullString) + return retValue; + } + + /// + /// Gets the portal setting as double. + /// + /// The key. + /// The portal Id. + /// The default value. + /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. + public static double GetPortalSettingAsDouble(string key, int portalId, double defaultValue) + { + double retValue = Null.NullDouble; + try + { + string setting; + Instance.GetPortalSettings(portalId).TryGetValue(key, out setting); + if (string.IsNullOrEmpty(setting)) { - try - { - FolderMappingController.Instance.AddDefaultFolderTypes(portalId); - } - catch (Exception Exc) - { - Logger.Error(Exc); - message += Localization.GetString("DefaultFolderMappings.Error") + Exc.Message + Exc.StackTrace; - } + retValue = defaultValue; } else { - throw new Exception(message); + retValue = Convert.ToDouble(setting); } + } + catch (Exception exc) + { + Logger.Error(exc); + } - LocaleCollection newPortalLocales = null; - if (message == Null.NullString) + return retValue; + } + + /// + /// Gets the portal setting as integer for a specific language (or neutral). + /// + /// The key. + /// The portal ID. + /// The default value. + /// culture code of the language to retrieve (not empty). + /// Returns setting's value if portal contains the specific setting (for specified lang, otherwise return defaultValue. + public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue, string cultureCode) + { + int retValue = Null.NullInteger; + try + { + string setting; + GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); + if (string.IsNullOrEmpty(setting)) { - try - { - this.CreatePredefinedFolderTypes(portalId); - this.ParseTemplateInternal(portalId, templatePath, templateFile, adminUser.UserID, PortalTemplateModuleAction.Replace, true, out newPortalLocales); - } - catch (Exception Exc) - { - Logger.Error(Exc); - message += Localization.GetString("PortalTemplate.Error") + Exc.Message + Exc.StackTrace; - } + retValue = defaultValue; } else { - throw new Exception(message); + retValue = Convert.ToInt32(setting); } + } + catch (Exception exc) + { + Logger.Error(exc); + } - if (message == Null.NullString) - { - var portal = this.GetPortal(portalId); - portal.Description = description; - portal.KeyWords = keyWords; - portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//UserProfile", portal.CultureCode); - if (portal.UserTabId == -1) - { - portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed", portal.CultureCode); - } - - portal.SearchTabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", portal.CultureCode); - this.UpdatePortalInfo(portal); + return retValue; + } - adminUser.Profile.PreferredLocale = portal.DefaultLanguage; - var portalSettings = new PortalSettings(portal); - adminUser.Profile.PreferredTimeZone = portalSettings.TimeZone; - UserController.UpdateUser(portal.PortalID, adminUser); + /// + /// takes in a text value, encrypts it with a FIPS compliant algorithm and stores. + /// + /// The portal ID. + /// host settings key. + /// host settings value. + /// pass phrase to allow encryption/decryption. + public static void UpdateEncryptedString(int portalID, string settingName, string settingValue, string passPhrase) + { + Requires.NotNullOrEmpty("key", settingName); + Requires.PropertyNotNull("value", settingValue); + Requires.NotNullOrEmpty("passPhrase", passPhrase); - DesktopModuleController.AddDesktopModulesToPortal(portalId); + var cipherText = Security.FIPSCompliant.EncryptAES(settingValue, passPhrase, Host.Host.GUID); - this.AddPortalAlias(portalId, portalAlias); + UpdatePortalSetting(portalID, settingName, cipherText); + } - UpdatePortalSetting(portalId, "DefaultPortalAlias", portalAlias, false); + /// + /// Updates a single neutral (not language specific) portal setting and clears it from the cache. + /// + /// The portal ID. + /// Name of the setting. + /// The setting value. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue) + { + UpdatePortalSetting(portalID, settingName, settingValue, true); + } - DataCache.ClearPortalCache(portalId, true); + /// + /// Updates a single neutral (not language specific) portal setting, optionally without clearing the cache. + /// + /// The portal ID. + /// Name of the setting. + /// The setting value. + /// if set to true [clear cache]. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache) + { + UpdatePortalSetting(portalID, settingName, settingValue, clearCache, Null.NullString, false); + } - if (newPortalLocales != null) - { - foreach (Locale newPortalLocale in newPortalLocales.AllValues) - { - Localization.AddLanguageToPortal(portalId, newPortalLocale.LanguageId, false); - if (portalSettings.ContentLocalizationEnabled) - { - this.MapLocalizedSpecialPages(portalId, newPortalLocale.Code); - } - } - } + /// + /// Updates a language specific or neutral portal setting and clears it from the cache. + /// + /// The portal ID. + /// Name of the setting. + /// The setting value. + /// culture code for language specific settings, null string ontherwise. + [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, string cultureCode) + { + UpdatePortalSetting(portalID, settingName, settingValue, true, cultureCode, false); + } - try - { - RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portalId); - } - catch (Exception Exc) - { - Logger.Error(Exc); - } + /// + /// Updates a language specific or neutral portal setting and optionally clears it from the cache. + /// + /// The portal ID. + /// Name of the setting. + /// The setting value. + /// if set to true [clear cache]. + /// culture code for language specific settings, null string ontherwise. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) + { + UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, false); + } - // add profanity list to new portal - try - { - const string listName = "ProfanityFilter"; - var listController = new ListController(); - var entry = new ListEntryInfo - { - PortalID = portalId, - SystemList = false, - ListName = listName + "-" + portalId, - }; - listController.AddListEntry(entry); - } - catch (Exception Exc) - { - Logger.Error(Exc); - } + /// + /// Updates a language specific or neutral portal setting and optionally clears it from the cache. + /// All overloaded methors will not encrypt the setting value. Therefore, call this method whenever + /// there is a need to encrypt the setting value before storing it in the datanbase. + /// + /// The portal ID. + /// Name of the setting. + /// The setting value. + /// if set to true [clear cache]. + /// culture code for language specific settings, null string ontherwise. + /// When true it encrypt the value before storing it in the database. + public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) + { + Instance.UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); + } - // add banned password list to new portal - try - { - const string listName = "BannedPasswords"; - var listController = new ListController(); - var entry = new ListEntryInfo - { - PortalID = portalId, - SystemList = false, - ListName = listName + "-" + portalId, - }; - listController.AddListEntry(entry); - } - catch (Exception Exc) - { - Logger.Error(Exc); - } + /// + /// Checks the desktop modules whether is installed. + /// + /// The nav. + /// Empty string if the module hasn't been installed, otherwise return the friendly name. + public static string CheckDesktopModulesInstalled(XPathNavigator nav) + { + string friendlyName; + DesktopModuleInfo desktopModule; + StringBuilder modulesNotInstalled = new StringBuilder(); - ServicesRoutingManager.ReRegisterServiceRoutesWhileSiteIsRunning(); + foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) + { + friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); - try + if (!string.IsNullOrEmpty(friendlyName)) + { + desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); + if (desktopModule == null) { - var log = new LogInfo + // PE and EE templates have HTML as friendly name so check to make sure + // there is really no HTML module installed + if (friendlyName == "HTML") { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.PORTAL_CREATED.ToString(), - }; - log.LogProperties.Add(new LogDetailInfo("Install Portal:", portalName)); - log.LogProperties.Add(new LogDetailInfo("FirstName:", adminUser.FirstName)); - log.LogProperties.Add(new LogDetailInfo("LastName:", adminUser.LastName)); - log.LogProperties.Add(new LogDetailInfo("Username:", adminUser.Username)); - log.LogProperties.Add(new LogDetailInfo("Email:", adminUser.Email)); - log.LogProperties.Add(new LogDetailInfo("Description:", description)); - log.LogProperties.Add(new LogDetailInfo("Keywords:", keyWords)); - log.LogProperties.Add(new LogDetailInfo("Template:", template.TemplateFilePath)); - log.LogProperties.Add(new LogDetailInfo("TemplateCulture:", template.CultureCode)); - log.LogProperties.Add(new LogDetailInfo("HomeDirectory:", homeDirectory)); - log.LogProperties.Add(new LogDetailInfo("PortalAlias:", portalAlias)); - log.LogProperties.Add(new LogDetailInfo("ServerPath:", serverPath)); - log.LogProperties.Add(new LogDetailInfo("ChildPath:", childPath)); - log.LogProperties.Add(new LogDetailInfo("IsChildPortal:", isChildPortal.ToString())); - LogController.Instance.AddLog(log); - } - catch (Exception exc) - { - Logger.Error(exc); + desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName("HTML Pro"); + if (desktopModule == null) + { + modulesNotInstalled.Append(friendlyName); + modulesNotInstalled.Append("
    "); + } + } + else + { + modulesNotInstalled.Append(friendlyName); + modulesNotInstalled.Append("
    "); + } } - - EventManager.Instance.OnPortalCreated(new PortalCreatedEventArgs { PortalId = portalId }); - } - else - { - throw new Exception(message); } } - else - { - DeletePortalInternal(portalId); - throw new Exception(message); - } + + return modulesNotInstalled.ToString(); } - private static int CreateRole(RoleInfo role) + /// + /// function provides the language for portalinfo requests + /// in case where language has not been installed yet, will return the core install default of en-us. + /// + /// + /// + /// + /// + public static string GetActivePortalLanguage(int portalID) { - int roleId; + // get Language + string Language = Localization.SystemLocale; + string tmpLanguage = GetPortalDefaultLanguage(portalID); + var isDefaultLanguage = false; + if (!string.IsNullOrEmpty(tmpLanguage)) + { + Language = tmpLanguage; + isDefaultLanguage = true; + } - // First check if the role exists - var objRoleInfo = RoleController.Instance.GetRole(role.PortalID, r => r.RoleName == role.RoleName); - if (objRoleInfo == null) + // handles case where portalcontroller methods invoked before a language is installed + if (portalID > Null.NullInteger && Globals.Status == Globals.UpgradeStatus.None && Localization.ActiveLanguagesByPortalID(portalID) == 1) { - roleId = RoleController.Instance.AddRole(role); + return Language; } - else + + if (HttpContext.Current != null && Globals.Status == Globals.UpgradeStatus.None) { - roleId = objRoleInfo.RoleID; + if (HttpContext.Current.Request.QueryString["language"] != null) + { + Language = HttpContext.Current.Request.QueryString["language"]; + } + else + { + PortalSettings _PortalSettings = GetCurrentPortalSettingsInternal(); + if (_PortalSettings != null && _PortalSettings.ActiveTab != null && !string.IsNullOrEmpty(_PortalSettings.ActiveTab.CultureCode)) + { + Language = _PortalSettings.ActiveTab.CultureCode; + } + else + { + // PortalSettings IS Nothing - probably means we haven't set it yet (in Begin Request) + // so try detecting the user's cookie + if (HttpContext.Current.Request["language"] != null) + { + Language = HttpContext.Current.Request["language"]; + isDefaultLanguage = false; + } + + // if no cookie - try detecting browser + if ((string.IsNullOrEmpty(Language) || isDefaultLanguage) && EnableBrowserLanguageInDefault(portalID)) + { + CultureInfo Culture = Localization.GetBrowserCulture(portalID); + + if (Culture != null) + { + Language = Culture.Name; + } + } + } + } } - return roleId; + return Language; } - private static int CreateRole(int portalId, string roleName, string description, float serviceFee, int billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, - bool isPublic, bool isAuto) + /// + /// return the current DefaultLanguage value from the Portals table for the requested Portalid. + /// + /// + /// + /// + /// + public static string GetPortalDefaultLanguage(int portalID) { - RoleInfo objRoleInfo = new RoleInfo(); - objRoleInfo.PortalID = portalId; - objRoleInfo.RoleName = roleName; - objRoleInfo.RoleGroupID = Null.NullInteger; - objRoleInfo.Description = description; - objRoleInfo.ServiceFee = Convert.ToSingle(serviceFee < 0 ? 0 : serviceFee); - objRoleInfo.BillingPeriod = billingPeriod; - objRoleInfo.BillingFrequency = billingFrequency; - objRoleInfo.TrialFee = Convert.ToSingle(trialFee < 0 ? 0 : trialFee); - objRoleInfo.TrialPeriod = trialPeriod; - objRoleInfo.TrialFrequency = trialFrequency; - objRoleInfo.IsPublic = isPublic; - objRoleInfo.AutoAssignment = isAuto; - return CreateRole(objRoleInfo); + string cacheKey = string.Format("PortalDefaultLanguage_{0}", portalID); + return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, portalID), GetPortalDefaultLanguageCallBack); } - private static void CreateRoleGroup(RoleGroupInfo roleGroup) + /// + /// set the required DefaultLanguage in the Portals table for a particular portal + /// saves having to update an entire PortalInfo object. + /// + /// + /// + /// + /// + public static void UpdatePortalDefaultLanguage(int portalID, string CultureCode) { - // First check if the role exists - var objRoleGroupInfo = RoleController.GetRoleGroupByName(roleGroup.PortalID, roleGroup.RoleGroupName); + DataProvider.Instance().UpdatePortalDefaultLanguage(portalID, CultureCode); - if (objRoleGroupInfo == null) - { - roleGroup.RoleGroupID = RoleController.AddRoleGroup(roleGroup); - } - else + // ensure localization record exists as new portal default language may be relying on fallback chain + // of which it is now the final part + DataProvider.Instance().EnsureLocalizationExists(portalID, CultureCode); + } + + public static void IncrementCrmVersion(int portalID) + { + int currentVersion; + var versionSetting = GetPortalSetting(ClientResourceSettings.VersionKey, portalID, "1"); + if (int.TryParse(versionSetting, out currentVersion)) { - roleGroup.RoleGroupID = objRoleGroupInfo.RoleGroupID; + var newVersion = currentVersion + 1; + UpdatePortalSetting(portalID, ClientResourceSettings.VersionKey, newVersion.ToString(CultureInfo.InvariantCulture), true); } } - private static void DeletePortalInternal(int portalId) + public static void IncrementOverridingPortalsCrmVersion() { - UserController.DeleteUsers(portalId, false, true); - - var portal = Instance.GetPortal(portalId); - - DataProvider.Instance().DeletePortalInfo(portalId); - - try + foreach (PortalInfo portal in Instance.GetPortals()) { - var log = new LogInfo + string setting = GetPortalSetting(ClientResourceSettings.OverrideDefaultSettingsKey, portal.PortalID, "False"); + bool overriden; + + // if this portal is overriding the host level... + if (bool.TryParse(setting, out overriden) && overriden) { - 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); + // increment its version + IncrementCrmVersion(portal.PortalID); + } } + } - 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); - // queue remove portal from search index - var document = new SearchDocumentToDelete + // If alias does not exist add new + if (portalAliasInfo == null) { - PortalId = portalId, - }; - - DataProvider.Instance().AddSearchDeletedItems(document); + portalAliasInfo = new PortalAliasInfo { PortalID = portalId, HTTPAlias = portalAlias, IsPrimary = true }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); + } } - private static bool DoesLogTypeExists(string logTypeKey) + /// + /// Copies the page template. + /// + /// The template file. + /// The mapped home directory. + public void CopyPageTemplate(string templateFile, string mappedHomeDirectory) { - LogTypeInfo logType; - Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - logTypeDictionary.TryGetValue(logTypeKey, out logType); - if (logType == null) + string hostTemplateFile = string.Format("{0}Templates\\{1}", Globals.HostMapPath, templateFile); + if (File.Exists(hostTemplateFile)) { - return false; - } + string portalTemplateFolder = string.Format("{0}Templates\\", mappedHomeDirectory); + if (!Directory.Exists(portalTemplateFolder)) + { + // Create Portal Templates folder + Directory.CreateDirectory(portalTemplateFolder); + } - return true; + string portalTemplateFile = portalTemplateFolder + templateFile; + if (!File.Exists(portalTemplateFile)) + { + File.Copy(hostTemplateFile, portalTemplateFile); + } + } } - private static PortalSettings GetCurrentPortalSettingsInternal() + /// + /// Creates the portal. + /// + /// Name of the portal. + /// The obj admin user. + /// The description. + /// The key words. + /// + /// The home directory. + /// The portal alias. + /// The server path. + /// The child path. + /// if set to true means the portal is child portal. + /// Portal id. + public int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, + string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { - PortalSettings objPortalSettings = null; + // Attempt to create a new portal + int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); + + // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. if (HttpContext.Current != null) { - objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; + HttpContext.Current.Items.Add("CreatingPortalId", portalId); } - return objPortalSettings; - } + string message = Null.NullString; - private static PortalInfo GetPortalInternal(int portalId, string cultureCode) - { - return Instance.GetPortalList(cultureCode).SingleOrDefault(p => p.PortalID == portalId); - } + if (portalId != -1) + { + // add administrator + int administratorId = adminUserId; + var adminUser = new UserInfo(); - private static object GetPortalDefaultLanguageCallBack(CacheItemArgs cacheItemArgs) - { - int portalID = (int)cacheItemArgs.ParamList[0]; - return DataProvider.Instance().GetPortalDefaultLanguage(portalID); - } + // add userportal record + UserController.AddUserPortal(portalId, administratorId); - private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) - { - var portalDic = new Dictionary(); - if (Host.Host.PerformanceSetting != Globals.PerformanceSettings.NoCaching) - { - // get all tabs - int intField = 0; - IDataReader dr = DataProvider.Instance().GetTabPaths(Null.NullInteger, Null.NullString); + // retrieve existing administrator try { - while (dr.Read()) - { - // add to dictionary - portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField))] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField)); - } + adminUser = UserController.GetUserById(portalId, administratorId); } - catch (Exception exc) + catch (Exception Exc) { - Exceptions.LogException(exc); + Logger.Error(Exc); } - finally + + if (administratorId > 0) { - // close datareader - CBO.CloseDataReader(dr, true); + this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } - - return portalDic; - } - - private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - var dicSettings = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - if (portalId <= -1) - { - return dicSettings; - } - - var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1]); - if (string.IsNullOrEmpty(cultureCode)) + else { - cultureCode = GetActivePortalLanguage(portalId); + message += Localization.GetString("CreatePortal.Error"); + throw new Exception(message); } - var dr = DataProvider.Instance().GetPortalSettings(portalId, cultureCode); try { - while (dr.Read()) - { - if (dr.IsDBNull(1)) - { - continue; - } - - var key = dr.GetString(0); - if (dicSettings.ContainsKey(key)) - { - dicSettings[key] = dr.GetString(1); - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(), - }; - log.AddProperty("Duplicate PortalSettings Key", key); - LogController.Instance.AddLog(log); - } - else - { - dicSettings.Add(key, dr.GetString(1)); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); + EnsureRequiredEventLogTypesExist(); } - finally + catch (Exception) { - CBO.CloseDataReader(dr, true); + // should be no exception, but suppress just in case } - return dicSettings; + // remove the portal id from http context as there is no exception. + if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) + { + HttpContext.Current.Items.Remove("CreatingPortalId"); + } + + return portalId; } - private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo folder) + /// + /// Creates the portal. + /// + /// Name of the portal. + /// The obj admin user. + /// The description. + /// The key words. + /// + /// The home directory. + /// The portal alias. + /// The server path. + /// The child path. + /// if set to true means the portal is child portal. + /// Portal id. + public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, + string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) { - var fileManager = FileManager.Instance; + // Attempt to create a new portal + int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); - foreach (XmlNode node in nodeFiles) + // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. + if (HttpContext.Current != null) { - var fileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "filename"); - - // First check if the file exists - var file = fileManager.GetFile(folder, fileName); - - if (file != null) - { - continue; - } + HttpContext.Current.Items.Add("CreatingPortalId", portalId); + } - file = new FileInfo - { - PortalId = portalId, - FileName = fileName, - Extension = XmlUtils.GetNodeValue(node.CreateNavigator(), "extension"), - Size = XmlUtils.GetNodeValueInt(node, "size"), - Width = XmlUtils.GetNodeValueInt(node, "width"), - Height = XmlUtils.GetNodeValueInt(node, "height"), - ContentType = XmlUtils.GetNodeValue(node.CreateNavigator(), "contenttype"), - SHA1Hash = XmlUtils.GetNodeValue(node.CreateNavigator(), "sha1hash"), - FolderId = folder.FolderID, - Folder = folder.FolderPath, - Title = string.Empty, - StartDate = DateTime.Now, - EndDate = Null.NullDate, - EnablePublishPeriod = false, - ContentItemID = Null.NullInteger, - }; + string message = Null.NullString; - // Save new File + if (portalId != -1) + { + // add administrator + int administratorId = Null.NullInteger; + adminUser.PortalID = portalId; try { - // Initially, install files are on local system, then we need the Standard folder provider to read the content regardless the target folderprovider - using (var fileContent = FolderProvider.Instance("StandardFolderProvider").GetFileStream(file)) + UserCreateStatus createStatus = UserController.CreateUser(ref adminUser); + if (createStatus == UserCreateStatus.Success) { - var contentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)); - var userId = UserController.Instance.GetCurrentUserInfo().UserID; - file.FileId = fileManager.AddFile(folder, fileName, fileContent, false, false, true, contentType, userId).FileId; - } - - fileManager.UpdateFile(file); - } - catch (InvalidFileExtensionException ex) // when the file is not allowed, we should not break parse process, but just log the error. - { - Logger.Error(ex.Message); - } - } - } - - private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, int portalId, FolderInfo folder) - { - PermissionController permissionController = new PermissionController(); - int permissionId = 0; + administratorId = adminUser.UserID; - // Clear the current folder permissions - folder.FolderPermissions.Clear(); - foreach (XmlNode xmlFolderPermission in nodeFolderPermissions) - { - string permissionKey = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissionkey"); - string permissionCode = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissioncode"); - string roleName = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "rolename"); - bool allowAccess = XmlUtils.GetNodeValueBoolean(xmlFolderPermission, "allowaccess"); - foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey)) - { - permissionId = permission.PermissionID; + // reload the UserInfo as when it was first created, it had no portal id and therefore + // used host profile definitions + adminUser = UserController.GetUserById(adminUser.PortalID, adminUser.UserID); + } + else + { + message += UserController.GetUserCreateStatus(createStatus); + } } - - int roleId = int.MinValue; - switch (roleName) + catch (Exception Exc) { - case Globals.glbRoleAllUsersName: - roleId = Convert.ToInt32(Globals.glbRoleAllUsers); - break; - case Globals.glbRoleUnauthUserName: - roleId = Convert.ToInt32(Globals.glbRoleUnauthUser); - break; - default: - RoleInfo objRole = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); - if (objRole != null) - { - roleId = objRole.RoleID; - } - - break; + Logger.Error(Exc); + message += Localization.GetString("CreateAdminUser.Error") + Exc.Message + Exc.StackTrace; } - // if role was found add, otherwise ignore - if (roleId != int.MinValue) + if (administratorId > 0) { - var folderPermission = new FolderPermissionInfo - { - FolderID = folder.FolderID, - PermissionID = permissionId, - RoleID = roleId, - UserID = Null.NullInteger, - AllowAccess = allowAccess, - }; - - bool canAdd = !folder.FolderPermissions.Cast() - .Any(fp => fp.FolderID == folderPermission.FolderID - && fp.PermissionID == folderPermission.PermissionID - && fp.RoleID == folderPermission.RoleID - && fp.UserID == folderPermission.UserID); - if (canAdd) - { - folder.FolderPermissions.Add(folderPermission); - } + this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); } } - - FolderPermissionController.SaveFolderPermissions(folder); - } - - private static void EnsureRequiredProvidersForFolderTypes() - { - if (ComponentFactory.GetComponent() == null) - { - ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); - ComponentFactory.RegisterComponentInstance(new FipsCompilanceCryptographyProvider()); - } - } - - private static void EnsureFolderProviderRegistration(FolderTypeConfig folderTypeConfig, XmlDocument webConfig) - where TAbstract : class - { - var providerBusinessClassNode = webConfig.SelectSingleNode("configuration/dotnetnuke/folder/providers/add[@name='" + folderTypeConfig.Provider + "']"); - - var typeClass = Type.GetType(providerBusinessClassNode.Attributes["type"].Value); - if (typeClass != null) + else { - ComponentFactory.RegisterComponentInstance(folderTypeConfig.Provider, Activator.CreateInstance(typeClass)); + message += Localization.GetString("CreatePortal.Error"); + throw new Exception(message); } - } - private void CreatePredefinedFolderTypes(int portalId) - { try { - EnsureRequiredProvidersForFolderTypes(); + EnsureRequiredEventLogTypesExist(); } - catch (Exception ex) + catch (Exception) { - Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); + // should be no exception, but suppress just in case } - var webConfig = Config.Load(); - foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) + // remove the portal id from http context as there is no exception. + if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) { - try - { - EnsureFolderProviderRegistration(folderTypeConfig, webConfig); - FolderMappingController.Instance.AddFolderMapping(this.GetFolderMappingFromConfig( - folderTypeConfig, - portalId)); - } - catch (Exception ex) - { - Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error") + ": " + folderTypeConfig.Name, ex); - } + HttpContext.Current.Items.Remove("CreatingPortalId"); } + + return portalId; } - private static bool EnableBrowserLanguageInDefault(int portalId) + /// + /// Get all the available portal templates grouped by culture. + /// + /// List of PortalTemplateInfo objects. + public IList GetAvailablePortalTemplates() { - bool retValue = Null.NullBoolean; - try + var list = new List(); + + var templateFilePaths = PortalTemplateIO.Instance.EnumerateTemplates(); + var languageFileNames = PortalTemplateIO.Instance.EnumerateLanguageFiles().Select(Path.GetFileName).ToList(); + + foreach (string templateFilePath in templateFilePaths) { - string setting; - GetPortalSettingsDictionary(portalId, Localization.SystemLocale).TryGetValue("EnableBrowserLanguage", out setting); - if (string.IsNullOrEmpty(setting)) + var currentFileName = Path.GetFileName(templateFilePath); + var langs = languageFileNames.Where(x => this.GetTemplateName(x).Equals(currentFileName, StringComparison.InvariantCultureIgnoreCase)).Select(x => this.GetCultureCode(x)).Distinct().ToList(); + + if (langs.Any()) { - retValue = Host.Host.EnableBrowserLanguage; + langs.ForEach(x => list.Add(new PortalTemplateInfo(templateFilePath, x))); } else { - retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); + // DNN-6544 portal creation requires valid culture, if template has no culture defined, then use portal's default language. + var portalSettings = PortalSettings.Current; + var cultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; + list.Add(new PortalTemplateInfo(templateFilePath, cultureCode)); } } - catch (Exception exc) - { - Logger.Error(exc); - } - return retValue; + return list; } - private static Dictionary GetPortalSettingsDictionary(int portalId, string cultureCode) + /// + /// Gets information of a portal. + /// + /// Id of the portal. + /// PortalInfo object with portal definition. + public PortalInfo GetPortal(int portalId) { - var httpContext = HttpContext.Current; - - if (string.IsNullOrEmpty(cultureCode) && portalId > -1) + if (portalId == -1) { - cultureCode = GetActivePortalLanguageFromHttpContext(httpContext, portalId); + return null; } - // Get PortalSettings from Context or from cache - var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); - Dictionary dictionary = null; - if (httpContext != null) + string defaultLanguage = GetActivePortalLanguage(portalId); + PortalInfo portal = this.GetPortal(portalId, defaultLanguage); + if (portal == null) { - dictionary = httpContext.Items[dictionaryKey] as Dictionary; - } - - if (dictionary == null) - { - var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); - dictionary = CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.PortalSettingsCacheTimeOut, - DataCache.PortalSettingsCachePriority, portalId, cultureCode), - GetPortalSettingsDictionaryCallback, - true); - if (httpContext != null) - { - httpContext.Items[dictionaryKey] = dictionary; - } + // Active language may not be valid, so fallback to default language + defaultLanguage = GetPortalDefaultLanguage(portalId); + portal = this.GetPortal(portalId, defaultLanguage); } - return dictionary; + return portal; } - private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + /// + /// Gets information of a portal. + /// + /// Id of the portal. + /// The culture code. + /// + public PortalInfo GetPortal(int portalId, string cultureCode) { - var cultureCode = string.Empty; - - // Lookup culturecode but cache it in the HttpContext for performance - var activeLanguageKey = string.Format("ActivePortalLanguage{0}", portalId); - if (httpContext != null) + if (portalId == -1) { - cultureCode = (string)httpContext.Items[activeLanguageKey]; + return null; } - if (string.IsNullOrEmpty(cultureCode)) + PortalInfo portal = GetPortalInternal(portalId, cultureCode); + + if (Localization.ActiveLanguagesByPortalID(portalId) > 1) { - cultureCode = GetActivePortalLanguage(portalId); - if (httpContext != null) + if (portal == null) { - httpContext.Items[activeLanguageKey] = cultureCode; - } - } + // Get Fallback language + string fallbackLanguage = string.Empty; - return cultureCode; - } + if (string.IsNullOrEmpty(cultureCode)) + { + cultureCode = GetPortalDefaultLanguage(portalId); + } - 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; - } + Locale userLocale = LocaleController.Instance.GetLocale(cultureCode); + if (userLocale != null && !string.IsNullOrEmpty(userLocale.Fallback)) + { + fallbackLanguage = userLocale.Fallback; + } - var active = XmlUtils.GetNodeValueBoolean(providerNavigator, "active"); - if (active) - { - ExtensionUrlProviderController.EnableProvider(provider.ExtensionUrlProviderId, portalId); - } - else - { - ExtensionUrlProviderController.DisableProvider(provider.ExtensionUrlProviderId, portalId); - } + if (string.IsNullOrEmpty(fallbackLanguage)) + { + fallbackLanguage = Localization.SystemLocale; + } - var settingsNavigator = providerNavigator.SelectSingleNode("settings"); - if (settingsNavigator != null) - { - foreach (XPathNavigator settingNavigator in settingsNavigator.Select("setting")) + portal = GetPortalInternal(portalId, fallbackLanguage); + + // if we cannot find any fallback, it mean's it's a non portal default langauge + if (portal == null) { - var name = XmlUtils.GetAttributeValue(settingNavigator, "name"); - var value = XmlUtils.GetAttributeValue(settingNavigator, "value"); - ExtensionUrlProviderController.SaveSetting(provider.ExtensionUrlProviderId, portalId, name, value); + DataProvider.Instance().EnsureLocalizationExists(portalId, GetActivePortalLanguage(portalId)); + DataCache.ClearHostCache(true); + portal = GetPortalInternal(portalId, GetActivePortalLanguage(portalId)); } } } + + return portal; } - private string EnsureSettingValue(string folderProviderType, FolderTypeSettingConfig settingNode, int portalId) + /// + /// Gets the portal. + /// + /// The unique id. + /// Portal info. + public PortalInfo GetPortal(Guid uniqueId) { - 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; + return this.GetPortalList(Null.NullString).SingleOrDefault(p => p.GUID == uniqueId); } - private string GetCultureCode(string languageFileName) + /// + /// Gets information from all portals. + /// + /// ArrayList of PortalInfo objects. + public ArrayList GetPortals() { - // e.g. "default template.template.en-US.resx" - return languageFileName.GetLocaleCodeFromFileName(); + return new ArrayList(this.GetPortalList(Null.NullString)); } - private FolderMappingInfo GetFolderMappingFromConfig(FolderTypeConfig node, int portalId) + /// + /// Get portals in specific culture. + /// + /// The culture code. + /// + public List GetPortalList(string cultureCode) { - var folderMapping = new FolderMappingInfo - { - PortalID = portalId, - MappingName = node.Name, - FolderProviderType = node.Provider, - }; + string cacheKey = string.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); + return CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), + c => CBO.FillCollection(DataProvider.Instance().GetPortals(cultureCode))); + } - foreach (FolderTypeSettingConfig settingNode in node.Settings) - { - var settingValue = this.EnsureSettingValue(folderMapping.FolderProviderType, settingNode, portalId); - folderMapping.FolderMappingSettings.Add(settingNode.Name, settingValue); - } + /// + /// Gets the portal settings dictionary. + /// + /// The portal ID. + /// portal settings. + public Dictionary GetPortalSettings(int portalId) + { + return GetPortalSettingsDictionary(portalId, string.Empty); + } - return folderMapping; + /// + /// Gets the portal settings dictionary. + /// + /// The portal ID. + /// The culture code. + /// portal settings. + public Dictionary GetPortalSettings(int portalId, string cultureCode) + { + return GetPortalSettingsDictionary(portalId, cultureCode); } - private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) + /// + /// Load info for a portal template. + /// + /// Full path to the portal template. + /// the culture code if any for the localization of the portal template. + /// A portal template. + public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) { - var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); + var template = new PortalTemplateInfo(templatePath, cultureCode); - switch (storageLocation) + if (!string.IsNullOrEmpty(cultureCode) && template.CultureCode != cultureCode) { - 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); + return null; } + + return template; } - private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, int portalId) + /// + /// Gets the portal space used bytes. + /// + /// The portal id. + /// Space used in bytes. + public long GetPortalSpaceUsedBytes(int portalId) { - var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); - var returnCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; - var clearCache = false; - foreach (XmlNode node in nodeEnabledLocales.SelectNodes("//locale")) + long size = 0; + IDataReader dr = DataProvider.Instance().GetPortalSpaceUsed(portalId); + try { - var cultureCode = node.InnerText; - var locale = LocaleController.Instance.GetLocale(cultureCode); - if (locale == null) - { - // if language does not exist in the installation, create it - locale = new Locale { Code = cultureCode, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(cultureCode).NativeName }; - Localization.SaveLanguage(locale, false); - clearCache = true; - } - - if (locale.Code != defaultLocale.Code) + if (dr.Read()) { - returnCollection.Add(locale.Code, locale); + if (dr["SpaceUsed"] != DBNull.Value) + { + size = Convert.ToInt64(dr["SpaceUsed"]); + } } } - - if (clearCache) + catch (Exception ex) { - DataCache.ClearHostCache(true); + Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); } - return returnCollection; + return size; } - private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) + /// + /// Verifies if there's enough space to upload a new file on the given portal. + /// + /// Id of the portal. + /// Size of the file being uploaded. + /// True if there's enough space available to upload the file. + public bool HasSpaceAvailable(int portalId, long fileSizeBytes) { - var listController = new ListController(); - Dictionary colDataTypes = listController.GetListEntryInfoDictionary("DataType"); - - int orderCounter = -1; - ProfilePropertyDefinition objProfileDefinition; - bool preferredTimeZoneFound = false; - foreach (XmlNode node in nodeProfileDefinitions.SelectNodes("//profiledefinition")) + int hostSpace; + if (portalId == -1) { - 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)) + hostSpace = 0; + } + else + { + PortalSettings ps = GetCurrentPortalSettingsInternal(); + if (ps != null && ps.PortalId == portalId) { - case 0: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.AllUsers; - break; - case 1: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.MembersOnly; - break; - case 2: - objProfileDefinition.DefaultVisibility = UserVisibilityMode.AdminOnly; - break; + hostSpace = ps.HostSpace; } - - if (objProfileDefinition.PropertyName == "PreferredTimeZone") + else { - preferredTimeZoneFound = true; + PortalInfo portal = this.GetPortal(portalId); + hostSpace = portal.HostSpace; } - - ProfileController.AddPropertyDefinition(objProfileDefinition); } - // 6.0 requires the old TimeZone property to be marked as Deleted - ProfilePropertyDefinition pdf = ProfileController.GetPropertyDefinitionByName(portalId, "TimeZone"); - if (pdf != null) + return (((this.GetPortalSpaceUsedBytes(portalId) + fileSizeBytes) / Math.Pow(1024, 2)) <= hostSpace) || hostSpace == 0; + } + + /// + /// Remaps the Special Pages such as Home, Profile, Search + /// to their localized versions. + /// + /// + /// + public void MapLocalizedSpecialPages(int portalId, string cultureCode) + { + DataCache.ClearHostCache(true); + DataProvider.Instance().EnsureLocalizationExists(portalId, cultureCode); + + PortalInfo defaultPortal = this.GetPortal(portalId, GetPortalDefaultLanguage(portalId)); + PortalInfo targetPortal = this.GetPortal(portalId, cultureCode); + + Locale targetLocale = LocaleController.Instance.GetLocale(cultureCode); + TabInfo tempTab; + if (defaultPortal.HomeTabId != Null.NullInteger) { - ProfileController.DeletePropertyDefinition(pdf); + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.HomeTabId, portalId, targetLocale); + if (tempTab != null) + { + targetPortal.HomeTabId = tempTab.TabID; + } } - // 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) + if (defaultPortal.LoginTabId != Null.NullInteger) { - orderCounter += 2; - - ListEntryInfo typeInfo = colDataTypes["DataType:TimeZoneInfo"]; - if (typeInfo == null) + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.LoginTabId, portalId, targetLocale); + if (tempTab != null) { - typeInfo = colDataTypes["DataType:Unknown"]; + targetPortal.LoginTabId = tempTab.TabID; } - - 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")) + if (defaultPortal.RegisterTabId != Null.NullInteger) { - HtmlUtils.WriteKeepAlive(); - var friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); - if (!string.IsNullOrEmpty(friendlyName)) + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.RegisterTabId, portalId, targetLocale); + if (tempTab != null) { - 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); - } + targetPortal.RegisterTabId = tempTab.TabID; } } - } - - 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; - var folderMappingController = FolderMappingController.Instance; - var xmlNodeList = nodeFolders.SelectNodes("//folder"); - if (xmlNodeList != null) + if (defaultPortal.SplashTabId != Null.NullInteger) { - foreach (XmlNode node in xmlNodeList) + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SplashTabId, portalId, targetLocale); + if (tempTab != null) { - HtmlUtils.WriteKeepAlive(); - var folderPath = XmlUtils.GetNodeValue(node.CreateNavigator(), "folderpath"); - - // First check if the folder exists - var objInfo = folderManager.GetFolder(portalId, folderPath); - - if (objInfo == null) - { - FolderMappingInfo folderMapping; - try - { - folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, folderPath) - ?? this.GetFolderMappingFromStorageLocation(portalId, node); - } - catch (Exception ex) - { - Logger.Error(ex); - folderMapping = folderMappingController.GetDefaultFolderMapping(portalId); - } - - var isProtected = XmlUtils.GetNodeValueBoolean(node, "isprotected"); - - try - { - // Save new folder - objInfo = folderManager.AddFolder(folderMapping, folderPath); - } - catch (Exception ex) - { - Logger.Error(ex); - - // Retry with default folderMapping - var defaultFolderMapping = folderMappingController.GetDefaultFolderMapping(portalId); - if (folderMapping.FolderMappingID != defaultFolderMapping.FolderMappingID) - { - objInfo = folderManager.AddFolder(defaultFolderMapping, folderPath); - } - else - { - throw; - } - } - - objInfo.IsProtected = isProtected; - - 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); + targetPortal.SplashTabId = tempTab.TabID; } } - } - - 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 (defaultPortal.UserTabId != Null.NullInteger) { - if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.UserTabId, portalId, targetLocale); + if (tempTab != null) { - settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); + targetPortal.UserTabId = tempTab.TabID; } + } - 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) + if (defaultPortal.SearchTabId != Null.NullInteger) + { + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SearchTabId, portalId, targetLocale); + if (tempTab != null) { - 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; - } + targetPortal.SearchTabId = tempTab.TabID; } + } - EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs + if (defaultPortal.Custom404TabId != Null.NullInteger) + { + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom404TabId, portalId, targetLocale); + if (tempTab != null) { - PortalId = portalID, - SettingName = settingName, - SettingValue = settingValue, - }); + targetPortal.Custom404TabId = tempTab.TabID; + } } - } - private void ParsePortalSettings(XmlNode nodeSettings, int portalId) - { - string currentCulture = GetActivePortalLanguage(portalId); - var objPortal = this.GetPortal(portalId); - objPortal.LogoFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "logofile")); - objPortal.FooterText = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "footertext"); - if (nodeSettings.SelectSingleNode("expirydate") != null) - { - objPortal.ExpiryDate = XmlUtils.GetNodeValueDate(nodeSettings, "expirydate", Null.NullDate); - } - - objPortal.UserRegistration = XmlUtils.GetNodeValueInt(nodeSettings, "userregistration"); - objPortal.BannerAdvertising = XmlUtils.GetNodeValueInt(nodeSettings, "banneradvertising"); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"))) + if (defaultPortal.Custom500TabId != Null.NullInteger) { - objPortal.Currency = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"); + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom500TabId, portalId, targetLocale); + if (tempTab != null) + { + targetPortal.Custom500TabId = tempTab.TabID; + } } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostfee"))) + if (defaultPortal.TermsTabId != Null.NullInteger) { - objPortal.HostFee = XmlUtils.GetNodeValueSingle(nodeSettings, "hostfee"); + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.TermsTabId, portalId, targetLocale); + if (tempTab != null) + { + targetPortal.TermsTabId = tempTab.TabID; + } } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostspace"))) + if (defaultPortal.PrivacyTabId != Null.NullInteger) { - objPortal.HostSpace = XmlUtils.GetNodeValueInt(nodeSettings, "hostspace"); + tempTab = TabController.Instance.GetTabByCulture(defaultPortal.PrivacyTabId, portalId, targetLocale); + if (tempTab != null) + { + targetPortal.PrivacyTabId = tempTab.TabID; + } } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "pagequota"))) - { - objPortal.PageQuota = XmlUtils.GetNodeValueInt(nodeSettings, "pagequota"); - } + this.UpdatePortalInternal(targetPortal, false); + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "userquota"))) + /// + /// Removes the related PortalLocalization record from the database, adds optional clear cache. + /// + /// + /// + /// + public void RemovePortalLocalization(int portalId, string cultureCode, bool clearCache = true) + { + DataProvider.Instance().RemovePortalLocalization(portalId, cultureCode); + if (clearCache) { - objPortal.UserQuota = XmlUtils.GetNodeValueInt(nodeSettings, "userquota"); + DataCache.ClearPortalCache(portalId, false); } + } - objPortal.BackgroundFile = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "backgroundfile"); - objPortal.PaymentProcessor = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "paymentprocessor"); + /// + /// Processess a template file for the new portal. + /// + /// PortalId of the new portal. + /// The template. + /// UserId for the portal administrator. This is used to assign roles to this user. + /// Flag to determine whether Module content is merged. + /// Flag to determine is the template is applied to an existing portal or a new one. + /// + /// The roles and settings nodes will only be processed on the portal template file. + /// + public void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + { + string templatePath, templateFile; + this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); - objPortal.DefaultLanguage = XmlUtils.GetNodeValue(nodeSettings, "defaultlanguage", "en-US"); - this.UpdatePortalInfo(objPortal); + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty))) + /// + /// Processes the resource file for the template file selected. + /// + /// New portal's folder. + /// full path to the resource file. + /// + /// The resource file is a zip file with the same name as the selected template file and with + /// an extension of .resources (to disable this file being downloaded). + /// For example: for template file "portal.template" a resource file "portal.template.resources" can be defined. + /// + public void ProcessResourceFileExplicit(string portalPath, string resoureceFile) + { + try { - UpdatePortalSetting(portalId, "DefaultPortalSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty), true, currentCulture); + FileSystemUtils.UnzipResources(new ZipInputStream(new FileStream(resoureceFile, FileMode.Open, FileAccess.Read)), portalPath); } - - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty))) + catch (Exception exc) { - UpdatePortalSetting(portalId, "DefaultAdminSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty), true, currentCulture); + Logger.Error(exc); } + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty))) - { - UpdatePortalSetting(portalId, "DefaultPortalContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty), true, currentCulture); - } + /// + /// Updates the portal expiry. + /// + /// The portal id. + /// The culture code. + public void UpdatePortalExpiry(int portalId, string cultureCode) + { + var portal = this.GetPortal(portalId, cultureCode); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty))) + if (portal.ExpiryDate == Null.NullDate) { - UpdatePortalSetting(portalId, "DefaultAdminContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty), true, currentCulture); + portal.ExpiryDate = DateTime.Now; } - // Enable Skin Widgets Setting - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty))) - { - UpdatePortalSetting(portalId, "EnableSkinWidgets", XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty)); - } + portal.ExpiryDate = portal.ExpiryDate.AddMonths(1); - // Enable AutoSAve feature - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty))) + this.UpdatePortalInfo(portal); + } + + /// + /// Updates basic portal information. + /// + /// + public void UpdatePortalInfo(PortalInfo portal) + { + this.UpdatePortalInternal(portal, true); + } + + internal static void EnsureRequiredEventLogTypesExist() + { + if (!DoesLogTypeExists(EventLogController.EventLogType.PAGE_NOT_FOUND_404.ToString())) { - UpdatePortalSetting(portalId, HtmlText_AutoSaveEnabled, XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty)); + // 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); - // Time to autosave, only if enableautosave exists - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty))) + // Add LogType + var logTypeConf = new LogTypeConfigInfo { - UpdatePortalSetting(portalId, HtmlText_TimeToAutoSave, XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty)); - } + 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); } - // Set Auto alias mapping - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL"))) + if (!DoesLogTypeExists(EventLogController.EventLogType.IP_LOGIN_BANNED.ToString())) { - UpdatePortalSetting(portalId, "PortalAliasMapping", XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL").ToUpperInvariant()); - } + // 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); - // Set Time Zone maping - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone))) - { - UpdatePortalSetting(portalId, "TimeZone", XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone)); + // 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 (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled"))) + if (!DoesLogTypeExists(EventLogController.EventLogType.TABURL_CREATED.ToString())) { - UpdatePortalSetting(portalId, "ContentLocalizationEnabled", XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled")); - } + 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); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled"))) - { - UpdatePortalSetting(portalId, "InlineEditorEnabled", XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled")); - } + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL updated"; + LogController.Instance.AddLogType(logTypeInfo); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablepopups"))) - { - UpdatePortalSetting(portalId, "EnablePopUps", XmlUtils.GetNodeValue(nodeSettings, "enablepopups")); - } + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; + LogController.Instance.AddLogType(logTypeInfo); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled"))) - { - UpdatePortalSetting(portalId, "HideFoldersEnabled", XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled")); - } + // 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); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode"))) - { - UpdatePortalSetting(portalId, "ControlPanelMode", XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode")); - } + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity"))) - { - UpdatePortalSetting(portalId, "ControlPanelSecurity", XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity")); + logTypeUrlConf.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + LogController.Instance.AddLogTypeConfigInfo(logTypeUrlConf); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility"))) + if (!DoesLogTypeExists(EventLogController.EventLogType.SCRIPT_COLLISION.ToString())) { - UpdatePortalSetting(portalId, "ControlPanelVisibility", XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility")); - } + // 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); - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty))) - { - UpdatePortalSetting(portalId, "PageHeadText", XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty)); + // 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); } + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty))) - { - UpdatePortalSetting(portalId, "InjectModuleHyperLink", XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty)); - } + protected override Func GetFactory() + { + return () => new PortalController(); + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty))) + 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) { - UpdatePortalSetting(portalId, "AddCompatibleHttpHeader", XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty)); + administratorRoleId = CreateRole(portalId, "Administrators", "Administrators of this Website", 0, 0, "M", 0, 0, "N", false, false); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty))) + if (registeredRoleId == -1) { - UpdatePortalSetting(portalId, "AllowUserUICulture", XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty)); + registeredRoleId = CreateRole(portalId, "Registered Users", "Registered Users", 0, 0, "M", 0, 0, "N", false, true); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty))) + if (subscriberRoleId == -1) { - UpdatePortalSetting(portalId, "EnableBrowserLanguage", XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty)); + subscriberRoleId = CreateRole(portalId, "Subscribers", "A public role for site subscriptions", 0, 0, "M", 0, 0, "N", true, true); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", string.Empty))) + if (unverifiedRoleId == -1) { - UpdatePortalSetting(portalId, "ShowCookieConsent", XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", "False")); + CreateRole(portalId, "Unverified Users", "Unverified Users", 0, 0, "M", 0, 0, "N", false, false); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty))) - { - UpdatePortalSetting(portalId, "CookieMoreLink", XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty), true, currentCulture); - } + 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); + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", string.Empty))) + private static string CreateProfileDefinitions(int portalId, string templateFilePath) + { + string strMessage = Null.NullString; + try { - UpdatePortalSetting(portalId, "DataConsentActive", XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", "False")); - } + // add profile definitions + XmlDocument xmlDoc = new XmlDocument { XmlResolver = null }; - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty))) + // 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) { - UpdatePortalSetting(portalId, "DataConsentTermsLastChange", XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty), true, currentCulture); + strMessage = Localization.GetString("CreateProfileDefinitions.Error"); + Exceptions.LogException(ex); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty))) + return strMessage; + } + + private static int CreatePortal(string portalName, string homeDirectory, string cultureCode) + { + // add portal + int PortalId = -1; + try { - UpdatePortalSetting(portalId, "DataConsentConsentRedirect", XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty), true, currentCulture); - } + // 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; - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty))) + 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) { - UpdatePortalSetting(portalId, "DataConsentUserDeleteAction", XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty), true, currentCulture); + Exceptions.LogException(ex); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty))) + try { - UpdatePortalSetting(portalId, "DataConsentDelay", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty), true, currentCulture); + EnsureRequiredEventLogTypesExist(); } - - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty))) + catch (Exception) { - UpdatePortalSetting(portalId, "DataConsentDelayMeasurement", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty), true, currentCulture); + // should be no exception, but suppress just in case } + return PortalId; } - private void ParseRoleGroups(XPathNavigator nav, int portalID, int administratorId) + private static int CreateRole(RoleInfo role) { - var administratorRoleId = -1; - var registeredRoleId = -1; - var subscriberRoleId = -1; - var unverifiedRoleId = -1; + int roleId; - foreach (XPathNavigator roleGroupNav in nav.Select("rolegroup")) + // First check if the role exists + var objRoleInfo = RoleController.Instance.GetRole(role.PortalID, r => r.RoleName == role.RoleName); + if (objRoleInfo == null) { - HtmlUtils.WriteKeepAlive(); - var roleGroup = CBO.DeserializeObject(new StringReader(roleGroupNav.OuterXml)); - if (roleGroup.RoleGroupName != "GlobalRoles") - { - roleGroup.PortalID = portalID; - CreateRoleGroup(roleGroup); - } - - foreach (var role in roleGroup.Roles.Values) - { - role.PortalID = portalID; - role.RoleGroupID = roleGroup.RoleGroupID; - role.Status = RoleStatus.Approved; - switch (role.RoleType) - { - case RoleType.Administrator: - administratorRoleId = CreateRole(role); - break; - case RoleType.RegisteredUser: - registeredRoleId = CreateRole(role); - break; - case RoleType.Subscriber: - subscriberRoleId = CreateRole(role); - break; - case RoleType.None: - CreateRole(role); - break; - case RoleType.UnverifiedUser: - unverifiedRoleId = CreateRole(role); - break; - } - } + roleId = RoleController.Instance.AddRole(role); + } + else + { + roleId = objRoleInfo.RoleID; } - CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); + return roleId; + } - // update portal setup - var portal = this.GetPortal(portalID); - this.UpdatePortalSetup( - portalID, - administratorId, - administratorRoleId, - registeredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalID)); + private static int CreateRole(int portalId, string roleName, string description, float serviceFee, int billingPeriod, string billingFrequency, float trialFee, int trialPeriod, string trialFrequency, + bool isPublic, bool isAuto) + { + RoleInfo objRoleInfo = new RoleInfo(); + objRoleInfo.PortalID = portalId; + objRoleInfo.RoleName = roleName; + objRoleInfo.RoleGroupID = Null.NullInteger; + objRoleInfo.Description = description; + objRoleInfo.ServiceFee = Convert.ToSingle(serviceFee < 0 ? 0 : serviceFee); + objRoleInfo.BillingPeriod = billingPeriod; + objRoleInfo.BillingFrequency = billingFrequency; + objRoleInfo.TrialFee = Convert.ToSingle(trialFee < 0 ? 0 : trialFee); + objRoleInfo.TrialPeriod = trialPeriod; + objRoleInfo.TrialFrequency = trialFrequency; + objRoleInfo.IsPublic = isPublic; + objRoleInfo.AutoAssignment = isAuto; + return CreateRole(objRoleInfo); } - private void ParseRoles(XPathNavigator nav, int portalID, int administratorId) + private static void CreateRoleGroup(RoleGroupInfo roleGroup) { - var administratorRoleId = -1; - var registeredRoleId = -1; - var subscriberRoleId = -1; - var unverifiedRoleId = -1; + // First check if the role exists + var objRoleGroupInfo = RoleController.GetRoleGroupByName(roleGroup.PortalID, roleGroup.RoleGroupName); - foreach (XPathNavigator roleNav in nav.Select("role")) + if (objRoleGroupInfo == null) { - HtmlUtils.WriteKeepAlive(); - var role = CBO.DeserializeObject(new StringReader(roleNav.OuterXml)); - role.PortalID = portalID; - role.RoleGroupID = Null.NullInteger; - switch (role.RoleType) - { - case RoleType.Administrator: - administratorRoleId = CreateRole(role); - break; - case RoleType.RegisteredUser: - registeredRoleId = CreateRole(role); - break; - case RoleType.Subscriber: - subscriberRoleId = CreateRole(role); - break; - case RoleType.None: - CreateRole(role); - break; - case RoleType.UnverifiedUser: - unverifiedRoleId = CreateRole(role); - break; - } + roleGroup.RoleGroupID = RoleController.AddRoleGroup(roleGroup); + } + else + { + roleGroup.RoleGroupID = objRoleGroupInfo.RoleGroupID; } - - // create required roles if not already created - CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); - - // update portal setup - var portal = this.GetPortal(portalID); - this.UpdatePortalSetup( - portalID, - administratorId, - administratorRoleId, - registeredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalID)); } - private void ParseTab(XmlNode nodeTab, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, ref Hashtable hModules, ref Hashtable hTabs, bool isNewPortal) + private static void DeletePortalInternal(int portalId) { - TabInfo tab = null; - string strName = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "name"); - var portal = this.GetPortal(portalId); - if (!string.IsNullOrEmpty(strName)) + UserController.DeleteUsers(portalId, false, true); + + var portal = Instance.GetPortal(portalId); + + DataProvider.Instance().DeletePortalInfo(portalId); + + try { - if (!isNewPortal) // running from wizard: try to find the tab by path + var log = new LogInfo { - string parenttabname = string.Empty; - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) - { - parenttabname = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; - } + 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); + } - if (hTabs[parenttabname + strName] != null) - { - tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parenttabname + strName]), portalId, false); - } - } + DataCache.ClearHostCache(true); - if (tab == null || isNewPortal) - { - tab = TabController.DeserializeTab(nodeTab, null, hTabs, portalId, isAdminTemplate, mergeTabs, hModules); - } + // queue remove portal from search index + var document = new SearchDocumentToDelete + { + PortalId = portalId, + }; - // when processing the template we should try and identify the Admin tab - var logType = "AdminTab"; - if (tab.TabName == "Admin") - { - portal.AdminTabId = tab.TabID; - } + DataProvider.Instance().AddSearchDeletedItems(document); + } - // when processing the template we can find: hometab, usertab, logintab - switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", string.Empty).ToLowerInvariant()) - { - case "splashtab": - portal.SplashTabId = tab.TabID; - logType = "SplashTab"; - break; - case "hometab": - portal.HomeTabId = tab.TabID; - logType = "HomeTab"; - break; - case "logintab": - portal.LoginTabId = tab.TabID; - logType = "LoginTab"; - break; - case "usertab": - portal.UserTabId = tab.TabID; - logType = "UserTab"; - break; - case "searchtab": - portal.SearchTabId = tab.TabID; - logType = "SearchTab"; - break; - case "404tab": - portal.Custom404TabId = tab.TabID; - logType = "Custom404Tab"; - break; - case "500tab": - portal.Custom500TabId = tab.TabID; - logType = "Custom500Tab"; - break; - case "termstab": - portal.TermsTabId = tab.TabID; - logType = "TermsTabId"; - break; - case "privacytab": - portal.PrivacyTabId = tab.TabID; - logType = "PrivacyTabId"; - break; - } + private static bool DoesLogTypeExists(string logTypeKey) + { + LogTypeInfo logType; + Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + logTypeDictionary.TryGetValue(logTypeKey, out logType); + if (logType == null) + { + return false; + } - this.UpdatePortalSetup( - portalId, - portal.AdministratorId, - portal.AdministratorRoleId, - portal.RegisteredRoleId, - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.AdminTabId, - GetActivePortalLanguage(portalId)); - EventLogController.Instance.AddLog( - logType, - tab.TabID.ToString(), - GetCurrentPortalSettingsInternal(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.PORTAL_SETTING_UPDATED); + return true; + } + + private static PortalSettings GetCurrentPortalSettingsInternal() + { + PortalSettings objPortalSettings = null; + if (HttpContext.Current != null) + { + objPortalSettings = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; } + + return objPortalSettings; } - private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + private static PortalInfo GetPortalInternal(int portalId, string cultureCode) { - // used to control if modules are true modules or instances - // will hold module ID from template / new module ID so new instances can reference right moduleid - // only first one from the template will be create as a true module, - // others will be moduleinstances (tabmodules) - Hashtable hModules = new Hashtable(); - Hashtable hTabs = new Hashtable(); + return Instance.GetPortalList(cultureCode).SingleOrDefault(p => p.PortalID == portalId); + } - // if running from wizard we need to pre populate htabs with existing tabs so ParseTab - // can find all existing ones - if (!isNewPortal) + private static object GetPortalDefaultLanguageCallBack(CacheItemArgs cacheItemArgs) + { + int portalID = (int)cacheItemArgs.ParamList[0]; + return DataProvider.Instance().GetPortalDefaultLanguage(portalID); + } + + private static object GetPortalDictionaryCallback(CacheItemArgs cacheItemArgs) + { + var portalDic = new Dictionary(); + if (Host.Host.PerformanceSetting != Globals.PerformanceSettings.NoCaching) { - Hashtable hTabNames = new Hashtable(); - foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) + // get all tabs + int intField = 0; + IDataReader dr = DataProvider.Instance().GetTabPaths(Null.NullInteger, Null.NullString); + try { - TabInfo objTab = tabPair.Value; - if (!objTab.IsDeleted) + while (dr.Read()) { - var tabname = objTab.TabName; - if (!Null.IsNull(objTab.ParentId)) - { - tabname = Convert.ToString(hTabNames[objTab.ParentId]) + "/" + objTab.TabName; - } - - hTabNames.Add(objTab.TabID, tabname); + // add to dictionary + portalDic[Convert.ToInt32(Null.SetNull(dr["TabID"], intField))] = Convert.ToInt32(Null.SetNull(dr["PortalID"], intField)); } } - - // when parsing tabs we will need tabid given tabname - foreach (int i in hTabNames.Keys) + catch (Exception exc) { - if (hTabs[hTabNames[i]] == null) - { - hTabs.Add(hTabNames[i], i); - } + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); } + } - hTabNames.Clear(); + return portalDic; + } + + private static object GetPortalSettingsDictionaryCallback(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var dicSettings = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + if (portalId <= -1) + { + return dicSettings; } - foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab")) + var cultureCode = Convert.ToString(cacheItemArgs.ParamList[1]); + if (string.IsNullOrEmpty(cultureCode)) { - HtmlUtils.WriteKeepAlive(); - this.ParseTab(nodeTab, portalId, isAdminTemplate, mergeTabs, ref hModules, ref hTabs, isNewPortal); + cultureCode = GetActivePortalLanguage(portalId); } - // Process tabs that are linked to tabs - foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'Tab']")) + var dr = DataProvider.Instance().GetPortalSettings(portalId, cultureCode); + try { - HtmlUtils.WriteKeepAlive(); - int tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); - string tabPath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); - if (tabId > Null.NullInteger) + while (dr.Read()) { - TabInfo objTab = TabController.Instance.GetTab(tabId, portalId, false); - objTab.Url = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString).ToString(); - TabController.Instance.UpdateTab(objTab); + if (dr.IsDBNull(1)) + { + continue; + } + + var key = dr.GetString(0); + if (dicSettings.ContainsKey(key)) + { + dicSettings[key] = dr.GetString(1); + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString(), + }; + log.AddProperty("Duplicate PortalSettings Key", key); + LogController.Instance.AddLog(log); + } + else + { + dicSettings.Add(key, dr.GetString(1)); + } } } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + CBO.CloseDataReader(dr, true); + } - var folderManager = FolderManager.Instance; + return dicSettings; + } + + private static void ParseFiles(XmlNodeList nodeFiles, int portalId, FolderInfo folder) + { var fileManager = FileManager.Instance; - // Process tabs that are linked to files - foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'File']")) + foreach (XmlNode node in nodeFiles) { - HtmlUtils.WriteKeepAlive(); - var tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); - var filePath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); - if (tabId > Null.NullInteger) - { - var objTab = TabController.Instance.GetTab(tabId, portalId, false); + var fileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "filename"); - var fileName = Path.GetFileName(filePath); + // First check if the file exists + var file = fileManager.GetFile(folder, fileName); - var folderPath = filePath.Substring(0, filePath.LastIndexOf(fileName)); - var folder = folderManager.GetFolder(portalId, folderPath); + if (file != null) + { + continue; + } - var file = fileManager.GetFile(folder, fileName); + file = new FileInfo + { + PortalId = portalId, + FileName = fileName, + Extension = XmlUtils.GetNodeValue(node.CreateNavigator(), "extension"), + Size = XmlUtils.GetNodeValueInt(node, "size"), + Width = XmlUtils.GetNodeValueInt(node, "width"), + Height = XmlUtils.GetNodeValueInt(node, "height"), + ContentType = XmlUtils.GetNodeValue(node.CreateNavigator(), "contenttype"), + SHA1Hash = XmlUtils.GetNodeValue(node.CreateNavigator(), "sha1hash"), + FolderId = folder.FolderID, + Folder = folder.FolderPath, + Title = string.Empty, + StartDate = DateTime.Now, + EndDate = Null.NullDate, + EnablePublishPeriod = false, + ContentItemID = Null.NullInteger, + }; - objTab.Url = "FileID=" + file.FileId; - TabController.Instance.UpdateTab(objTab); + // Save new File + try + { + // Initially, install files are on local system, then we need the Standard folder provider to read the content regardless the target folderprovider + using (var fileContent = FolderProvider.Instance("StandardFolderProvider").GetFileStream(file)) + { + var contentType = FileContentTypeManager.Instance.GetContentType(Path.GetExtension(fileName)); + var userId = UserController.Instance.GetCurrentUserInfo().UserID; + file.FileId = fileManager.AddFile(folder, fileName, fileContent, false, false, true, contentType, userId).FileId; + } + + fileManager.UpdateFile(file); + } + catch (InvalidFileExtensionException ex) // when the file is not allowed, we should not break parse process, but just log the error. + { + Logger.Error(ex.Message); } } } - private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) - { - LocaleCollection localeCollection; - this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); - } - - private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) + private static void ParseFolderPermissions(XmlNodeList nodeFolderPermissions, int portalId, FolderInfo folder) { - CachingProvider.DisableCacheExpiration(); + PermissionController permissionController = new PermissionController(); + int permissionId = 0; - var xmlPortal = new XmlDocument { XmlResolver = null }; - IFolderInfo objFolder; - try - { - xmlPortal.Load(Path.Combine(templatePath, templateFile)); - } - catch (Exception ex) + // Clear the current folder permissions + folder.FolderPermissions.Clear(); + foreach (XmlNode xmlFolderPermission in nodeFolderPermissions) { - Logger.Error(ex); + string permissionKey = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissionkey"); + string permissionCode = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "permissioncode"); + string roleName = XmlUtils.GetNodeValue(xmlFolderPermission.CreateNavigator(), "rolename"); + bool allowAccess = XmlUtils.GetNodeValueBoolean(xmlFolderPermission, "allowaccess"); + foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey(permissionCode, permissionKey)) + { + 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: + RoleInfo objRole = RoleController.Instance.GetRole(portalId, r => r.RoleName == roleName); + if (objRole != null) + { + roleId = objRole.RoleID; + } + + break; + } + + // if role was found add, otherwise ignore + if (roleId != int.MinValue) + { + var folderPermission = new FolderPermissionInfo + { + FolderID = folder.FolderID, + PermissionID = permissionId, + RoleID = roleId, + UserID = Null.NullInteger, + AllowAccess = allowAccess, + }; + + bool canAdd = !folder.FolderPermissions.Cast() + .Any(fp => fp.FolderID == folderPermission.FolderID + && fp.PermissionID == folderPermission.PermissionID + && fp.RoleID == folderPermission.RoleID + && fp.UserID == folderPermission.UserID); + if (canAdd) + { + folder.FolderPermissions.Add(folderPermission); + } + } } - var node = xmlPortal.SelectSingleNode("//portal/settings"); - if (node != null && isNewPortal) + FolderPermissionController.SaveFolderPermissions(folder); + } + + private static void EnsureRequiredProvidersForFolderTypes() + { + if (ComponentFactory.GetComponent() == null) { - HtmlUtils.WriteKeepAlive(); - this.ParsePortalSettings(node, portalId); + ComponentFactory.InstallComponents(new ProviderInstaller("cryptography", typeof(CryptographyProvider), typeof(FipsCompilanceCryptographyProvider))); + ComponentFactory.RegisterComponentInstance(new FipsCompilanceCryptographyProvider()); } + } - node = xmlPortal.SelectSingleNode("//locales"); - if (node != null && isNewPortal) + private static void EnsureFolderProviderRegistration(FolderTypeConfig folderTypeConfig, XmlDocument webConfig) + where TAbstract : class + { + var providerBusinessClassNode = webConfig.SelectSingleNode("configuration/dotnetnuke/folder/providers/add[@name='" + folderTypeConfig.Provider + "']"); + + var typeClass = Type.GetType(providerBusinessClassNode.Attributes["type"].Value); + if (typeClass != null) { - HtmlUtils.WriteKeepAlive(); - localeCollection = ParseEnabledLocales(node, portalId); + ComponentFactory.RegisterComponentInstance(folderTypeConfig.Provider, Activator.CreateInstance(typeClass)); } - else + } + + private static bool EnableBrowserLanguageInDefault(int portalId) + { + bool retValue = Null.NullBoolean; + try { - var portalInfo = Instance.GetPortal(portalId); - var defaultLocale = LocaleController.Instance.GetLocale(portalInfo.DefaultLanguage); - if (defaultLocale == null) + string setting; + GetPortalSettingsDictionary(portalId, Localization.SystemLocale).TryGetValue("EnableBrowserLanguage", out setting); + if (string.IsNullOrEmpty(setting)) { - defaultLocale = new Locale { Code = portalInfo.DefaultLanguage, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(portalInfo.DefaultLanguage).NativeName }; - Localization.SaveLanguage(defaultLocale, false); + retValue = Host.Host.EnableBrowserLanguage; + } + else + { + retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); } - - localeCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; } - - node = xmlPortal.SelectSingleNode("//portal/rolegroups"); - if (node != null) + catch (Exception exc) { - this.ParseRoleGroups(node.CreateNavigator(), portalId, administratorId); + Logger.Error(exc); } - node = xmlPortal.SelectSingleNode("//portal/roles"); - if (node != null) - { - this.ParseRoles(node.CreateNavigator(), portalId, administratorId); - } + return retValue; + } - node = xmlPortal.SelectSingleNode("//portal/portalDesktopModules"); - if (node != null) - { - ParsePortalDesktopModules(node.CreateNavigator(), portalId); - } + private static Dictionary GetPortalSettingsDictionary(int portalId, string cultureCode) + { + var httpContext = HttpContext.Current; - node = xmlPortal.SelectSingleNode("//portal/folders"); - if (node != null) + if (string.IsNullOrEmpty(cultureCode) && portalId > -1) { - this.ParseFolders(node, portalId); + cultureCode = GetActivePortalLanguageFromHttpContext(httpContext, portalId); } - node = xmlPortal.SelectSingleNode("//portal/extensionUrlProviders"); - if (node != null) + // Get PortalSettings from Context or from cache + var dictionaryKey = string.Format(HttpContextKeyPortalSettingsDictionary, portalId, cultureCode); + Dictionary dictionary = null; + if (httpContext != null) { - this.ParseExtensionUrlProviders(node.CreateNavigator(), portalId); + dictionary = httpContext.Items[dictionaryKey] as Dictionary; } - var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - - if (FolderManager.Instance.GetFolder(portalId, string.Empty) == null) + if (dictionary == null) { - objFolder = FolderManager.Instance.AddFolder(defaultFolderMapping, string.Empty); - objFolder.IsProtected = true; - FolderManager.Instance.UpdateFolder(objFolder); - - this.AddFolderPermissions(portalId, objFolder.FolderID); + var cacheKey = string.Format(DataCache.PortalSettingsCacheKey, portalId, cultureCode); + dictionary = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.PortalSettingsCacheTimeOut, + DataCache.PortalSettingsCachePriority, portalId, cultureCode), + GetPortalSettingsDictionaryCallback, + true); + if (httpContext != null) + { + httpContext.Items[dictionaryKey] = dictionary; + } } - if (FolderManager.Instance.GetFolder(portalId, "Templates/") == null) - { - var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Templates/") ?? defaultFolderMapping; - objFolder = FolderManager.Instance.AddFolder(folderMapping, "Templates/"); - objFolder.IsProtected = true; - FolderManager.Instance.UpdateFolder(objFolder); + return dictionary; + } - // AddFolderPermissions(PortalId, objFolder.FolderID); - } + private static string GetActivePortalLanguageFromHttpContext(HttpContext httpContext, int portalId) + { + var cultureCode = string.Empty; - // force creation of users folder if not present on template - if (FolderManager.Instance.GetFolder(portalId, "Users/") == null) + // Lookup culturecode but cache it in the HttpContext for performance + var activeLanguageKey = string.Format("ActivePortalLanguage{0}", portalId); + if (httpContext != null) { - var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Users/") ?? defaultFolderMapping; - objFolder = FolderManager.Instance.AddFolder(folderMapping, "Users/"); - objFolder.IsProtected = true; - FolderManager.Instance.UpdateFolder(objFolder); - - // AddFolderPermissions(PortalId, objFolder.FolderID); + cultureCode = (string)httpContext.Items[activeLanguageKey]; } - if (mergeTabs == PortalTemplateModuleAction.Replace) + if (string.IsNullOrEmpty(cultureCode)) { - foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) + cultureCode = GetActivePortalLanguage(portalId); + if (httpContext != null) { - var objTab = tabPair.Value; - objTab.TabName = objTab.TabName + "_old"; - objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName); - objTab.IsDeleted = true; - TabController.Instance.UpdateTab(objTab); - foreach (KeyValuePair modulePair in ModuleController.Instance.GetTabModules(objTab.TabID)) - { - var objModule = modulePair.Value; - ModuleController.Instance.DeleteTabModule(objModule.TabID, objModule.ModuleID, false); - } + httpContext.Items[activeLanguageKey] = cultureCode; } } - node = xmlPortal.SelectSingleNode("//portal/tabs"); - if (node != null) + return cultureCode; + } + + private static LocaleCollection ParseEnabledLocales(XmlNode nodeEnabledLocales, int portalId) + { + var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); + var returnCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; + var clearCache = false; + foreach (XmlNode node in nodeEnabledLocales.SelectNodes("//locale")) { - string version = xmlPortal.DocumentElement.GetAttribute("version"); - if (version != "5.0") + var cultureCode = node.InnerText; + var locale = LocaleController.Instance.GetLocale(cultureCode); + if (locale == null) { - XmlDocument xmlAdmin = new XmlDocument { XmlResolver = null }; - try - { - string path = Path.Combine(templatePath, "admin.template"); - if (!File.Exists(path)) - { - // if the template is a merged copy of a localized templte the - // admin.template may be one director up - path = Path.Combine(templatePath, "..\admin.template"); - } - - xmlAdmin.Load(path); + // if language does not exist in the installation, create it + locale = new Locale { Code = cultureCode, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(cultureCode).NativeName }; + Localization.SaveLanguage(locale, false); + clearCache = true; + } - XmlNode adminNode = xmlAdmin.SelectSingleNode("//portal/tabs"); - foreach (XmlNode adminTabNode in adminNode.ChildNodes) - { - node.AppendChild(xmlPortal.ImportNode(adminTabNode, true)); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } + if (locale.Code != defaultLocale.Code) + { + returnCollection.Add(locale.Code, locale); } + } - this.ParseTabs(node, portalId, false, mergeTabs, isNewPortal); + if (clearCache) + { + DataCache.ClearHostCache(true); } - CachingProvider.EnableCacheExpiration(); + return returnCollection; } - private void PrepareLocalizedPortalTemplate(PortalTemplateInfo template, out string templatePath, out string templateFile) + private static void ParseProfileDefinitions(XmlNode nodeProfileDefinitions, int portalId) { - if (string.IsNullOrEmpty(template.LanguageFilePath)) + var listController = new ListController(); + Dictionary colDataTypes = listController.GetListEntryInfoDictionary("DataType"); + + int orderCounter = -1; + ProfilePropertyDefinition objProfileDefinition; + bool preferredTimeZoneFound = false; + foreach (XmlNode node in nodeProfileDefinitions.SelectNodes("//profiledefinition")) { - // no language to merge - templatePath = Path.GetDirectoryName(template.TemplateFilePath) + @"\"; - templateFile = Path.GetFileName(template.TemplateFilePath); - return; - } + orderCounter += 2; + ListEntryInfo typeInfo; + if (!colDataTypes.TryGetValue("DataType:" + XmlUtils.GetNodeValue(node.CreateNavigator(), "datatype"), out typeInfo)) + { + typeInfo = colDataTypes["DataType:Unknown"]; + } - templatePath = Path.Combine(TestableGlobals.Instance.HostMapPath, "MergedTemplate"); - Directory.CreateDirectory(templatePath); + 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"); - var buffer = new StringBuilder(File.ReadAllText(template.TemplateFilePath)); + 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; + } - XDocument languageDoc; - using (var reader = PortalTemplateIO.Instance.OpenTextReader(template.LanguageFilePath)) + 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) { - languageDoc = XDocument.Load(reader); + ProfileController.DeletePropertyDefinition(pdf); } - var localizedData = languageDoc.Descendants("data"); - - foreach (var item in localizedData) + // 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) { - var nameAttribute = item.Attribute("name"); - if (nameAttribute != null) - { - string name = nameAttribute.Value; - var valueElement = item.Descendants("value").FirstOrDefault(); - if (valueElement != null) - { - string value = valueElement.Value; + orderCounter += 2; - buffer = buffer.Replace(string.Format("[{0}]", name), value); - } + ListEntryInfo typeInfo = colDataTypes["DataType:TimeZoneInfo"]; + if (typeInfo == null) + { + typeInfo = colDataTypes["DataType:Unknown"]; } - } - templateFile = string.Format("Merged-{0}-{1}", template.CultureCode, Path.GetFileName(template.TemplateFilePath)); - - File.WriteAllText(Path.Combine(templatePath, templateFile), buffer.ToString()); + 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 void UpdatePortalInternal(PortalInfo portal, bool clearCache) + private static void ParsePortalDesktopModules(XPathNavigator nav, int portalID) { - var processorPassword = portal.ProcessorPassword; - if (!string.IsNullOrEmpty(processorPassword)) + foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) { - processorPassword = Security.FIPSCompliant.EncryptAES(processorPassword, Config.GetDecryptionkey(), Host.Host.GUID); - } - - DataProvider.Instance().UpdatePortalInfo( - portal.PortalID, - portal.PortalGroupID, - portal.PortalName, - portal.LogoFile, - portal.FooterText, - portal.ExpiryDate, - portal.UserRegistration, - portal.BannerAdvertising, - portal.Currency, - portal.AdministratorId, - portal.HostFee, - portal.HostSpace, - portal.PageQuota, - portal.UserQuota, - portal.PaymentProcessor, - portal.ProcessorUserId, - processorPassword, - portal.Description, - portal.KeyWords, - portal.BackgroundFile, - 0, // site log history function has been removed. - portal.SplashTabId, - portal.HomeTabId, - portal.LoginTabId, - portal.RegisterTabId, - portal.UserTabId, - portal.SearchTabId, - portal.Custom404TabId, - portal.Custom500TabId, - portal.TermsTabId, - portal.PrivacyTabId, - portal.DefaultLanguage, - portal.HomeDirectory, - UserController.Instance.GetCurrentUserInfo().UserID, - portal.CultureCode); + 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); + } + } - EventLogController.Instance.AddLog("PortalId", portal.PortalID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); + 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; + } + } - // ensure a localization item exists (in case a new default language has been set) - DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, portal.DefaultLanguage); + permissions.Add(desktopModulePermission); + } - // clear portal cache - if (clearCache) - { - DataCache.ClearHostCache(true); + DesktopModuleController.AddDesktopModuleToPortal(portalID, desktopModule, permissions, false); + } + } } } - 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) - { - DataProvider.Instance().UpdatePortalSetup( - portalId, - administratorId, - administratorRoleId, - registeredRoleId, - splashTabId, - homeTabId, - loginTabId, - registerTabId, - userTabId, - searchTabId, - custom404TabId, - custom500TabId, - termsTabId, - privacyTabId, - adminTabId, - cultureCode); - EventLogController.Instance.AddLog("PortalId", portalId.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); - DataCache.ClearHostCache(true); - } - - /// - /// Creates the portal. - /// - /// Name of the portal. - /// The obj admin user. - /// The description. - /// The key words. - /// - /// The home directory. - /// The portal alias. - /// The server path. - /// The child path. - /// if set to true means the portal is child portal. - /// Portal id. - public int CreatePortal(string portalName, int adminUserId, string description, string keyWords, PortalTemplateInfo template, - string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) + private static void UpdatePortalSettingInternal(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) { - // Attempt to create a new portal - int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); - - // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. - if (HttpContext.Current != null) - { - HttpContext.Current.Items.Add("CreatingPortalId", portalId); - } - - string message = Null.NullString; + string currentSetting = GetPortalSetting(settingName, portalID, string.Empty, cultureCode); - if (portalId != -1) + if (currentSetting != settingValue) { - // add administrator - int administratorId = adminUserId; - var adminUser = new UserInfo(); - - // add userportal record - UserController.AddUserPortal(portalId, administratorId); - - // retrieve existing administrator - try + if (isSecure && !string.IsNullOrEmpty(settingName) && !string.IsNullOrEmpty(settingValue)) { - adminUser = UserController.GetUserById(portalId, administratorId); + settingValue = Security.FIPSCompliant.EncryptAES(settingValue, Config.GetDecryptionkey(), Host.Host.GUID); } - catch (Exception Exc) + + 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) { - Logger.Error(Exc); + 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; + } } - if (administratorId > 0) + EventManager.Instance.OnPortalSettingUpdated(new PortalSettingUpdatedEventArgs { - this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); - } + PortalId = portalID, + SettingName = settingName, + SettingValue = settingValue, + }); } - else + } + + private void AddFolderPermissions(int portalId, int folderId) + { + var portal = this.GetPortal(portalId); + var folderManager = FolderManager.Instance; + var folder = folderManager.GetFolder(folderId); + var permissionController = new PermissionController(); + foreach (PermissionInfo permission in permissionController.GetPermissionByCodeAndKey("SYSTEM_FOLDER", string.Empty)) { - message += Localization.GetString("CreatePortal.Error"); - throw new Exception(message); + var folderPermission = new FolderPermissionInfo(permission) + { + FolderID = folder.FolderID, + RoleID = portal.AdministratorRoleId, + AllowAccess = true, + }; + + folder.FolderPermissions.Add(folderPermission); + if (permission.PermissionKey == "READ") + { + // add READ permissions to the All Users Role + folderManager.AddAllUserReadPermission(folder, permission); + } } + FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + } + + 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) + { + // Add default workflows try { - EnsureRequiredEventLogTypesExist(); + SystemWorkflowManager.Instance.CreateSystemWorkflows(portalId); } - catch (Exception) + catch (Exception ex) { - // should be no exception, but suppress just in case + Exceptions.LogException(ex); } - // remove the portal id from http context as there is no exception. - if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) + string templatePath, templateFile; + this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); + string mergedTemplatePath = Path.Combine(templatePath, templateFile); + + if (string.IsNullOrEmpty(homeDirectory)) { - HttpContext.Current.Items.Remove("CreatingPortalId"); + homeDirectory = "Portals/" + portalId; } - return portalId; - } - - /// - /// Creates the portal. - /// - /// Name of the portal. - /// The obj admin user. - /// The description. - /// The key words. - /// - /// The home directory. - /// The portal alias. - /// The server path. - /// The child path. - /// if set to true means the portal is child portal. - /// Portal id. - public int CreatePortal(string portalName, UserInfo adminUser, string description, string keyWords, PortalTemplateInfo template, - string homeDirectory, string portalAlias, string serverPath, string childPath, bool isChildPortal) - { - // Attempt to create a new portal - int portalId = CreatePortal(portalName, homeDirectory, template.CultureCode); + string mappedHomeDirectory = string.Format(Globals.ApplicationMapPath + "\\" + homeDirectory + "\\").Replace("/", "\\"); - // Log the portal if into http context, if exception occurred in next step, we can remove the portal which is not really created. - if (HttpContext.Current != null) + if (Directory.Exists(mappedHomeDirectory)) { - HttpContext.Current.Items.Add("CreatingPortalId", portalId); + message += string.Format(Localization.GetString("CreatePortalHomeFolderExists.Error"), homeDirectory); + throw new Exception(message); } - string message = Null.NullString; + message += CreateProfileDefinitions(portalId, mergedTemplatePath); - if (portalId != -1) + if (string.IsNullOrEmpty(message)) { - // add administrator - int administratorId = Null.NullInteger; - adminUser.PortalID = portalId; try { - UserCreateStatus createStatus = UserController.CreateUser(ref adminUser); - if (createStatus == UserCreateStatus.Success) - { - administratorId = adminUser.UserID; - - // reload the UserInfo as when it was first created, it had no portal id and therefore - // used host profile definitions - adminUser = UserController.GetUserById(adminUser.PortalID, adminUser.UserID); - } - else + // the upload directory may already exist if this is a new DB working with a previously installed application + if (Directory.Exists(mappedHomeDirectory)) { - message += UserController.GetUserCreateStatus(createStatus); + Globals.DeleteFolderRecursive(mappedHomeDirectory); } } catch (Exception Exc) { Logger.Error(Exc); - message += Localization.GetString("CreateAdminUser.Error") + Exc.Message + Exc.StackTrace; + message += Localization.GetString("DeleteUploadFolder.Error") + Exc.Message + Exc.StackTrace; } - if (administratorId > 0) + // Set up Child Portal + if (message == Null.NullString) { - this.CreatePortalInternal(portalId, portalName, adminUser, description, keyWords, template, homeDirectory, portalAlias, serverPath, childPath, isChildPortal, ref message); + if (isChildPortal) + { + message = CreateChildPortalFolder(childPath); + } + } + else + { + throw new Exception(message); } - } - else - { - message += Localization.GetString("CreatePortal.Error"); - throw new Exception(message); - } - - try - { - EnsureRequiredEventLogTypesExist(); - } - catch (Exception) - { - // should be no exception, but suppress just in case - } - // remove the portal id from http context as there is no exception. - if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CreatingPortalId")) - { - HttpContext.Current.Items.Remove("CreatingPortalId"); - } + if (message == Null.NullString) + { + try + { + // create the upload directory for the new portal + Directory.CreateDirectory(mappedHomeDirectory); - return portalId; - } + // ensure that the Templates folder exists + string templateFolder = string.Format("{0}Templates", mappedHomeDirectory); + if (!Directory.Exists(templateFolder)) + { + Directory.CreateDirectory(templateFolder); + } - /// - /// Get all the available portal templates grouped by culture. - /// - /// List of PortalTemplateInfo objects. - public IList GetAvailablePortalTemplates() - { - var list = new List(); + // ensure that the Users folder exists + string usersFolder = string.Format("{0}Users", mappedHomeDirectory); + if (!Directory.Exists(usersFolder)) + { + Directory.CreateDirectory(usersFolder); + } - var templateFilePaths = PortalTemplateIO.Instance.EnumerateTemplates(); - var languageFileNames = PortalTemplateIO.Instance.EnumerateLanguageFiles().Select(Path.GetFileName).ToList(); + // copy the default page template + this.CopyPageTemplate("Default.page.template", mappedHomeDirectory); - foreach (string templateFilePath in templateFilePaths) - { - var currentFileName = Path.GetFileName(templateFilePath); - var langs = languageFileNames.Where(x => this.GetTemplateName(x).Equals(currentFileName, StringComparison.InvariantCultureIgnoreCase)).Select(x => this.GetCultureCode(x)).Distinct().ToList(); + // process zip resource file if present + if (File.Exists(template.ResourceFilePath)) + { + this.ProcessResourceFileExplicit(mappedHomeDirectory, template.ResourceFilePath); + } + } + catch (Exception Exc) + { + Logger.Error(Exc); + message += Localization.GetString("ChildPortal.Error") + Exc.Message + Exc.StackTrace; + } + } + else + { + throw new Exception(message); + } - if (langs.Any()) + if (message == Null.NullString) { - langs.ForEach(x => list.Add(new PortalTemplateInfo(templateFilePath, x))); + try + { + FolderMappingController.Instance.AddDefaultFolderTypes(portalId); + } + catch (Exception Exc) + { + Logger.Error(Exc); + message += Localization.GetString("DefaultFolderMappings.Error") + Exc.Message + Exc.StackTrace; + } } else { - // DNN-6544 portal creation requires valid culture, if template has no culture defined, then use portal's default language. - var portalSettings = PortalSettings.Current; - var cultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; - list.Add(new PortalTemplateInfo(templateFilePath, cultureCode)); + throw new Exception(message); } - } - - return list; - } - - /// - /// Gets the current portal settings. - /// - /// portal settings. - PortalSettings IPortalController.GetCurrentPortalSettings() - { - return GetCurrentPortalSettingsInternal(); - } - IAbPortalSettings IPortalController.GetCurrentSettings() - { - return GetCurrentPortalSettingsInternal(); - } - - /// - /// Gets information of a portal. - /// - /// Id of the portal. - /// PortalInfo object with portal definition. - public PortalInfo GetPortal(int portalId) - { - if (portalId == -1) - { - return null; - } + LocaleCollection newPortalLocales = null; + if (message == Null.NullString) + { + try + { + this.CreatePredefinedFolderTypes(portalId); + this.ParseTemplateInternal(portalId, templatePath, templateFile, adminUser.UserID, PortalTemplateModuleAction.Replace, true, out newPortalLocales); + } + catch (Exception Exc) + { + Logger.Error(Exc); + message += Localization.GetString("PortalTemplate.Error") + Exc.Message + Exc.StackTrace; + } + } + else + { + throw new Exception(message); + } - string defaultLanguage = GetActivePortalLanguage(portalId); - PortalInfo portal = this.GetPortal(portalId, defaultLanguage); - if (portal == null) - { - // Active language may not be valid, so fallback to default language - defaultLanguage = GetPortalDefaultLanguage(portalId); - portal = this.GetPortal(portalId, defaultLanguage); - } + if (message == Null.NullString) + { + var portal = this.GetPortal(portalId); + portal.Description = description; + portal.KeyWords = keyWords; + portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//UserProfile", portal.CultureCode); + if (portal.UserTabId == -1) + { + portal.UserTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed", portal.CultureCode); + } - return portal; - } + portal.SearchTabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", portal.CultureCode); + this.UpdatePortalInfo(portal); - /// - /// Gets information of a portal. - /// - /// Id of the portal. - /// The culture code. - /// - public PortalInfo GetPortal(int portalId, string cultureCode) - { - if (portalId == -1) - { - return null; - } + adminUser.Profile.PreferredLocale = portal.DefaultLanguage; + var portalSettings = new PortalSettings(portal); + adminUser.Profile.PreferredTimeZone = portalSettings.TimeZone; + UserController.UpdateUser(portal.PortalID, adminUser); - PortalInfo portal = GetPortalInternal(portalId, cultureCode); + DesktopModuleController.AddDesktopModulesToPortal(portalId); - if (Localization.ActiveLanguagesByPortalID(portalId) > 1) - { - if (portal == null) - { - // Get Fallback language - string fallbackLanguage = string.Empty; + this.AddPortalAlias(portalId, portalAlias); - if (string.IsNullOrEmpty(cultureCode)) + UpdatePortalSetting(portalId, "DefaultPortalAlias", portalAlias, false); + + DataCache.ClearPortalCache(portalId, true); + + if (newPortalLocales != null) { - cultureCode = GetPortalDefaultLanguage(portalId); + foreach (Locale newPortalLocale in newPortalLocales.AllValues) + { + Localization.AddLanguageToPortal(portalId, newPortalLocale.LanguageId, false); + if (portalSettings.ContentLocalizationEnabled) + { + this.MapLocalizedSpecialPages(portalId, newPortalLocale.Code); + } + } } - Locale userLocale = LocaleController.Instance.GetLocale(cultureCode); - if (userLocale != null && !string.IsNullOrEmpty(userLocale.Fallback)) + try { - fallbackLanguage = userLocale.Fallback; + RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portalId); } - - if (string.IsNullOrEmpty(fallbackLanguage)) + catch (Exception Exc) { - fallbackLanguage = Localization.SystemLocale; + Logger.Error(Exc); } - portal = GetPortalInternal(portalId, fallbackLanguage); - - // if we cannot find any fallback, it mean's it's a non portal default langauge - if (portal == null) + // add profanity list to new portal + try { - DataProvider.Instance().EnsureLocalizationExists(portalId, GetActivePortalLanguage(portalId)); - DataCache.ClearHostCache(true); - portal = GetPortalInternal(portalId, GetActivePortalLanguage(portalId)); + const string listName = "ProfanityFilter"; + var listController = new ListController(); + var entry = new ListEntryInfo + { + PortalID = portalId, + SystemList = false, + ListName = listName + "-" + portalId, + }; + listController.AddListEntry(entry); + } + catch (Exception Exc) + { + Logger.Error(Exc); } - } - } - - return portal; - } - - /// - /// Gets the portal. - /// - /// The unique id. - /// Portal info. - public PortalInfo GetPortal(Guid uniqueId) - { - return this.GetPortalList(Null.NullString).SingleOrDefault(p => p.GUID == uniqueId); - } - - /// - /// Gets information from all portals. - /// - /// ArrayList of PortalInfo objects. - public ArrayList GetPortals() - { - return new ArrayList(this.GetPortalList(Null.NullString)); - } - - /// - /// Get portals in specific culture. - /// - /// The culture code. - /// - public List GetPortalList(string cultureCode) - { - string cacheKey = string.Format(DataCache.PortalCacheKey, Null.NullInteger, cultureCode); - return CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, cultureCode), - c => CBO.FillCollection(DataProvider.Instance().GetPortals(cultureCode))); - } - - /// - /// Gets the portal settings dictionary. - /// - /// The portal ID. - /// portal settings. - public Dictionary GetPortalSettings(int portalId) - { - return GetPortalSettingsDictionary(portalId, string.Empty); - } - - /// - /// Gets the portal settings dictionary. - /// - /// The portal ID. - /// The culture code. - /// portal settings. - public Dictionary GetPortalSettings(int portalId, string cultureCode) - { - return GetPortalSettingsDictionary(portalId, cultureCode); - } - - /// - /// Load info for a portal template. - /// - /// Full path to the portal template. - /// the culture code if any for the localization of the portal template. - /// A portal template. - public PortalTemplateInfo GetPortalTemplate(string templatePath, string cultureCode) - { - var template = new PortalTemplateInfo(templatePath, cultureCode); - if (!string.IsNullOrEmpty(cultureCode) && template.CultureCode != cultureCode) - { - return null; - } + // add banned password list to new portal + try + { + const string listName = "BannedPasswords"; + var listController = new ListController(); + var entry = new ListEntryInfo + { + PortalID = portalId, + SystemList = false, + ListName = listName + "-" + portalId, + }; + listController.AddListEntry(entry); + } + catch (Exception Exc) + { + Logger.Error(Exc); + } - return template; - } + ServicesRoutingManager.ReRegisterServiceRoutesWhileSiteIsRunning(); - /// - /// Gets the portal space used bytes. - /// - /// The portal id. - /// Space used in bytes. - public long GetPortalSpaceUsedBytes(int portalId) - { - long size = 0; - IDataReader dr = DataProvider.Instance().GetPortalSpaceUsed(portalId); - try - { - if (dr.Read()) - { - if (dr["SpaceUsed"] != DBNull.Value) + try { - size = Convert.ToInt64(dr["SpaceUsed"]); + var log = new LogInfo + { + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.PORTAL_CREATED.ToString(), + }; + log.LogProperties.Add(new LogDetailInfo("Install Portal:", portalName)); + log.LogProperties.Add(new LogDetailInfo("FirstName:", adminUser.FirstName)); + log.LogProperties.Add(new LogDetailInfo("LastName:", adminUser.LastName)); + log.LogProperties.Add(new LogDetailInfo("Username:", adminUser.Username)); + log.LogProperties.Add(new LogDetailInfo("Email:", adminUser.Email)); + log.LogProperties.Add(new LogDetailInfo("Description:", description)); + log.LogProperties.Add(new LogDetailInfo("Keywords:", keyWords)); + log.LogProperties.Add(new LogDetailInfo("Template:", template.TemplateFilePath)); + log.LogProperties.Add(new LogDetailInfo("TemplateCulture:", template.CultureCode)); + log.LogProperties.Add(new LogDetailInfo("HomeDirectory:", homeDirectory)); + log.LogProperties.Add(new LogDetailInfo("PortalAlias:", portalAlias)); + log.LogProperties.Add(new LogDetailInfo("ServerPath:", serverPath)); + log.LogProperties.Add(new LogDetailInfo("ChildPath:", childPath)); + log.LogProperties.Add(new LogDetailInfo("IsChildPortal:", isChildPortal.ToString())); + LogController.Instance.AddLog(log); + } + catch (Exception exc) + { + Logger.Error(exc); } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return size; - } - /// - /// Verifies if there's enough space to upload a new file on the given portal. - /// - /// Id of the portal. - /// Size of the file being uploaded. - /// True if there's enough space available to upload the file. - public bool HasSpaceAvailable(int portalId, long fileSizeBytes) - { - int hostSpace; - if (portalId == -1) - { - hostSpace = 0; - } - else - { - PortalSettings ps = GetCurrentPortalSettingsInternal(); - if (ps != null && ps.PortalId == portalId) - { - hostSpace = ps.HostSpace; + EventManager.Instance.OnPortalCreated(new PortalCreatedEventArgs { PortalId = portalId }); } else { - PortalInfo portal = this.GetPortal(portalId); - hostSpace = portal.HostSpace; + throw new Exception(message); } } - - return (((this.GetPortalSpaceUsedBytes(portalId) + fileSizeBytes) / Math.Pow(1024, 2)) <= hostSpace) || hostSpace == 0; + else + { + DeletePortalInternal(portalId); + throw new Exception(message); + } } - /// - /// Remaps the Special Pages such as Home, Profile, Search - /// to their localized versions. - /// - /// - /// - public void MapLocalizedSpecialPages(int portalId, string cultureCode) + private void CreatePredefinedFolderTypes(int portalId) { - DataCache.ClearHostCache(true); - DataProvider.Instance().EnsureLocalizationExists(portalId, cultureCode); - - PortalInfo defaultPortal = this.GetPortal(portalId, GetPortalDefaultLanguage(portalId)); - PortalInfo targetPortal = this.GetPortal(portalId, cultureCode); - - Locale targetLocale = LocaleController.Instance.GetLocale(cultureCode); - TabInfo tempTab; - if (defaultPortal.HomeTabId != Null.NullInteger) + try { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.HomeTabId, portalId, targetLocale); - if (tempTab != null) - { - targetPortal.HomeTabId = tempTab.TabID; - } + EnsureRequiredProvidersForFolderTypes(); } - - if (defaultPortal.LoginTabId != Null.NullInteger) + catch (Exception ex) { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.LoginTabId, portalId, targetLocale); - if (tempTab != null) - { - targetPortal.LoginTabId = tempTab.TabID; - } + Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error"), ex); } - if (defaultPortal.RegisterTabId != Null.NullInteger) + var webConfig = Config.Load(); + foreach (FolderTypeConfig folderTypeConfig in FolderMappingsConfigController.Instance.FolderTypes) { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.RegisterTabId, portalId, targetLocale); - if (tempTab != null) + try { - targetPortal.RegisterTabId = tempTab.TabID; + EnsureFolderProviderRegistration(folderTypeConfig, webConfig); + FolderMappingController.Instance.AddFolderMapping(this.GetFolderMappingFromConfig( + folderTypeConfig, + portalId)); } - } - - if (defaultPortal.SplashTabId != Null.NullInteger) - { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SplashTabId, portalId, targetLocale); - if (tempTab != null) + catch (Exception ex) { - targetPortal.SplashTabId = tempTab.TabID; + Logger.Error(Localization.GetString("CreatingConfiguredFolderMapping.Error") + ": " + folderTypeConfig.Name, ex); } } + } - if (defaultPortal.UserTabId != Null.NullInteger) + private void ParseExtensionUrlProviders(XPathNavigator providersNavigator, int portalId) + { + var providers = ExtensionUrlProviderController.GetProviders(portalId); + foreach (XPathNavigator providerNavigator in providersNavigator.Select("extensionUrlProvider")) { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.UserTabId, portalId, targetLocale); - if (tempTab != null) + HtmlUtils.WriteKeepAlive(); + var providerName = XmlUtils.GetNodeValue(providerNavigator, "name"); + var provider = providers.SingleOrDefault(p => p.ProviderName.Equals(providerName, StringComparison.OrdinalIgnoreCase)); + if (provider == null) { - targetPortal.UserTabId = tempTab.TabID; + continue; } - } - if (defaultPortal.SearchTabId != Null.NullInteger) - { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.SearchTabId, portalId, targetLocale); - if (tempTab != null) + var active = XmlUtils.GetNodeValueBoolean(providerNavigator, "active"); + if (active) { - targetPortal.SearchTabId = tempTab.TabID; + ExtensionUrlProviderController.EnableProvider(provider.ExtensionUrlProviderId, portalId); } - } - - if (defaultPortal.Custom404TabId != Null.NullInteger) - { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom404TabId, portalId, targetLocale); - if (tempTab != null) + else { - targetPortal.Custom404TabId = tempTab.TabID; + ExtensionUrlProviderController.DisableProvider(provider.ExtensionUrlProviderId, portalId); } - } - if (defaultPortal.Custom500TabId != Null.NullInteger) - { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.Custom500TabId, portalId, targetLocale); - if (tempTab != null) + var settingsNavigator = providerNavigator.SelectSingleNode("settings"); + if (settingsNavigator != null) { - targetPortal.Custom500TabId = tempTab.TabID; + 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); + } } } + } - if (defaultPortal.TermsTabId != Null.NullInteger) + 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) { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.TermsTabId, portalId, targetLocale); - if (tempTab != null) - { - targetPortal.TermsTabId = tempTab.TabID; - } + return FolderProvider.Instance(folderProviderType).EncryptValue(ensuredSettingValue); + + // return PortalSecurity.Instance.Encrypt(Host.Host.GUID, ensuredSettingValue.Trim()); } - if (defaultPortal.PrivacyTabId != Null.NullInteger) + 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 { - tempTab = TabController.Instance.GetTabByCulture(defaultPortal.PrivacyTabId, portalId, targetLocale); - if (tempTab != null) - { - targetPortal.PrivacyTabId = tempTab.TabID; - } + 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); } - this.UpdatePortalInternal(targetPortal, false); + return folderMapping; } - /// - /// Removes the related PortalLocalization record from the database, adds optional clear cache. - /// - /// - /// - /// - public void RemovePortalLocalization(int portalId, string cultureCode, bool clearCache = true) + private FolderMappingInfo GetFolderMappingFromStorageLocation(int portalId, XmlNode folderNode) { - DataProvider.Instance().RemovePortalLocalization(portalId, cultureCode); - if (clearCache) + var storageLocation = Convert.ToInt32(XmlUtils.GetNodeValue(folderNode, "storagelocation", "0")); + + switch (storageLocation) { - DataCache.ClearPortalCache(portalId, false); + 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); } } - /// - /// Processess a template file for the new portal. - /// - /// PortalId of the new portal. - /// The template. - /// UserId for the portal administrator. This is used to assign roles to this user. - /// Flag to determine whether Module content is merged. - /// Flag to determine is the template is applied to an existing portal or a new one. - /// - /// The roles and settings nodes will only be processed on the portal template file. - /// - public void ParseTemplate(int portalId, PortalTemplateInfo template, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + private string GetTemplateName(string languageFileName) { - string templatePath, templateFile; - this.PrepareLocalizedPortalTemplate(template, out templatePath, out templateFile); + // e.g. "default template.template.en-US.resx" + return languageFileName.GetFileNameFromLocalizedResxFile(); + } - this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal); + private void ParseFolders(XmlNode nodeFolders, int portalId) + { + var folderManager = FolderManager.Instance; + var folderMappingController = FolderMappingController.Instance; + var xmlNodeList = nodeFolders.SelectNodes("//folder"); + if (xmlNodeList != null) + { + foreach (XmlNode node in xmlNodeList) + { + HtmlUtils.WriteKeepAlive(); + var folderPath = XmlUtils.GetNodeValue(node.CreateNavigator(), "folderpath"); + + // First check if the folder exists + var objInfo = folderManager.GetFolder(portalId, folderPath); + + if (objInfo == null) + { + FolderMappingInfo folderMapping; + try + { + folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, folderPath) + ?? this.GetFolderMappingFromStorageLocation(portalId, node); + } + catch (Exception ex) + { + Logger.Error(ex); + folderMapping = folderMappingController.GetDefaultFolderMapping(portalId); + } + + var isProtected = XmlUtils.GetNodeValueBoolean(node, "isprotected"); + + try + { + // Save new folder + objInfo = folderManager.AddFolder(folderMapping, folderPath); + } + catch (Exception ex) + { + Logger.Error(ex); + + // Retry with default folderMapping + var defaultFolderMapping = folderMappingController.GetDefaultFolderMapping(portalId); + if (folderMapping.FolderMappingID != defaultFolderMapping.FolderMappingID) + { + objInfo = folderManager.AddFolder(defaultFolderMapping, folderPath); + } + else + { + throw; + } + } + + objInfo.IsProtected = isProtected; + + 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); + } + } } - /// - /// Processes the resource file for the template file selected. - /// - /// New portal's folder. - /// full path to the resource file. - /// - /// The resource file is a zip file with the same name as the selected template file and with - /// an extension of .resources (to disable this file being downloaded). - /// For example: for template file "portal.template" a resource file "portal.template.resources" can be defined. - /// - public void ProcessResourceFileExplicit(string portalPath, string resoureceFile) + private void ParsePortalSettings(XmlNode nodeSettings, int portalId) { - try + string currentCulture = GetActivePortalLanguage(portalId); + var objPortal = this.GetPortal(portalId); + objPortal.LogoFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "logofile")); + objPortal.FooterText = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "footertext"); + if (nodeSettings.SelectSingleNode("expirydate") != null) { - FileSystemUtils.UnzipResources(new ZipInputStream(new FileStream(resoureceFile, FileMode.Open, FileAccess.Read)), portalPath); + objPortal.ExpiryDate = XmlUtils.GetNodeValueDate(nodeSettings, "expirydate", Null.NullDate); + } + + objPortal.UserRegistration = XmlUtils.GetNodeValueInt(nodeSettings, "userregistration"); + objPortal.BannerAdvertising = XmlUtils.GetNodeValueInt(nodeSettings, "banneradvertising"); + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"))) + { + objPortal.Currency = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "currency"); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostfee"))) + { + objPortal.HostFee = XmlUtils.GetNodeValueSingle(nodeSettings, "hostfee"); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "hostspace"))) + { + objPortal.HostSpace = XmlUtils.GetNodeValueInt(nodeSettings, "hostspace"); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "pagequota"))) + { + objPortal.PageQuota = XmlUtils.GetNodeValueInt(nodeSettings, "pagequota"); } - catch (Exception exc) + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "userquota"))) { - Logger.Error(exc); + objPortal.UserQuota = XmlUtils.GetNodeValueInt(nodeSettings, "userquota"); } - } - /// - /// Updates the portal expiry. - /// - /// The portal id. - /// The culture code. - public void UpdatePortalExpiry(int portalId, string cultureCode) - { - var portal = this.GetPortal(portalId, cultureCode); + objPortal.BackgroundFile = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "backgroundfile"); + objPortal.PaymentProcessor = XmlUtils.GetNodeValue(nodeSettings.CreateNavigator(), "paymentprocessor"); - if (portal.ExpiryDate == Null.NullDate) + objPortal.DefaultLanguage = XmlUtils.GetNodeValue(nodeSettings, "defaultlanguage", "en-US"); + this.UpdatePortalInfo(objPortal); + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty))) { - portal.ExpiryDate = DateTime.Now; + UpdatePortalSetting(portalId, "DefaultPortalSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrc", string.Empty), true, currentCulture); } - portal.ExpiryDate = portal.ExpiryDate.AddMonths(1); + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty))) + { + UpdatePortalSetting(portalId, "DefaultAdminSkin", XmlUtils.GetNodeValue(nodeSettings, "skinsrcadmin", string.Empty), true, currentCulture); + } - this.UpdatePortalInfo(portal); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty))) + { + UpdatePortalSetting(portalId, "DefaultPortalContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrc", string.Empty), true, currentCulture); + } - /// - /// Updates basic portal information. - /// - /// - public void UpdatePortalInfo(PortalInfo portal) - { - this.UpdatePortalInternal(portal, true); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty))) + { + UpdatePortalSetting(portalId, "DefaultAdminContainer", XmlUtils.GetNodeValue(nodeSettings, "containersrcadmin", string.Empty), true, currentCulture); + } - [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] - void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) - { - UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, false); - } + // Enable Skin Widgets Setting + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty))) + { + UpdatePortalSetting(portalId, "EnableSkinWidgets", XmlUtils.GetNodeValue(nodeSettings, "enableskinwidgets", string.Empty)); + } - /// - /// Adds or Updates or Deletes a portal setting value. - /// - void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) - { - UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); - } + // Enable AutoSAve feature + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty))) + { + UpdatePortalSetting(portalId, HtmlText_AutoSaveEnabled, XmlUtils.GetNodeValue(nodeSettings, "enableautosave", string.Empty)); - /// - /// Deletes all expired portals. - /// - /// The server path. - public static void DeleteExpiredPortals(string serverPath) - { - foreach (PortalInfo portal in GetExpiredPortals()) + // Time to autosave, only if enableautosave exists + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty))) + { + UpdatePortalSetting(portalId, HtmlText_TimeToAutoSave, XmlUtils.GetNodeValue(nodeSettings, "timetoautosave", string.Empty)); + } + } + + // Set Auto alias mapping + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL"))) { - DeletePortal(portal, serverPath); + UpdatePortalSetting(portalId, "PortalAliasMapping", XmlUtils.GetNodeValue(nodeSettings, "portalaliasmapping", "CANONICALURL").ToUpperInvariant()); } - } - /// - /// Deletes the portal. - /// - /// The portal. - /// The server path. - /// If the method executed successful, it will return NullString, otherwise return error message. - public static string DeletePortal(PortalInfo portal, string serverPath) - { - string message = string.Empty; + // Set Time Zone maping + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone))) + { + UpdatePortalSetting(portalId, "TimeZone", XmlUtils.GetNodeValue(nodeSettings, "timezone", Localization.SystemTimeZone)); + } - // check if this is the last portal - var portals = Instance.GetPortals(); - if (portals.Count > 1) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled"))) { - if (portal != null) - { - // delete custom resource files - Globals.DeleteFilesRecursive(serverPath, ".Portal-" + portal.PortalID + ".resx"); + UpdatePortalSetting(portalId, "ContentLocalizationEnabled", XmlUtils.GetNodeValue(nodeSettings, "contentlocalizationenabled")); + } - // If child portal delete child folder - var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); - if (arr.Count > 0) - { - var portalAliasInfo = arr[0]; - string portalName = Globals.GetPortalDomainName(portalAliasInfo.HTTPAlias, null, true); - if (portalAliasInfo.HTTPAlias.IndexOf("/", StringComparison.Ordinal) > -1) - { - portalName = GetPortalFolder(portalAliasInfo.HTTPAlias); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled"))) + { + UpdatePortalSetting(portalId, "InlineEditorEnabled", XmlUtils.GetNodeValue(nodeSettings, "inlineeditorenabled")); + } - if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) - { - DeletePortalFolder(serverPath, portalName); - } - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablepopups"))) + { + UpdatePortalSetting(portalId, "EnablePopUps", XmlUtils.GetNodeValue(nodeSettings, "enablepopups")); + } - // delete upload directory - if (!string.IsNullOrEmpty(portal.HomeDirectory)) - { - var homeDirectory = portal.HomeDirectoryMapPath; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled"))) + { + UpdatePortalSetting(portalId, "HideFoldersEnabled", XmlUtils.GetNodeValue(nodeSettings, "hidefoldersenabled")); + } - // check whether home directory is not used by other portal - // it happens when new portal creation failed, but home directory defined by user is already in use with other portal - var homeDirectoryInUse = portals.OfType().Any(x => - x.PortalID != portal.PortalID && - x.HomeDirectoryMapPath.Equals(homeDirectory, StringComparison.OrdinalIgnoreCase)); + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode"))) + { + UpdatePortalSetting(portalId, "ControlPanelMode", XmlUtils.GetNodeValue(nodeSettings, "controlpanelmode")); + } - if (!homeDirectoryInUse) - { - if (Directory.Exists(homeDirectory)) - { - Globals.DeleteFolderRecursive(homeDirectory); - } - } - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity"))) + { + UpdatePortalSetting(portalId, "ControlPanelSecurity", XmlUtils.GetNodeValue(nodeSettings, "controlpanelsecurity")); + } - // remove database references - DeletePortalInternal(portal.PortalID); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility"))) + { + UpdatePortalSetting(portalId, "ControlPanelVisibility", XmlUtils.GetNodeValue(nodeSettings, "controlpanelvisibility")); } - else + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty))) { - message = Localization.GetString("LastPortal"); + UpdatePortalSetting(portalId, "PageHeadText", XmlUtils.GetNodeValue(nodeSettings, "pageheadtext", string.Empty)); } - return message; - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty))) + { + UpdatePortalSetting(portalId, "InjectModuleHyperLink", XmlUtils.GetNodeValue(nodeSettings, "injectmodulehyperlink", string.Empty)); + } - /// - /// Get the portal folder froma child portal alias. - /// - /// portal alias. - /// folder path of the child portal. - public static string GetPortalFolder(string alias) - { - alias = alias.ToLowerInvariant().Replace("http://", string.Empty).Replace("https://", string.Empty); - var appPath = Globals.ApplicationPath + "/"; - if (string.IsNullOrEmpty(Globals.ApplicationPath) || alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) == Null.NullInteger) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty))) { - return alias.Contains("/") ? alias.Substring(alias.IndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1) : string.Empty; + UpdatePortalSetting(portalId, "AddCompatibleHttpHeader", XmlUtils.GetNodeValue(nodeSettings, "addcompatiblehttpheader", string.Empty)); } - return alias.Substring(alias.IndexOf(appPath, StringComparison.InvariantCultureIgnoreCase) + appPath.Length); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty))) + { + UpdatePortalSetting(portalId, "AllowUserUICulture", XmlUtils.GetNodeValue(nodeSettings, "allowuseruiculture", string.Empty)); + } - /// Delete the child portal folder and try to remove its parent when parent folder is empty. - /// the server path. - /// the child folder path. - public static void DeletePortalFolder(string serverPath, string portalFolder) - { - var physicalPath = serverPath + portalFolder; - Globals.DeleteFolderRecursive(physicalPath); + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty))) + { + UpdatePortalSetting(portalId, "EnableBrowserLanguage", XmlUtils.GetNodeValue(nodeSettings, "enablebrowserlanguage", string.Empty)); + } - // remove parent folder if its empty. - var parentFolder = Directory.GetParent(physicalPath); - while (parentFolder != null && !parentFolder.FullName.Equals(serverPath.TrimEnd('\\'), StringComparison.InvariantCultureIgnoreCase)) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", string.Empty))) { - if (parentFolder.GetDirectories().Length + parentFolder.GetFiles().Length == 0) - { - parentFolder.Delete(); - parentFolder = parentFolder.Parent; - } - else - { - break; - } + UpdatePortalSetting(portalId, "ShowCookieConsent", XmlUtils.GetNodeValue(nodeSettings, "showcookieconsent", "False")); } - } - /// - /// Gets the portal dictionary. - /// - /// portal dictionary. the dictionary's Key -> Value is: TabId -> PortalId. - public static Dictionary GetPortalDictionary() - { - string cacheKey = string.Format(DataCache.PortalDictionaryCacheKey); - return CBO.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.PortalDictionaryTimeOut, DataCache.PortalDictionaryCachePriority), GetPortalDictionaryCallback); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty))) + { + UpdatePortalSetting(portalId, "CookieMoreLink", XmlUtils.GetNodeValue(nodeSettings, "cookiemorelink", string.Empty), true, currentCulture); + } - /// ----------------------------------------------------------------------------- - /// - /// GetPortalsByName gets all the portals whose name matches a provided filter expression. - /// - /// - /// - /// The email address to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of PortalInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetPortalsByName(string nameToMatch, int pageIndex, int pageSize, ref int totalRecords) - { - if (pageIndex == -1) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", string.Empty))) + { + UpdatePortalSetting(portalId, "DataConsentActive", XmlUtils.GetNodeValue(nodeSettings, "dataconsentactive", "False")); + } + + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty))) { - pageIndex = 0; - pageSize = int.MaxValue; + UpdatePortalSetting(portalId, "DataConsentTermsLastChange", XmlUtils.GetNodeValue(nodeSettings, "dataconsenttermslastchange", string.Empty), true, currentCulture); } - Type type = typeof(PortalInfo); - return CBO.FillCollection(DataProvider.Instance().GetPortalsByName(nameToMatch, pageIndex, pageSize), ref type, ref totalRecords); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty))) + { + UpdatePortalSetting(portalId, "DataConsentConsentRedirect", XmlUtils.GetNodeValue(nodeSettings, "dataconsentconsentredirect", string.Empty), true, currentCulture); + } - public static ArrayList GetPortalsByUser(int userId) - { - Type type = typeof(PortalInfo); - return CBO.FillCollection(DataProvider.Instance().GetPortalsByUser(userId), type); - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty))) + { + UpdatePortalSetting(portalId, "DataConsentUserDeleteAction", XmlUtils.GetNodeValue(nodeSettings, "dataconsentuserdeleteaction", string.Empty), true, currentCulture); + } - public static int GetEffectivePortalId(int portalId) - { - if (portalId > Null.NullInteger && Globals.Status != Globals.UpgradeStatus.Upgrade) + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty))) { - var portal = Instance.GetPortal(portalId); - var portalGroup = (from p in PortalGroupController.Instance.GetPortalGroups() - where p.PortalGroupId == portal.PortalGroupID - select p) - .SingleOrDefault(); + UpdatePortalSetting(portalId, "DataConsentDelay", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelay", string.Empty), true, currentCulture); + } - if (portalGroup != null) - { - portalId = portalGroup.MasterPortalId; - } + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty))) + { + UpdatePortalSetting(portalId, "DataConsentDelayMeasurement", XmlUtils.GetNodeValue(nodeSettings, "dataconsentdelaymeasurement", string.Empty), true, currentCulture); } - return portalId; } - /// - /// Gets all expired portals. - /// - /// all expired portals as array list. - public static ArrayList GetExpiredPortals() + private void ParseRoleGroups(XPathNavigator nav, int portalID, int administratorId) { - return CBO.FillCollection(DataProvider.Instance().GetExpiredPortals(), typeof(PortalInfo)); - } + var administratorRoleId = -1; + var registeredRoleId = -1; + var subscriberRoleId = -1; + var unverifiedRoleId = -1; - /// - /// Determines whether the portal is child portal. - /// - /// The portal. - /// The server path. - /// - /// true if the portal is child portal; otherwise, false. - /// - public static bool IsChildPortal(PortalInfo portal, string serverPath) - { - bool isChild = Null.NullBoolean; - var arr = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); - if (arr.Count > 0) + foreach (XPathNavigator roleGroupNav in nav.Select("rolegroup")) { - PortalAliasInfo portalAlias = arr[0]; - var portalName = Globals.GetPortalDomainName(portalAlias.HTTPAlias, null, true); - if (portalAlias.HTTPAlias.IndexOf("/") > -1) + HtmlUtils.WriteKeepAlive(); + var roleGroup = CBO.DeserializeObject(new StringReader(roleGroupNav.OuterXml)); + if (roleGroup.RoleGroupName != "GlobalRoles") { - portalName = GetPortalFolder(portalAlias.HTTPAlias); + roleGroup.PortalID = portalID; + CreateRoleGroup(roleGroup); } - if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) + foreach (var role in roleGroup.Roles.Values) { - isChild = true; + role.PortalID = portalID; + role.RoleGroupID = roleGroup.RoleGroupID; + role.Status = RoleStatus.Approved; + switch (role.RoleType) + { + case RoleType.Administrator: + administratorRoleId = CreateRole(role); + break; + case RoleType.RegisteredUser: + registeredRoleId = CreateRole(role); + break; + case RoleType.Subscriber: + subscriberRoleId = CreateRole(role); + break; + case RoleType.None: + CreateRole(role); + break; + case RoleType.UnverifiedUser: + unverifiedRoleId = CreateRole(role); + break; + } } } - return isChild; - } - - public static bool IsMemberOfPortalGroup(int portalId) - { - var portal = Instance.GetPortal(portalId); - - return portal != null && portal.PortalGroupID > Null.NullInteger; - } - - /// - /// Deletes the portal setting (neutral and for all languages). - /// - /// The portal ID. - /// Name of the setting. - public static void DeletePortalSetting(int portalID, string settingName) - { - DeletePortalSetting(portalID, settingName, Null.NullString); - } - - /// - /// Deletes the portal setting in this language. - /// - /// The portal ID. - /// Name of the setting. - /// The culture code. - public static void DeletePortalSetting(int portalID, string settingName, string cultureCode) - { - DataProvider.Instance().DeletePortalSetting(portalID, settingName, cultureCode.ToLowerInvariant()); - EventLogController.Instance.AddLog("SettingName", settingName + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); - DataCache.ClearHostCache(true); - } - - /// - /// Deletes all portal settings by portal id. - /// - /// The portal ID. - public static void DeletePortalSettings(int portalID) - { - DeletePortalSettings(portalID, Null.NullString); - } + CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); - /// - /// Deletes all portal settings by portal id and for a given language (Null: all languages and neutral settings). - /// - /// The portal ID. - public static void DeletePortalSettings(int portalID, string cultureCode) - { - DataProvider.Instance().DeletePortalSettings(portalID, cultureCode); - EventLogController.Instance.AddLog("PortalID", portalID.ToString() + ((cultureCode == Null.NullString) ? string.Empty : " (" + cultureCode + ")"), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTAL_SETTING_DELETED); - DataCache.ClearHostCache(true); + // update portal setup + var portal = this.GetPortal(portalID); + this.UpdatePortalSetup( + portalID, + administratorId, + administratorRoleId, + registeredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalID)); } - /// - /// takes in a text value, decrypts it with a FIPS compliant algorithm and returns the value. - /// - /// the setting to read. - /// the pass phrase used for encryption/decryption. - /// - public static string GetEncryptedString(string settingName, int portalID, string passPhrase) + private void ParseRoles(XPathNavigator nav, int portalID, int administratorId) { - Requires.NotNullOrEmpty("key", settingName); - Requires.NotNullOrEmpty("passPhrase", passPhrase); - - var cipherText = GetPortalSetting(settingName, portalID, string.Empty); - - return Security.FIPSCompliant.DecryptAES(cipherText, passPhrase, Host.Host.GUID); - } + var administratorRoleId = -1; + var registeredRoleId = -1; + var subscriberRoleId = -1; + var unverifiedRoleId = -1; - /// - /// Gets the portal setting. - /// - /// Name of the setting. - /// The portal ID. - /// The default value. - /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. - public static string GetPortalSetting(string settingName, int portalID, string defaultValue) - { - var retValue = Null.NullString; - try - { - string setting; - Instance.GetPortalSettings(portalID).TryGetValue(settingName, out setting); - retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; - } - catch (Exception exc) + foreach (XPathNavigator roleNav in nav.Select("role")) { - Logger.Error(exc); + HtmlUtils.WriteKeepAlive(); + var role = CBO.DeserializeObject(new StringReader(roleNav.OuterXml)); + role.PortalID = portalID; + role.RoleGroupID = Null.NullInteger; + switch (role.RoleType) + { + case RoleType.Administrator: + administratorRoleId = CreateRole(role); + break; + case RoleType.RegisteredUser: + registeredRoleId = CreateRole(role); + break; + case RoleType.Subscriber: + subscriberRoleId = CreateRole(role); + break; + case RoleType.None: + CreateRole(role); + break; + case RoleType.UnverifiedUser: + unverifiedRoleId = CreateRole(role); + break; + } } - return retValue; - } - - /// - /// Gets the portal setting for a specific language (or neutral). - /// - /// Name of the setting. - /// The portal ID. - /// The default value. - /// culture code of the language to retrieve (not empty). - /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. - public static string GetPortalSetting(string settingName, int portalID, string defaultValue, string cultureCode) - { - var retValue = Null.NullString; - try - { - string setting; - Instance.GetPortalSettings(portalID, cultureCode).TryGetValue(settingName, out setting); - retValue = string.IsNullOrEmpty(setting) ? defaultValue : setting; - } - catch (Exception exc) - { - Logger.Error(exc); - } + // create required roles if not already created + CreateDefaultPortalRoles(portalID, administratorId, ref administratorRoleId, ref registeredRoleId, ref subscriberRoleId, unverifiedRoleId); - return retValue; + // update portal setup + var portal = this.GetPortal(portalID); + this.UpdatePortalSetup( + portalID, + administratorId, + administratorRoleId, + registeredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalID)); } - /// - /// Gets the portal setting as boolean. - /// - /// The key. - /// The portal ID. - /// default value. - /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. - public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue) + private void ParseTab(XmlNode nodeTab, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, ref Hashtable hModules, ref Hashtable hTabs, bool isNewPortal) { - bool retValue = Null.NullBoolean; - try + TabInfo tab = null; + string strName = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "name"); + var portal = this.GetPortal(portalId); + if (!string.IsNullOrEmpty(strName)) { - string setting; - Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); - if (string.IsNullOrEmpty(setting)) + if (!isNewPortal) // running from wizard: try to find the tab by path { - retValue = defaultValue; + string parenttabname = string.Empty; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent"))) + { + parenttabname = XmlUtils.GetNodeValue(nodeTab.CreateNavigator(), "parent") + "/"; + } + + if (hTabs[parenttabname + strName] != null) + { + tab = TabController.Instance.GetTab(Convert.ToInt32(hTabs[parenttabname + strName]), portalId, false); + } } - else + + if (tab == null || isNewPortal) { - retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); + tab = TabController.DeserializeTab(nodeTab, null, hTabs, portalId, isAdminTemplate, mergeTabs, hModules); } - } - catch (Exception exc) - { - Logger.Error(exc); - } - return retValue; + // when processing the template we should try and identify the Admin tab + var logType = "AdminTab"; + if (tab.TabName == "Admin") + { + portal.AdminTabId = tab.TabID; + } + + // when processing the template we can find: hometab, usertab, logintab + switch (XmlUtils.GetNodeValue(nodeTab, "tabtype", string.Empty).ToLowerInvariant()) + { + case "splashtab": + portal.SplashTabId = tab.TabID; + logType = "SplashTab"; + break; + case "hometab": + portal.HomeTabId = tab.TabID; + logType = "HomeTab"; + break; + case "logintab": + portal.LoginTabId = tab.TabID; + logType = "LoginTab"; + break; + case "usertab": + portal.UserTabId = tab.TabID; + logType = "UserTab"; + break; + case "searchtab": + portal.SearchTabId = tab.TabID; + logType = "SearchTab"; + break; + case "404tab": + portal.Custom404TabId = tab.TabID; + logType = "Custom404Tab"; + break; + case "500tab": + portal.Custom500TabId = tab.TabID; + logType = "Custom500Tab"; + break; + case "termstab": + portal.TermsTabId = tab.TabID; + logType = "TermsTabId"; + break; + case "privacytab": + portal.PrivacyTabId = tab.TabID; + logType = "PrivacyTabId"; + break; + } + + this.UpdatePortalSetup( + portalId, + portal.AdministratorId, + portal.AdministratorRoleId, + portal.RegisteredRoleId, + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.AdminTabId, + GetActivePortalLanguage(portalId)); + EventLogController.Instance.AddLog( + logType, + tab.TabID.ToString(), + GetCurrentPortalSettingsInternal(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.PORTAL_SETTING_UPDATED); + } } - /// - /// Gets the portal setting as boolean for a specific language (or neutral). - /// - /// The key. - /// The portal ID. - /// default value. - /// culture code of the language to retrieve (not empty). - /// Returns setting's value if portal contains the specific setting in specified language or neutral, otherwise return defaultValue. - public static bool GetPortalSettingAsBoolean(string key, int portalID, bool defaultValue, string cultureCode) + private void ParseTabs(XmlNode nodeTabs, int portalId, bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, bool isNewPortal) { - bool retValue = Null.NullBoolean; - try + // used to control if modules are true modules or instances + // will hold module ID from template / new module ID so new instances can reference right moduleid + // only first one from the template will be create as a true module, + // others will be moduleinstances (tabmodules) + Hashtable hModules = new Hashtable(); + Hashtable hTabs = new Hashtable(); + + // if running from wizard we need to pre populate htabs with existing tabs so ParseTab + // can find all existing ones + if (!isNewPortal) { - string setting; - GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); - if (string.IsNullOrEmpty(setting)) + Hashtable hTabNames = new Hashtable(); + foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) { - retValue = defaultValue; + TabInfo objTab = tabPair.Value; + if (!objTab.IsDeleted) + { + var tabname = objTab.TabName; + if (!Null.IsNull(objTab.ParentId)) + { + tabname = Convert.ToString(hTabNames[objTab.ParentId]) + "/" + objTab.TabName; + } + + hTabNames.Add(objTab.TabID, tabname); + } } - else + + // when parsing tabs we will need tabid given tabname + foreach (int i in hTabNames.Keys) { - retValue = setting.StartsWith("Y", StringComparison.InvariantCultureIgnoreCase) || setting.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase); + if (hTabs[hTabNames[i]] == null) + { + hTabs.Add(hTabNames[i], i); + } } + + hTabNames.Clear(); } - catch (Exception exc) + + foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab")) { - Logger.Error(exc); + HtmlUtils.WriteKeepAlive(); + this.ParseTab(nodeTab, portalId, isAdminTemplate, mergeTabs, ref hModules, ref hTabs, isNewPortal); } - return retValue; - } - - /// - /// Gets the portal setting as integer. - /// - /// The key. - /// The portal ID. - /// The default value. - /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. - public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue) - { - int retValue = Null.NullInteger; - try + // Process tabs that are linked to tabs + foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'Tab']")) { - string setting; - Instance.GetPortalSettings(portalID).TryGetValue(key, out setting); - if (string.IsNullOrEmpty(setting)) - { - retValue = defaultValue; - } - else + HtmlUtils.WriteKeepAlive(); + int tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); + string tabPath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); + if (tabId > Null.NullInteger) { - retValue = Convert.ToInt32(setting); + TabInfo objTab = TabController.Instance.GetTab(tabId, portalId, false); + objTab.Url = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString).ToString(); + TabController.Instance.UpdateTab(objTab); } } - catch (Exception exc) + + var folderManager = FolderManager.Instance; + var fileManager = FileManager.Instance; + + // Process tabs that are linked to files + foreach (XmlNode nodeTab in nodeTabs.SelectNodes("//tab[url/@type = 'File']")) { - Logger.Error(exc); - } + HtmlUtils.WriteKeepAlive(); + var tabId = XmlUtils.GetNodeValueInt(nodeTab, "tabid", Null.NullInteger); + var filePath = XmlUtils.GetNodeValue(nodeTab, "url", Null.NullString); + if (tabId > Null.NullInteger) + { + var objTab = TabController.Instance.GetTab(tabId, portalId, false); - return retValue; + var fileName = Path.GetFileName(filePath); + + var folderPath = filePath.Substring(0, filePath.LastIndexOf(fileName)); + var folder = folderManager.GetFolder(portalId, folderPath); + + var file = fileManager.GetFile(folder, fileName); + + objTab.Url = "FileID=" + file.FileId; + TabController.Instance.UpdateTab(objTab); + } + } } - /// - /// Gets the portal setting as double. - /// - /// The key. - /// The portal Id. - /// The default value. - /// Returns setting's value if portal contains the specific setting, otherwise return defaultValue. - public static double GetPortalSettingAsDouble(string key, int portalId, double defaultValue) + private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal) + { + LocaleCollection localeCollection; + this.ParseTemplateInternal(portalId, templatePath, templateFile, administratorId, mergeTabs, isNewPortal, out localeCollection); + } + + private void ParseTemplateInternal(int portalId, string templatePath, string templateFile, int administratorId, PortalTemplateModuleAction mergeTabs, bool isNewPortal, out LocaleCollection localeCollection) { - double retValue = Null.NullDouble; + CachingProvider.DisableCacheExpiration(); + + var xmlPortal = new XmlDocument { XmlResolver = null }; + IFolderInfo objFolder; try { - string setting; - Instance.GetPortalSettings(portalId).TryGetValue(key, out setting); - if (string.IsNullOrEmpty(setting)) - { - retValue = defaultValue; - } - else - { - retValue = Convert.ToDouble(setting); - } + xmlPortal.Load(Path.Combine(templatePath, templateFile)); } - catch (Exception exc) + catch (Exception ex) { - Logger.Error(exc); + Logger.Error(ex); } - return retValue; - } + var node = xmlPortal.SelectSingleNode("//portal/settings"); + if (node != null && isNewPortal) + { + HtmlUtils.WriteKeepAlive(); + this.ParsePortalSettings(node, portalId); + } - /// - /// Gets the portal setting as integer for a specific language (or neutral). - /// - /// The key. - /// The portal ID. - /// The default value. - /// culture code of the language to retrieve (not empty). - /// Returns setting's value if portal contains the specific setting (for specified lang, otherwise return defaultValue. - public static int GetPortalSettingAsInteger(string key, int portalID, int defaultValue, string cultureCode) - { - int retValue = Null.NullInteger; - try + node = xmlPortal.SelectSingleNode("//locales"); + if (node != null && isNewPortal) { - string setting; - GetPortalSettingsDictionary(portalID, cultureCode).TryGetValue(key, out setting); - if (string.IsNullOrEmpty(setting)) - { - retValue = defaultValue; - } - else + HtmlUtils.WriteKeepAlive(); + localeCollection = ParseEnabledLocales(node, portalId); + } + else + { + var portalInfo = Instance.GetPortal(portalId); + var defaultLocale = LocaleController.Instance.GetLocale(portalInfo.DefaultLanguage); + if (defaultLocale == null) { - retValue = Convert.ToInt32(setting); + defaultLocale = new Locale { Code = portalInfo.DefaultLanguage, Fallback = Localization.SystemLocale, Text = CultureInfo.GetCultureInfo(portalInfo.DefaultLanguage).NativeName }; + Localization.SaveLanguage(defaultLocale, false); } + + localeCollection = new LocaleCollection { { defaultLocale.Code, defaultLocale } }; } - catch (Exception exc) + + node = xmlPortal.SelectSingleNode("//portal/rolegroups"); + if (node != null) { - Logger.Error(exc); + this.ParseRoleGroups(node.CreateNavigator(), portalId, administratorId); } - return retValue; - } + node = xmlPortal.SelectSingleNode("//portal/roles"); + if (node != null) + { + this.ParseRoles(node.CreateNavigator(), portalId, administratorId); + } - /// - /// takes in a text value, encrypts it with a FIPS compliant algorithm and stores. - /// - /// The portal ID. - /// host settings key. - /// host settings value. - /// pass phrase to allow encryption/decryption. - public static void UpdateEncryptedString(int portalID, string settingName, string settingValue, string passPhrase) - { - Requires.NotNullOrEmpty("key", settingName); - Requires.PropertyNotNull("value", settingValue); - Requires.NotNullOrEmpty("passPhrase", passPhrase); + node = xmlPortal.SelectSingleNode("//portal/portalDesktopModules"); + if (node != null) + { + ParsePortalDesktopModules(node.CreateNavigator(), portalId); + } - var cipherText = Security.FIPSCompliant.EncryptAES(settingValue, passPhrase, Host.Host.GUID); + node = xmlPortal.SelectSingleNode("//portal/folders"); + if (node != null) + { + this.ParseFolders(node, portalId); + } - UpdatePortalSetting(portalID, settingName, cipherText); - } + node = xmlPortal.SelectSingleNode("//portal/extensionUrlProviders"); + if (node != null) + { + this.ParseExtensionUrlProviders(node.CreateNavigator(), portalId); + } - /// - /// Updates a single neutral (not language specific) portal setting and clears it from the cache. - /// - /// The portal ID. - /// Name of the setting. - /// The setting value. - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue) - { - UpdatePortalSetting(portalID, settingName, settingValue, true); - } + var defaultFolderMapping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - /// - /// Updates a single neutral (not language specific) portal setting, optionally without clearing the cache. - /// - /// The portal ID. - /// Name of the setting. - /// The setting value. - /// if set to true [clear cache]. - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache) - { - UpdatePortalSetting(portalID, settingName, settingValue, clearCache, Null.NullString, false); - } + if (FolderManager.Instance.GetFolder(portalId, string.Empty) == null) + { + objFolder = FolderManager.Instance.AddFolder(defaultFolderMapping, string.Empty); + objFolder.IsProtected = true; + FolderManager.Instance.UpdateFolder(objFolder); - /// - /// Updates a language specific or neutral portal setting and clears it from the cache. - /// - /// The portal ID. - /// Name of the setting. - /// The setting value. - /// culture code for language specific settings, null string ontherwise. - [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, string cultureCode) - { - UpdatePortalSetting(portalID, settingName, settingValue, true, cultureCode, false); - } + this.AddFolderPermissions(portalId, objFolder.FolderID); + } - /// - /// Updates a language specific or neutral portal setting and optionally clears it from the cache. - /// - /// The portal ID. - /// Name of the setting. - /// The setting value. - /// if set to true [clear cache]. - /// culture code for language specific settings, null string ontherwise. - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) - { - UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, false); - } + if (FolderManager.Instance.GetFolder(portalId, "Templates/") == null) + { + var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Templates/") ?? defaultFolderMapping; + objFolder = FolderManager.Instance.AddFolder(folderMapping, "Templates/"); + objFolder.IsProtected = true; + FolderManager.Instance.UpdateFolder(objFolder); - /// - /// Updates a language specific or neutral portal setting and optionally clears it from the cache. - /// All overloaded methors will not encrypt the setting value. Therefore, call this method whenever - /// there is a need to encrypt the setting value before storing it in the datanbase. - /// - /// The portal ID. - /// Name of the setting. - /// The setting value. - /// if set to true [clear cache]. - /// culture code for language specific settings, null string ontherwise. - /// When true it encrypt the value before storing it in the database. - public static void UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) - { - Instance.UpdatePortalSetting(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); - } + // AddFolderPermissions(PortalId, objFolder.FolderID); + } - /// - /// Checks the desktop modules whether is installed. - /// - /// The nav. - /// Empty string if the module hasn't been installed, otherwise return the friendly name. - public static string CheckDesktopModulesInstalled(XPathNavigator nav) - { - string friendlyName; - DesktopModuleInfo desktopModule; - StringBuilder modulesNotInstalled = new StringBuilder(); + // force creation of users folder if not present on template + if (FolderManager.Instance.GetFolder(portalId, "Users/") == null) + { + var folderMapping = FolderMappingsConfigController.Instance.GetFolderMapping(portalId, "Users/") ?? defaultFolderMapping; + objFolder = FolderManager.Instance.AddFolder(folderMapping, "Users/"); + objFolder.IsProtected = true; + FolderManager.Instance.UpdateFolder(objFolder); - foreach (XPathNavigator desktopModuleNav in nav.Select("portalDesktopModule")) + // AddFolderPermissions(PortalId, objFolder.FolderID); + } + + if (mergeTabs == PortalTemplateModuleAction.Replace) { - friendlyName = XmlUtils.GetNodeValue(desktopModuleNav, "friendlyname"); + foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) + { + var objTab = tabPair.Value; + objTab.TabName = objTab.TabName + "_old"; + objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName); + objTab.IsDeleted = true; + TabController.Instance.UpdateTab(objTab); + foreach (KeyValuePair modulePair in ModuleController.Instance.GetTabModules(objTab.TabID)) + { + var objModule = modulePair.Value; + ModuleController.Instance.DeleteTabModule(objModule.TabID, objModule.ModuleID, false); + } + } + } - if (!string.IsNullOrEmpty(friendlyName)) + node = xmlPortal.SelectSingleNode("//portal/tabs"); + if (node != null) + { + string version = xmlPortal.DocumentElement.GetAttribute("version"); + if (version != "5.0") { - desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); - if (desktopModule == null) + XmlDocument xmlAdmin = new XmlDocument { XmlResolver = null }; + try { - // PE and EE templates have HTML as friendly name so check to make sure - // there is really no HTML module installed - if (friendlyName == "HTML") + string path = Path.Combine(templatePath, "admin.template"); + if (!File.Exists(path)) { - desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName("HTML Pro"); - if (desktopModule == null) - { - modulesNotInstalled.Append(friendlyName); - modulesNotInstalled.Append("
    "); - } + // if the template is a merged copy of a localized templte the + // admin.template may be one director up + path = Path.Combine(templatePath, "..\admin.template"); } - else - { - modulesNotInstalled.Append(friendlyName); - modulesNotInstalled.Append("
    "); + + xmlAdmin.Load(path); + + XmlNode adminNode = xmlAdmin.SelectSingleNode("//portal/tabs"); + foreach (XmlNode adminTabNode in adminNode.ChildNodes) + { + node.AppendChild(xmlPortal.ImportNode(adminTabNode, true)); } } + catch (Exception ex) + { + Logger.Error(ex); + } } + + this.ParseTabs(node, portalId, false, mergeTabs, isNewPortal); } - return modulesNotInstalled.ToString(); + CachingProvider.EnableCacheExpiration(); } - /// - /// function provides the language for portalinfo requests - /// in case where language has not been installed yet, will return the core install default of en-us. - /// - /// - /// - /// - /// - public static string GetActivePortalLanguage(int portalID) + private void PrepareLocalizedPortalTemplate(PortalTemplateInfo template, out string templatePath, out string templateFile) { - // get Language - string Language = Localization.SystemLocale; - string tmpLanguage = GetPortalDefaultLanguage(portalID); - var isDefaultLanguage = false; - if (!string.IsNullOrEmpty(tmpLanguage)) + if (string.IsNullOrEmpty(template.LanguageFilePath)) { - Language = tmpLanguage; - isDefaultLanguage = true; + // no language to merge + templatePath = Path.GetDirectoryName(template.TemplateFilePath) + @"\"; + templateFile = Path.GetFileName(template.TemplateFilePath); + return; } - // handles case where portalcontroller methods invoked before a language is installed - if (portalID > Null.NullInteger && Globals.Status == Globals.UpgradeStatus.None && Localization.ActiveLanguagesByPortalID(portalID) == 1) + templatePath = Path.Combine(TestableGlobals.Instance.HostMapPath, "MergedTemplate"); + Directory.CreateDirectory(templatePath); + + var buffer = new StringBuilder(File.ReadAllText(template.TemplateFilePath)); + + XDocument languageDoc; + using (var reader = PortalTemplateIO.Instance.OpenTextReader(template.LanguageFilePath)) { - return Language; + languageDoc = XDocument.Load(reader); } - if (HttpContext.Current != null && Globals.Status == Globals.UpgradeStatus.None) + var localizedData = languageDoc.Descendants("data"); + + foreach (var item in localizedData) { - if (HttpContext.Current.Request.QueryString["language"] != null) - { - Language = HttpContext.Current.Request.QueryString["language"]; - } - else + var nameAttribute = item.Attribute("name"); + if (nameAttribute != null) { - PortalSettings _PortalSettings = GetCurrentPortalSettingsInternal(); - if (_PortalSettings != null && _PortalSettings.ActiveTab != null && !string.IsNullOrEmpty(_PortalSettings.ActiveTab.CultureCode)) - { - Language = _PortalSettings.ActiveTab.CultureCode; - } - else + string name = nameAttribute.Value; + var valueElement = item.Descendants("value").FirstOrDefault(); + if (valueElement != null) { - // PortalSettings IS Nothing - probably means we haven't set it yet (in Begin Request) - // so try detecting the user's cookie - if (HttpContext.Current.Request["language"] != null) - { - Language = HttpContext.Current.Request["language"]; - isDefaultLanguage = false; - } - - // if no cookie - try detecting browser - if ((string.IsNullOrEmpty(Language) || isDefaultLanguage) && EnableBrowserLanguageInDefault(portalID)) - { - CultureInfo Culture = Localization.GetBrowserCulture(portalID); + string value = valueElement.Value; - if (Culture != null) - { - Language = Culture.Name; - } - } + buffer = buffer.Replace(string.Format("[{0}]", name), value); } } } - return Language; + templateFile = string.Format("Merged-{0}-{1}", template.CultureCode, Path.GetFileName(template.TemplateFilePath)); + + File.WriteAllText(Path.Combine(templatePath, templateFile), buffer.ToString()); } - /// - /// return the current DefaultLanguage value from the Portals table for the requested Portalid. - /// - /// - /// - /// - /// - public static string GetPortalDefaultLanguage(int portalID) + private void UpdatePortalInternal(PortalInfo portal, bool clearCache) { - string cacheKey = string.Format("PortalDefaultLanguage_{0}", portalID); - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority, portalID), GetPortalDefaultLanguageCallBack); + var processorPassword = portal.ProcessorPassword; + if (!string.IsNullOrEmpty(processorPassword)) + { + processorPassword = Security.FIPSCompliant.EncryptAES(processorPassword, Config.GetDecryptionkey(), Host.Host.GUID); + } + + DataProvider.Instance().UpdatePortalInfo( + portal.PortalID, + portal.PortalGroupID, + portal.PortalName, + portal.LogoFile, + portal.FooterText, + portal.ExpiryDate, + portal.UserRegistration, + portal.BannerAdvertising, + portal.Currency, + portal.AdministratorId, + portal.HostFee, + portal.HostSpace, + portal.PageQuota, + portal.UserQuota, + portal.PaymentProcessor, + portal.ProcessorUserId, + processorPassword, + portal.Description, + portal.KeyWords, + portal.BackgroundFile, + 0, // site log history function has been removed. + portal.SplashTabId, + portal.HomeTabId, + portal.LoginTabId, + portal.RegisterTabId, + portal.UserTabId, + portal.SearchTabId, + portal.Custom404TabId, + portal.Custom500TabId, + portal.TermsTabId, + portal.PrivacyTabId, + portal.DefaultLanguage, + portal.HomeDirectory, + UserController.Instance.GetCurrentUserInfo().UserID, + portal.CultureCode); + + EventLogController.Instance.AddLog("PortalId", portal.PortalID.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); + + // ensure a localization item exists (in case a new default language has been set) + DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, portal.DefaultLanguage); + + // clear portal cache + if (clearCache) + { + DataCache.ClearHostCache(true); + } + } + + 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) + { + DataProvider.Instance().UpdatePortalSetup( + portalId, + administratorId, + administratorRoleId, + registeredRoleId, + splashTabId, + homeTabId, + loginTabId, + registerTabId, + userTabId, + searchTabId, + custom404TabId, + custom500TabId, + termsTabId, + privacyTabId, + adminTabId, + cultureCode); + EventLogController.Instance.AddLog("PortalId", portalId.ToString(), GetCurrentPortalSettingsInternal(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.PORTALINFO_UPDATED); + DataCache.ClearHostCache(true); } /// - /// set the required DefaultLanguage in the Portals table for a particular portal - /// saves having to update an entire PortalInfo object. + /// Gets the current portal settings. /// - /// - /// - /// - /// - public static void UpdatePortalDefaultLanguage(int portalID, string CultureCode) + /// portal settings. + PortalSettings IPortalController.GetCurrentPortalSettings() { - DataProvider.Instance().UpdatePortalDefaultLanguage(portalID, CultureCode); - - // ensure localization record exists as new portal default language may be relying on fallback chain - // of which it is now the final part - DataProvider.Instance().EnsureLocalizationExists(portalID, CultureCode); + return GetCurrentPortalSettingsInternal(); } - public static void IncrementCrmVersion(int portalID) + IAbPortalSettings IPortalController.GetCurrentSettings() { - int currentVersion; - var versionSetting = GetPortalSetting(ClientResourceSettings.VersionKey, portalID, "1"); - if (int.TryParse(versionSetting, out currentVersion)) - { - var newVersion = currentVersion + 1; - UpdatePortalSetting(portalID, ClientResourceSettings.VersionKey, newVersion.ToString(CultureInfo.InvariantCulture), true); - } + return GetCurrentPortalSettingsInternal(); } - public static void IncrementOverridingPortalsCrmVersion() + [Obsolete("Deprecated in DNN 9.2.0. Use the overloaded one with the 'isSecure' parameter instead. Scheduled removal in v11.0.0.")] + void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode) { - foreach (PortalInfo portal in Instance.GetPortals()) - { - string setting = GetPortalSetting(ClientResourceSettings.OverrideDefaultSettingsKey, portal.PortalID, "False"); - bool overriden; + UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, false); + } - // if this portal is overriding the host level... - if (bool.TryParse(setting, out overriden) && overriden) - { - // increment its version - IncrementCrmVersion(portal.PortalID); - } - } + /// + /// Adds or Updates or Deletes a portal setting value. + /// + void IPortalController.UpdatePortalSetting(int portalID, string settingName, string settingValue, bool clearCache, string cultureCode, bool isSecure) + { + UpdatePortalSettingInternal(portalID, settingName, settingValue, clearCache, cultureCode, isSecure); } public class PortalTemplateInfo @@ -3693,12 +3693,29 @@ public PortalTemplateInfo(string templateFilePath, string cultureCode) this.InitNameAndDescription(); } + public string ResourceFilePath + { + get + { + if (this._resourceFilePath == null) + { + this._resourceFilePath = PortalTemplateIO.Instance.GetResourceFilePath(this.TemplateFilePath); + } + + return this._resourceFilePath; + } + } + 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; } + private static string ReadLanguageFileValue(XDocument xmlDoc, string name) { return (from f in xmlDoc.Descendants("data") @@ -3775,23 +3792,6 @@ private void InitLocalizationFields(string cultureCode) this.CultureCode = portalSettings != null ? GetPortalDefaultLanguage(portalSettings.PortalId) : Localization.SystemLocale; } } - - public string LanguageFilePath { get; private set; } - - public string Description { get; private set; } - - public string ResourceFilePath - { - get - { - if (this._resourceFilePath == null) - { - this._resourceFilePath = PortalTemplateIO.Instance.GetResourceFilePath(this.TemplateFilePath); - } - - return this._resourceFilePath; - } - } } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs index d983fc31f9b..1321b498d9d 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupController.cs @@ -23,10 +23,10 @@ namespace DotNetNuke.Entities.Portals public class PortalGroupController : ComponentBase, IPortalGroupController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PortalGroupController)); private readonly IDataService _dataService; private readonly IPortalController _portalController; - + public PortalGroupController() : this(DataService.Instance, PortalController.Instance) { @@ -40,8 +40,8 @@ public PortalGroupController(IDataService dataService, IPortalController portalC this._dataService = dataService; this._portalController = portalController; - } - + } + public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, UserCopiedCallback callback) { Requires.NotNull("portal", portal); @@ -73,7 +73,7 @@ public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, Use if (masterUsers.Count > 0) { - var autoAssignRoles = RoleController.Instance.GetRoles( + var autoAssignRoles = RoleController.Instance.GetRoles( portal.PortalID, role => role.AutoAssignment && @@ -85,7 +85,7 @@ public void AddPortalToGroup(PortalInfo portal, PortalGroupInfo portalGroup, Use { RoleController.Instance.AddUserRole(portalGroup.MasterPortalId, user.UserID, autoAssignRole.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); } - + this.OnUserAddedToSiteGroup(callback, portal, user, totalUsers, userNo); } } @@ -116,7 +116,7 @@ public int AddPortalGroup(PortalGroupInfo portalGroup) portal.PortalGroupID = portalGroup.PortalGroupId; this._portalController.UpdatePortalInfo(portal); } - + this.LogEvent(EventLogController.EventLogType.PORTALGROUP_CREATED, portalGroup, null); ClearCache(); @@ -145,11 +145,137 @@ public void DeletePortalGroup(PortalGroupInfo portalGroup) ClearCache(); } + public IEnumerable GetPortalGroups() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PortalGroupsCacheKey, + DataCache.PortalGroupsCacheTimeOut, + DataCache.PortalGroupsCachePriority), + this.GetPortalGroupsCallback); + } + + public IEnumerable GetPortalsByGroup(int portalGroupId) + { + var portals = PortalController.Instance.GetPortals(); + + return portals.Cast() + .Where(portal => portal.PortalGroupID == portalGroupId) + .ToList(); + } + + public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup, bool copyUsers, UserCopiedCallback callback) + { + // Argument Contract + 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); + + // Callback to update progress bar + var args = new UserCopiedEventArgs + { + TotalUsers = 0, + UserNo = 0, + UserName = string.Empty, + PortalName = portal.PortalName, + Stage = "startingremove", + }; + callback(args); + + // Remove portal from group + this.DeleteSharedModules(portal); + portal.PortalGroupID = -1; + PortalController.Instance.UpdatePortalInfo(portal); + this.LogEvent(EventLogController.EventLogType.PORTAL_REMOVEDFROMPORTALGROUP, portalGroup, portal); + + this.CopyPropertyDefinitions(portal.PortalID, portalGroup.MasterPortalId); + + var userNo = 0; + if (copyUsers) + { + var users = UserController.GetUsers(portalGroup.MasterPortalId); + foreach (UserInfo masterUser in users) + { + userNo += 1; + + UserController.CopyUserToPortal(masterUser, portal, false); + + // Callback to update progress bar + args = new UserCopiedEventArgs + { + TotalUsers = users.Count, + UserNo = userNo, + UserName = masterUser.Username, + PortalName = portal.PortalName, + }; + + callback(args); + } + } + else + { + // Get admin users + var adminUsers = RoleController.Instance.GetUsersByRole(Null.NullInteger, portal.AdministratorRoleName) + .Where(u => RoleController.Instance.GetUserRole(portal.PortalID, u.UserID, portal.AdministratorRoleId) != null); + + foreach (var user in adminUsers) + { + UserController.CopyUserToPortal(user, portal, false); + + // Callback to update progress bar + args = new UserCopiedEventArgs + { + TotalUsers = 1, + UserNo = ++userNo, + UserName = user.Username, + PortalName = portal.PortalName, + }; + + callback(args); + } + } + + // Callback to update progress bar + args = new UserCopiedEventArgs + { + TotalUsers = 1, + UserNo = userNo, + UserName = string.Empty, + PortalName = portal.PortalName, + Stage = "finishedremove", + PortalGroupId = portalGroup.PortalGroupId, + }; + callback(args); + } + + public void UpdatePortalGroup(PortalGroupInfo portalGroup) + { + // Argument Contract + Requires.NotNull("portalGroup", portalGroup); + Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); + + this._dataService.UpdatePortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); + + ClearCache(); + } + + public bool IsModuleShared(int moduleId, PortalInfo portal) + { + if (portal == null) + { + return false; + } + + return this.GetSharedModulesWithPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted) || this.GetSharedModulesByPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted); + } + private static void ClearCache() { DataCache.RemoveCache(DataCache.PortalGroupsCacheKey); } - + private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) { return CBO.FillCollection(this._dataService.GetPortalGroups()); @@ -157,11 +283,11 @@ private object GetPortalGroupsCallback(CacheItemArgs cacheItemArgs) private void OnAddPortalToGroupStart(UserCopiedCallback callback, PortalInfo portal) { - if (callback == null) - { - return; - } - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = 0, @@ -175,11 +301,11 @@ private void OnAddPortalToGroupStart(UserCopiedCallback callback, PortalInfo por private void OnUserAddedToSiteGroup(UserCopiedCallback callback, PortalInfo portal, UserInfo currentUser, int totalUsers, int currentUserNumber) { - if (callback == null) - { - return; - } - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, @@ -192,11 +318,11 @@ private void OnUserAddedToSiteGroup(UserCopiedCallback callback, PortalInfo port private void OnAddPortalToGroupFinishing(UserCopiedCallback callback, PortalInfo portal, int totalUsers) { - if (callback == null) - { - return; - } - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, @@ -210,11 +336,11 @@ private void OnAddPortalToGroupFinishing(UserCopiedCallback callback, PortalInfo private void OnAddPortalToGroupFinished(UserCopiedCallback callback, PortalInfo portal, PortalGroupInfo portalGroup, int totalUsers) { - if (callback == null) - { - return; - } - + if (callback == null) + { + return; + } + var args = new UserCopiedEventArgs { TotalUsers = totalUsers, @@ -243,14 +369,14 @@ private void LogEvent(EventLogController.EventLogType eventType, PortalGroupInfo log.LogProperties.Add(new LogDetailInfo("Portal:", portal.PortalName)); log.LogProperties.Add(new LogDetailInfo("PortalID:", portal.PortalID.ToString())); } - + LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); } - } + } private void RemoveProfileDefinitions(PortalInfo portal) { @@ -288,8 +414,8 @@ private void DeleteSharedModules(PortalInfo portal) private IEnumerable GetSharedModulesWithPortal(PortalInfo portal) { - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( DataCache.SharedModulesWithPortalCacheKey, DataCache.SharedModulesWithPortalCacheTimeOut, DataCache.SharedModulesWithPortalCachePriority, @@ -299,139 +425,13 @@ private IEnumerable GetSharedModulesWithPortal(PortalInfo portal) private IEnumerable GetSharedModulesByPortal(PortalInfo portal) { - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( DataCache.SharedModulesByPortalCacheKey, DataCache.SharedModulesByPortalCacheTimeOut, DataCache.SharedModulesByPortalCachePriority, portal), (p) => CBO.FillCollection(this._dataService.GetSharedModulesByPortal(portal))); } - - public IEnumerable GetPortalGroups() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.PortalGroupsCacheKey, - DataCache.PortalGroupsCacheTimeOut, - DataCache.PortalGroupsCachePriority), - this.GetPortalGroupsCallback); - } - - public IEnumerable GetPortalsByGroup(int portalGroupId) - { - var portals = PortalController.Instance.GetPortals(); - - return portals.Cast() - .Where(portal => portal.PortalGroupID == portalGroupId) - .ToList(); - } - - public void RemovePortalFromGroup(PortalInfo portal, PortalGroupInfo portalGroup, bool copyUsers, UserCopiedCallback callback) - { - // Argument Contract - 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); - - // Callback to update progress bar - var args = new UserCopiedEventArgs - { - TotalUsers = 0, - UserNo = 0, - UserName = string.Empty, - PortalName = portal.PortalName, - Stage = "startingremove", - }; - callback(args); - - // Remove portal from group - this.DeleteSharedModules(portal); - portal.PortalGroupID = -1; - PortalController.Instance.UpdatePortalInfo(portal); - this.LogEvent(EventLogController.EventLogType.PORTAL_REMOVEDFROMPORTALGROUP, portalGroup, portal); - - this.CopyPropertyDefinitions(portal.PortalID, portalGroup.MasterPortalId); - - var userNo = 0; - if (copyUsers) - { - var users = UserController.GetUsers(portalGroup.MasterPortalId); - foreach (UserInfo masterUser in users) - { - userNo += 1; - - UserController.CopyUserToPortal(masterUser, portal, false); - - // Callback to update progress bar - args = new UserCopiedEventArgs - { - TotalUsers = users.Count, - UserNo = userNo, - UserName = masterUser.Username, - PortalName = portal.PortalName, - }; - - callback(args); - } - } - else - { - // Get admin users - var adminUsers = RoleController.Instance.GetUsersByRole(Null.NullInteger, portal.AdministratorRoleName) - .Where(u => RoleController.Instance.GetUserRole(portal.PortalID, u.UserID, portal.AdministratorRoleId) != null); - - foreach (var user in adminUsers) - { - UserController.CopyUserToPortal(user, portal, false); - - // Callback to update progress bar - args = new UserCopiedEventArgs - { - TotalUsers = 1, - UserNo = ++userNo, - UserName = user.Username, - PortalName = portal.PortalName, - }; - - callback(args); - } - } - - // Callback to update progress bar - args = new UserCopiedEventArgs - { - TotalUsers = 1, - UserNo = userNo, - UserName = string.Empty, - PortalName = portal.PortalName, - Stage = "finishedremove", - PortalGroupId = portalGroup.PortalGroupId, - }; - callback(args); - } - - public void UpdatePortalGroup(PortalGroupInfo portalGroup) - { - // Argument Contract - Requires.NotNull("portalGroup", portalGroup); - Requires.PropertyNotNegative("portalGroup", "PortalGroupId", portalGroup.PortalGroupId); - - this._dataService.UpdatePortalGroup(portalGroup, UserController.Instance.GetCurrentUserInfo().UserID); - - ClearCache(); - } - - public bool IsModuleShared(int moduleId, PortalInfo portal) - { - if (portal == null) - { - return false; - } - - return this.GetSharedModulesWithPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted) || this.GetSharedModulesByPortal(portal).Any(x => x.ModuleID == moduleId && !x.IsDeleted); - } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs b/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs index bc3d2f292fd..3d9a9678854 100644 --- a/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalGroupInfo.cs @@ -13,12 +13,6 @@ namespace DotNetNuke.Entities.Portals [Serializable] public class PortalGroupInfo : BaseEntityInfo, IHydratable { - public int PortalGroupId { get; set; } - - public string AuthenticationDomain { get; set; } - - public int MasterPortalId { get; set; } - public string MasterPortalName { get @@ -32,24 +26,30 @@ public string MasterPortalName portalName = portal.PortalName; } } - + return portalName; } } + public int PortalGroupId { get; set; } + + public string AuthenticationDomain { get; set; } + + public int MasterPortalId { get; set; } + [Required] public string PortalGroupDescription { get; set; } [Required] - public string PortalGroupName { get; set; } - + public string PortalGroupName { get; set; } + public int KeyID { get { return this.PortalGroupId; } - + set { this.PortalGroupId = value; @@ -65,6 +65,6 @@ public void Fill(IDataReader dr) this.PortalGroupDescription = Null.SetNullString(dr["PortalGroupDescription"]); this.MasterPortalId = Null.SetNullInteger(dr["MasterPortalID"]); this.AuthenticationDomain = Null.SetNullString(dr["AuthenticationDomain"]); - } + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalInfo.cs b/DNN Platform/Library/Entities/Portals/PortalInfo.cs index 851f9d25fa1..f9f1af923c0 100644 --- a/DNN Platform/Library/Entities/Portals/PortalInfo.cs +++ b/DNN Platform/Library/Entities/Portals/PortalInfo.cs @@ -50,14 +50,14 @@ namespace DotNetNuke.Entities.Portals [XmlRoot("settings", IsNullable = false)] [Serializable] public class PortalInfo : BaseEntityInfo, IHydratable - { + { private string _administratorRoleName; private int _pages = Null.NullInteger; - private string _registeredRoleName; + private string _registeredRoleName; private int _users; - - /// + + /// /// Initializes a new instance of the class. /// Create new Portalinfo instance. /// @@ -74,8 +74,78 @@ public class PortalInfo : BaseEntityInfo, IHydratable public PortalInfo() { this.Users = Null.NullInteger; - } - + } + + /// + /// Gets or sets the footer text as specified in the Portal settings. + /// + /// Footer text of the portal. + /// Returns the the footer text of the portal. + /// + /// This show the usage of the FooterText property + /// + /// txtFooterText.Text = objPortal.FooterText + /// + /// + /// + [XmlElement("footertext")] + public string FooterText { get; set; } + + /// + /// Gets or sets home directory of the portal (logical path). + /// + /// Portal home directory. + /// Portal home directory. + /// + [XmlElement("homedirectory")] + public string HomeDirectory { get; set; } + + /// + /// Gets home System (local) directory of the portal (logical path). + /// + /// Portal home system directory. + /// Portal home system directory in local filesystem. + /// + [XmlElement("homesystemdirectory")] + public string HomeSystemDirectory + { + get { return string.Format("{0}-System", this.HomeDirectory); } + } + + /// + /// Gets fysical path on disk of the home directory of the portal. + /// + /// + /// Fysical path on disk of the home directory of the portal + /// + /// Fully qualified path of the home directory. + /// + [XmlIgnore] + public string HomeDirectoryMapPath + { + get + { + return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeDirectory.Replace("/", "\\")); + } + } + + /// + /// Gets fysical path on disk of the home directory of the portal. + /// + /// + /// Fysical path on disk of the home directory of the portal + /// + /// Fully qualified path of the home system (local) directory. + /// + [XmlIgnore] + public string HomeSystemDirectoryMapPath + { + get + { + return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeSystemDirectory.Replace("/", "\\")); + } + } + /// /// Gets or sets userID of the user who is the admininistrator of the portal. /// @@ -226,20 +296,6 @@ public PortalInfo() [XmlElement("expirydate")] public DateTime ExpiryDate { get; set; } - /// - /// Gets or sets the footer text as specified in the Portal settings. - /// - /// Footer text of the portal. - /// Returns the the footer text of the portal. - /// - /// This show the usage of the FooterText property - /// - /// txtFooterText.Text = objPortal.FooterText - /// - /// - /// - [XmlElement("footertext")] - public string FooterText { get; set; } /// /// Gets or sets gUID of the portal info object. @@ -250,26 +306,6 @@ public PortalInfo() [XmlIgnore] public Guid GUID { get; set; } - /// - /// Gets or sets home directory of the portal (logical path). - /// - /// Portal home directory. - /// Portal home directory. - /// - [XmlElement("homedirectory")] - public string HomeDirectory { get; set; } - - /// - /// Gets home System (local) directory of the portal (logical path). - /// - /// Portal home system directory. - /// Portal home system directory in local filesystem. - /// - [XmlElement("homesystemdirectory")] - public string HomeSystemDirectory - { - get { return string.Format("{0}-System", this.HomeDirectory); } - } /// /// Gets or sets tabdId of the Home page. @@ -314,8 +350,8 @@ 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. /// @@ -441,8 +477,8 @@ public string HomeSystemDirectory /// /// Gets or sets payment Processor userId. /// - /// - /// Payment Processor userId + /// + /// Payment Processor userId /// /// /// @@ -615,10 +651,10 @@ public int Users { this._users = UserController.GetUserCountByPortal(this.PortalID); } - + return this._users; } - + set { this._users = value; } } @@ -629,8 +665,8 @@ public int Users /// Version # of the portal installation. /// [XmlElement("version")] - public string Version { get; set; } - + public string Version { get; set; } + /// /// Gets or sets the actual name of the Administrators group of the portal. /// This name is retrieved from the RoleController object. @@ -652,50 +688,16 @@ public string AdministratorRoleName this._administratorRoleName = adminRole.RoleName; } } - + return this._administratorRoleName; } - + set { this._administratorRoleName = value; } } - /// - /// Gets fysical path on disk of the home directory of the portal. - /// - /// - /// Fysical path on disk of the home directory of the portal - /// - /// Fully qualified path of the home directory. - /// - [XmlIgnore] - public string HomeDirectoryMapPath - { - get - { - return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeDirectory.Replace("/", "\\")); - } - } - - /// - /// Gets fysical path on disk of the home directory of the portal. - /// - /// - /// Fysical path on disk of the home directory of the portal - /// - /// Fully qualified path of the home system (local) directory. - /// - [XmlIgnore] - public string HomeSystemDirectoryMapPath - { - get - { - return string.Format("{0}\\{1}\\", Globals.ApplicationMapPath, this.HomeSystemDirectory.Replace("/", "\\")); - } - } - /// /// Gets or sets actual number of pages of the portal. /// @@ -711,10 +713,10 @@ public int Pages { this._pages = TabController.Instance.GetUserTabsByPortal(this.PortalID).Count; } - + return this._pages; } - + set { this._pages = value; @@ -742,19 +744,19 @@ public string RegisteredRoleName this._registeredRoleName = regUsersRole.RoleName; } } - + return this._registeredRoleName; } - + set { this._registeredRoleName = value; } - } - + } + [XmlIgnore] [Obsolete("Deprecated in DNN 6.0. Scheduled removal in v10.0.0.")] - public int TimeZoneOffset { get; set; } + public int TimeZoneOffset { get; set; } /// /// Gets or sets and sets the Key ID. @@ -767,13 +769,13 @@ public int KeyID { return this.PortalID; } - + set { this.PortalID = value; } - } - + } + /// /// Fills a PortalInfo from a Data Reader. /// @@ -832,7 +834,7 @@ public void Fill(IDataReader dr) // for backward compatibility this.ProcessorPassword = p; } - + this.SplashTabId = Null.SetNullInteger(dr["SplashTabID"]); this.HomeTabId = Null.SetNullInteger(dr["HomeTabID"]); this.LoginTabId = Null.SetNullInteger(dr["LoginTabID"]); @@ -848,13 +850,13 @@ public void Fill(IDataReader dr) { this.Custom404TabId = Null.SetNullInteger(dr["Custom404TabId"]); } - + if (schema.Select("ColumnName = 'Custom500TabId'").Length > 0) { this.Custom500TabId = Null.SetNullInteger(dr["Custom500TabId"]); } } - + this.TermsTabId = Null.SetNullInteger(dr["TermsTabId"]); this.PrivacyTabId = Null.SetNullInteger(dr["PrivacyTabId"]); diff --git a/DNN Platform/Library/Entities/Portals/PortalSettings.cs b/DNN Platform/Library/Entities/Portals/PortalSettings.cs index 8203daa6e72..c9ab45864d0 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettings.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettings.cs @@ -44,6 +44,40 @@ public PortalSettings(int tabId, int portalId) this.BuildPortalSettings(tabId, portal); } + /// ----------------------------------------------------------------------------- + /// + /// Initializes a new instance of the class. + /// The PortalSettings Constructor encapsulates all of the logic + /// necessary to obtain configuration settings necessary to render + /// a Portal Tab view for a given request. + /// + /// + /// + /// The current tab. + /// The current portal. + /// ----------------------------------------------------------------------------- + public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) + { + this.PortalId = portalAliasInfo.PortalID; + this.PortalAlias = portalAliasInfo; + var portal = string.IsNullOrEmpty(portalAliasInfo.CultureCode) ? + PortalController.Instance.GetPortal(portalAliasInfo.PortalID) + : PortalController.Instance.GetPortal(portalAliasInfo.PortalID, portalAliasInfo.CultureCode); + + this.BuildPortalSettings(tabId, portal); + } + + public PortalSettings(PortalInfo portal) + : this(Null.NullInteger, portal) + { + } + + public PortalSettings(int tabId, PortalInfo portal) + { + this.PortalId = portal != null ? portal.PortalID : Null.NullInteger; + this.BuildPortalSettings(tabId, portal); + } + public enum ControlPanelPermission { TabEditor, @@ -72,81 +106,205 @@ public enum UserDeleteAction HardDelete = 3, } - /// ----------------------------------------------------------------------------- - /// - /// Initializes a new instance of the class. - /// The PortalSettings Constructor encapsulates all of the logic - /// necessary to obtain configuration settings necessary to render - /// a Portal Tab view for a given request. - /// - /// - /// - /// The current tab. - /// The current portal. - /// ----------------------------------------------------------------------------- - public PortalSettings(int tabId, PortalAliasInfo portalAliasInfo) + public static PortalSettings Current { - this.PortalId = portalAliasInfo.PortalID; - this.PortalAlias = portalAliasInfo; - var portal = string.IsNullOrEmpty(portalAliasInfo.CultureCode) ? - PortalController.Instance.GetPortal(portalAliasInfo.PortalID) - : PortalController.Instance.GetPortal(portalAliasInfo.PortalID, portalAliasInfo.CultureCode); - - this.BuildPortalSettings(tabId, portal); + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } } - public PortalSettings(PortalInfo portal) - : this(Null.NullInteger, portal) + public CacheLevel Cacheability { + get + { + return CacheLevel.fullyCacheable; + } } - public PortalSettings(int tabId, PortalInfo portal) + public bool ControlPanelVisible { - this.PortalId = portal != null ? portal.PortalID : Null.NullInteger; - this.BuildPortalSettings(tabId, portal); + get + { + var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + this.PortalId)); + return string.IsNullOrEmpty(setting) ? this.DefaultControlPanelVisibility : Convert.ToBoolean(setting); + } } - public static PortalSettings Current + public string DefaultPortalAlias { get { - return PortalController.Instance.GetCurrentPortalSettings(); + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId).Where(alias => alias.IsPrimary)) + { + return alias.HTTPAlias; + } + + return string.Empty; } } - public TabInfo ActiveTab { get; set; } + public PortalAliasMapping PortalAliasMappingMode + { + get + { + return PortalSettingsController.Instance().GetPortalAliasMappingMode(this.PortalId); + } + } - public int AdministratorId { get; set; } + /// Gets the currently logged in user identifier. + /// The user identifier. + public int UserId + { + get + { + if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) + { + return this.UserInfo.UserID; + } - public int AdministratorRoleId { get; set; } + return Null.NullInteger; + } + } - private void BuildPortalSettings(int tabId, PortalInfo portal) + /// Gets the currently logged in user. + /// The current user information. + public UserInfo UserInfo { - PortalSettingsController.Instance().LoadPortalSettings(this); + get + { + return UserController.Instance.GetCurrentUserInfo(); + } + } - if (portal == null) + public Mode UserMode + { + get { - return; + Mode mode; + if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) + { + mode = this.DefaultControlPanelMode; + string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + this.PortalId)); + switch (setting.ToUpper()) + { + case "VIEW": + mode = Mode.View; + break; + case "EDIT": + mode = Mode.Edit; + break; + case "LAYOUT": + mode = Mode.Layout; + break; + } + } + else + { + mode = Mode.View; + } + + return mode; } + } - PortalSettingsController.Instance().LoadPortal(portal, this); + /// + /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (if either this specific portal or the entire instance is locked). If locked, any actions which update the database should be disabled. + /// + public bool IsLocked + { + get { return this.IsThisPortalLocked || Host.Host.IsLocked; } + } - var key = string.Join(":", "ActiveTab", portal.PortalID.ToString(), tabId.ToString()); - var items = HttpContext.Current != null ? HttpContext.Current.Items : null; - if (items != null && items.Contains(key)) + /// + /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (note, the entire instance may still be locked, this only indicates whether this portal is specifically locked). If locked, any actions which update the database should be disabled. + /// + public bool IsThisPortalLocked + { + get { return PortalController.GetPortalSettingAsBoolean("IsLocked", this.PortalId, false); } + } + + public string PageHeadText + { + get { - this.ActiveTab = items[key] as TabInfo; + // For New Install + string pageHead = ""; + string setting; + if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("PageHeadText", out setting)) + { + // Hack to store empty string portalsetting with non empty default value + pageHead = (setting == "false") ? string.Empty : setting; + } + + return pageHead; } - else + } + + /* + * add on the top of the module + * + * Desactivate this remove the html5 compatibility warnings + * (and make the output smaller) + * + */ + public bool InjectModuleHyperLink + { + get { - this.ActiveTab = PortalSettingsController.Instance().GetActiveTab(tabId, this); - if (items != null && this.ActiveTab != null) + return PortalController.GetPortalSettingAsBoolean("InjectModuleHyperLink", this.PortalId, true); + } + } + + /* + * generates a : Page.Response.AddHeader("X-UA-Compatible", ""); + * + + */ + public string AddCompatibleHttpHeader + { + get + { + string CompatibleHttpHeader = "IE=edge"; + string setting; + if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("AddCompatibleHttpHeader", out setting)) { - items[key] = this.ActiveTab; + // Hack to store empty string portalsetting with non empty default value + CompatibleHttpHeader = (setting == "false") ? string.Empty : setting; } + + return CompatibleHttpHeader; + } + } + + /// + /// Gets a value indicating whether if true then add a cachebuster parameter to generated file URI's. + /// + public bool AddCachebusterToResourceUris + { + get + { + return PortalController.GetPortalSettingAsBoolean("AddCachebusterToResourceUris", this.PortalId, true); + } + } + + /// + /// Gets a value indicating whether if this is true, then regular users can't send message to specific user/group. + /// + public bool DisablePrivateMessage + { + get + { + return PortalController.GetPortalSetting("DisablePrivateMessage", this.PortalId, "N") == "Y"; } } + 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; } @@ -429,193 +587,8 @@ private void BuildPortalSettings(int tabId, PortalInfo portal) public int SMTPMaxIdleTime { get; internal set; } - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - - public bool ControlPanelVisible - { - get - { - var setting = Convert.ToString(Personalization.GetProfile("Usability", "ControlPanelVisible" + this.PortalId)); - return string.IsNullOrEmpty(setting) ? this.DefaultControlPanelVisibility : Convert.ToBoolean(setting); - } - } - - public string DefaultPortalAlias - { - get - { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId).Where(alias => alias.IsPrimary)) - { - return alias.HTTPAlias; - } - - return string.Empty; - } - } - - public PortalAliasMapping PortalAliasMappingMode - { - get - { - return PortalSettingsController.Instance().GetPortalAliasMappingMode(this.PortalId); - } - } - - /// Gets the currently logged in user identifier. - /// The user identifier. - public int UserId - { - get - { - if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) - { - return this.UserInfo.UserID; - } - - return Null.NullInteger; - } - } - - /// Gets the currently logged in user. - /// The current user information. - public UserInfo UserInfo - { - get - { - return UserController.Instance.GetCurrentUserInfo(); - } - } - - public Mode UserMode - { - get - { - Mode mode; - if (HttpContext.Current != null && HttpContext.Current.Request.IsAuthenticated) - { - mode = this.DefaultControlPanelMode; - string setting = Convert.ToString(Personalization.GetProfile("Usability", "UserMode" + this.PortalId)); - switch (setting.ToUpper()) - { - case "VIEW": - mode = Mode.View; - break; - case "EDIT": - mode = Mode.Edit; - break; - case "LAYOUT": - mode = Mode.Layout; - break; - } - } - else - { - mode = Mode.View; - } - - return mode; - } - } - - /// - /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (if either this specific portal or the entire instance is locked). If locked, any actions which update the database should be disabled. - /// - public bool IsLocked - { - get { return this.IsThisPortalLocked || Host.Host.IsLocked; } - } - - /// - /// Gets a value indicating whether get a value indicating whether the current portal is in maintenance mode (note, the entire instance may still be locked, this only indicates whether this portal is specifically locked). If locked, any actions which update the database should be disabled. - /// - public bool IsThisPortalLocked - { - get { return PortalController.GetPortalSettingAsBoolean("IsLocked", this.PortalId, false); } - } - public TimeZoneInfo TimeZone { get; set; } = TimeZoneInfo.Local; - public string PageHeadText - { - get - { - // For New Install - string pageHead = ""; - string setting; - if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("PageHeadText", out setting)) - { - // Hack to store empty string portalsetting with non empty default value - pageHead = (setting == "false") ? string.Empty : setting; - } - - return pageHead; - } - } - - /* - * add on the top of the module - * - * Desactivate this remove the html5 compatibility warnings - * (and make the output smaller) - * - */ - public bool InjectModuleHyperLink - { - get - { - return PortalController.GetPortalSettingAsBoolean("InjectModuleHyperLink", this.PortalId, true); - } - } - - /* - * generates a : Page.Response.AddHeader("X-UA-Compatible", ""); - * - - */ - public string AddCompatibleHttpHeader - { - get - { - string CompatibleHttpHeader = "IE=edge"; - string setting; - if (PortalController.Instance.GetPortalSettings(this.PortalId).TryGetValue("AddCompatibleHttpHeader", out setting)) - { - // Hack to store empty string portalsetting with non empty default value - CompatibleHttpHeader = (setting == "false") ? string.Empty : setting; - } - - return CompatibleHttpHeader; - } - } - - /// - /// Gets a value indicating whether if true then add a cachebuster parameter to generated file URI's. - /// - public bool AddCachebusterToResourceUris - { - get - { - return PortalController.GetPortalSettingAsBoolean("AddCachebusterToResourceUris", this.PortalId, true); - } - } - - /// - /// Gets a value indicating whether if this is true, then regular users can't send message to specific user/group. - /// - public bool DisablePrivateMessage - { - get - { - return PortalController.GetPortalSetting("DisablePrivateMessage", this.PortalId, "N") == "Y"; - } - } - /// /// Gets a value indicating whether if true then all users will be pushed through the data consent workflow. /// @@ -876,5 +849,32 @@ public PortalSettings Clone() { return (PortalSettings)this.MemberwiseClone(); } + + private void BuildPortalSettings(int tabId, PortalInfo portal) + { + PortalSettingsController.Instance().LoadPortalSettings(this); + + if (portal == null) + { + return; + } + + PortalSettingsController.Instance().LoadPortal(portal, this); + + var key = string.Join(":", "ActiveTab", portal.PortalID.ToString(), tabId.ToString()); + var items = HttpContext.Current != null ? HttpContext.Current.Items : null; + if (items != null && items.Contains(key)) + { + this.ActiveTab = items[key] as TabInfo; + } + else + { + this.ActiveTab = PortalSettingsController.Instance().GetActiveTab(tabId, this); + if (items != null && this.ActiveTab != null) + { + items[key] = this.ActiveTab; + } + } + } } } diff --git a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs index 12450eb24e0..c276a6e193c 100644 --- a/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs +++ b/DNN Platform/Library/Entities/Portals/PortalSettingsController.cs @@ -38,11 +38,11 @@ public virtual void ConfigureActiveTab(PortalSettings portalSettings) { var activeTab = portalSettings.ActiveTab; - if (activeTab == null || activeTab.TabID == Null.NullInteger) - { - return; - } - + if (activeTab == null || activeTab.TabID == Null.NullInteger) + { + return; + } + this.UpdateSkinSettings(activeTab, portalSettings); activeTab.BreadCrumbs = new ArrayList(this.GetBreadcrumbs(activeTab.TabID, portalSettings.PortalId)); @@ -76,7 +76,7 @@ public virtual TabInfo GetActiveTab(int tabId, PortalSettings portalSettings) { activeTab.StartDate = DateTime.MinValue; } - + if (Null.IsNull(activeTab.EndDate)) { activeTab.EndDate = DateTime.MaxValue; @@ -105,7 +105,7 @@ public virtual PortalSettings.PortalAliasMapping GetPortalAliasMappingMode(int p break; } } - + return aliasMapping; } @@ -159,64 +159,6 @@ 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); @@ -292,10 +234,10 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) if (!string.IsNullOrEmpty(setting)) { var timeZone = TimeZoneInfo.FindSystemTimeZoneById(setting); - if (timeZone != null) - { - portalSettings.TimeZone = timeZone; - } + if (timeZone != null) + { + portalSettings.TimeZone = timeZone; + } } setting = settings.GetValueOrDefault("DataConsentActive", "False"); @@ -305,7 +247,7 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) { portalSettings.DataConsentTermsLastChange = DateTime.Parse(setting, System.Globalization.CultureInfo.InvariantCulture); } - + setting = settings.GetValueOrDefault("DataConsentConsentRedirect", "-1"); portalSettings.DataConsentConsentRedirect = int.Parse(setting); setting = settings.GetValueOrDefault("DataConsentUserDeleteAction", "0"); @@ -318,6 +260,13 @@ public virtual void LoadPortalSettings(PortalSettings portalSettings) portalSettings.AllowedExtensionsWhitelist = new FileExtensionWhitelist(setting); } + protected List GetBreadcrumbs(int tabId, int portalId) + { + var breadCrumbs = new List(); + GetBreadCrumbs(breadCrumbs, tabId, portalId); + return breadCrumbs; + } + protected virtual void UpdateSkinSettings(TabInfo activeTab, PortalSettings portalSettings) { if (Globals.IsAdminSkin()) @@ -334,7 +283,7 @@ protected virtual void UpdateSkinSettings(TabInfo activeTab, PortalSettings port Host.Host.DefaultPortalSkin, portalSettings.CultureCode)) ? portalSettings.DefaultPortalSkin : PortalController.GetPortalSetting("DefaultPortalSkin", portalSettings.PortalId, Host.Host.DefaultPortalSkin, portalSettings.CultureCode); } - + activeTab.SkinSrc = SkinController.FormatSkinSrc(activeTab.SkinSrc, portalSettings); activeTab.SkinPath = SkinController.FormatSkinPath(activeTab.SkinSrc); @@ -354,5 +303,56 @@ protected virtual void UpdateSkinSettings(TabInfo activeTab, PortalSettings port activeTab.ContainerSrc = SkinController.FormatSkinSrc(activeTab.ContainerSrc, portalSettings); activeTab.ContainerPath = SkinController.FormatSkinPath(activeTab.ContainerSrc); } + + 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; + } } } diff --git a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs index 98380d61e29..4814e923c02 100644 --- a/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs +++ b/DNN Platform/Library/Entities/Portals/UserCopiedEventArgs.cs @@ -7,17 +7,17 @@ namespace DotNetNuke.Entities.Portals public class UserCopiedEventArgs { public bool Cancel { get; set; } - + public string PortalName { get; set; } - + public float TotalUsers { get; set; } - + public string UserName { get; set; } - + public float UserNo { get; set; } - + public string Stage { get; set; } - + public int PortalGroupId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfileController.cs b/DNN Platform/Library/Entities/Profile/ProfileController.cs index a8463561b1b..70b2742bf3c 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileController.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileController.cs @@ -36,11 +36,11 @@ namespace DotNetNuke.Entities.Profile /// ----------------------------------------------------------------------------- public class ProfileController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProfileController)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ProfileController)); private static readonly DataProvider _dataProvider = DataProvider.Instance(); private static readonly ProfileProvider _profileProvider = ProfileProvider.Instance(); - private static int _orderCounter; - + private static int _orderCounter; + /// ----------------------------------------------------------------------------- /// /// Adds the default property definitions for a portal. @@ -99,8 +99,8 @@ public static int AddPropertyDefinition(ProfilePropertyDefinition definition) { definition.Visible = true; } - - int intDefinition = _dataProvider.AddPropertyDefinition( + + int intDefinition = _dataProvider.AddPropertyDefinition( portalId, definition.ModuleDefId, definition.DataType, @@ -121,155 +121,6 @@ public static int AddPropertyDefinition(ProfilePropertyDefinition definition) return intDefinition; } - internal static void AddDefaultDefinition(int portalId, string category, string name, string type, int length, int viewOrder, UserVisibilityMode defaultVisibility, - Dictionary types) - { - ListEntryInfo typeInfo = types["DataType:" + type] ?? types["DataType:Unknown"]; - var propertyDefinition = new ProfilePropertyDefinition(portalId) - { - DataType = typeInfo.EntryID, - DefaultValue = string.Empty, - ModuleDefId = Null.NullInteger, - PropertyCategory = category, - PropertyName = name, - Required = false, - ViewOrder = viewOrder, - Visible = true, - Length = length, - DefaultVisibility = defaultVisibility, - }; - 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) - { - ProfilePropertyDefinition definition = null; - try - { - definition = FillPropertyDefinitionInfo(dr, true); - } - catch (Exception ex) - { - Logger.Error(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return definition; - } - - private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader dr, bool checkForOpenDataReader) - { - ProfilePropertyDefinition definition = null; - - // read datareader - bool canContinue = true; - if (checkForOpenDataReader) - { - canContinue = false; - if (dr.Read()) - { - canContinue = true; - } - } - - if (canContinue) - { - int portalid = 0; - portalid = Convert.ToInt32(Null.SetNull(dr["PortalId"], portalid)); - definition = new ProfilePropertyDefinition(portalid); - definition.PropertyDefinitionId = Convert.ToInt32(Null.SetNull(dr["PropertyDefinitionId"], definition.PropertyDefinitionId)); - definition.ModuleDefId = Convert.ToInt32(Null.SetNull(dr["ModuleDefId"], definition.ModuleDefId)); - definition.DataType = Convert.ToInt32(Null.SetNull(dr["DataType"], definition.DataType)); - definition.DefaultValue = Convert.ToString(Null.SetNull(dr["DefaultValue"], definition.DefaultValue)); - definition.PropertyCategory = Convert.ToString(Null.SetNull(dr["PropertyCategory"], definition.PropertyCategory)); - definition.PropertyName = Convert.ToString(Null.SetNull(dr["PropertyName"], definition.PropertyName)); - definition.Length = Convert.ToInt32(Null.SetNull(dr["Length"], definition.Length)); - if (dr.GetSchemaTable().Select("ColumnName = 'ReadOnly'").Length > 0) - { - definition.ReadOnly = Convert.ToBoolean(Null.SetNull(dr["ReadOnly"], definition.ReadOnly)); - } - - definition.Required = Convert.ToBoolean(Null.SetNull(dr["Required"], definition.Required)); - definition.ValidationExpression = Convert.ToString(Null.SetNull(dr["ValidationExpression"], definition.ValidationExpression)); - definition.ViewOrder = Convert.ToInt32(Null.SetNull(dr["ViewOrder"], definition.ViewOrder)); - definition.Visible = Convert.ToBoolean(Null.SetNull(dr["Visible"], definition.Visible)); - definition.DefaultVisibility = (UserVisibilityMode)Convert.ToInt32(Null.SetNull(dr["DefaultVisibility"], definition.DefaultVisibility)); - definition.ProfileVisibility = new ProfileVisibility - { - VisibilityMode = definition.DefaultVisibility, - }; - definition.Deleted = Convert.ToBoolean(Null.SetNull(dr["Deleted"], definition.Deleted)); - } - - return definition; - } - - private static List FillPropertyDefinitionInfoCollection(IDataReader dr) - { - var arr = new List(); - try - { - while (dr.Read()) - { - // fill business object - ProfilePropertyDefinition definition = FillPropertyDefinitionInfo(dr, false); - - // add to collection - arr.Add(definition); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - - return arr; - } - - private static int GetEffectivePortalId(int portalId) - { - return PortalController.GetEffectivePortalId(portalId); - } - - private static IEnumerable GetPropertyDefinitions(int portalId) - { - // Get the Cache Key - string key = string.Format(DataCache.ProfileDefinitionsCacheKey, portalId); - - // Try fetching the List from the Cache - var definitions = (List)DataCache.GetCache(key); - if (definitions == null) - { - // definitions caching settings - int timeOut = DataCache.ProfileDefinitionsCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); - - // Get the List from the database - definitions = FillPropertyDefinitionInfoCollection(_dataProvider.GetPropertyDefinitionsByPortal(portalId)); - - // Cache the List - if (timeOut > 0) - { - DataCache.SetCache(key, definitions, TimeSpan.FromMinutes(timeOut)); - } - } - - return definitions; - } - /// ----------------------------------------------------------------------------- /// /// Clears the Profile Definitions Cache. @@ -327,13 +178,13 @@ public static ProfilePropertyDefinition GetPropertyDefinition(int definitionId, break; } } - + if (!bFound) { // Try Database definition = FillPropertyDefinitionInfo(_dataProvider.GetPropertyDefinition(definitionId)); } - + return definition; } @@ -360,13 +211,13 @@ public static ProfilePropertyDefinition GetPropertyDefinitionByName(int portalId break; } } - + if (!bFound) { // Try Database definition = FillPropertyDefinitionInfo(_dataProvider.GetPropertyDefinitionByName(portalId, name)); } - + return definition; } @@ -390,7 +241,7 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByCatego definitions.Add(definition); } } - + return definitions; } @@ -440,7 +291,7 @@ public static ProfilePropertyDefinitionCollection GetPropertyDefinitionsByPortal definitions.Add(clone ? definition.Clone() : definition); } } - + return definitions; } @@ -472,8 +323,8 @@ public static void UpdatePropertyDefinition(ProfilePropertyDefinition definition { definition.Visible = true; } - - _dataProvider.UpdatePropertyDefinition( + + _dataProvider.UpdatePropertyDefinition( definition.PropertyDefinitionId, definition.DataType, definition.DefaultValue, @@ -536,7 +387,7 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio user.PortalID = portalId; var photoChanged = Null.NullBoolean; - + // Iterate through the Definitions if (profileProperties != null) { @@ -573,7 +424,7 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio UserController.UpdateUser(portalId, user); } - + return user; } @@ -583,7 +434,7 @@ public static UserInfo UpdateUserProfile(UserInfo user, ProfilePropertyDefinitio /// have been set). /// /// The Id of the portal. - /// The profile. + /// The profile. /// /// ----------------------------------------------------------------------------- public static bool ValidateProfile(int portalId, UserProfile objProfile) @@ -598,7 +449,7 @@ public static bool ValidateProfile(int portalId, UserProfile objProfile) break; } } - + return isValid; } @@ -618,7 +469,7 @@ public static List SearchProfilePropertyValues(int portalId, string prop { return res; } - + using ( IDataReader ir = Data.DataProvider.Instance() .SearchProfilePropertyValues(portalId, propertyName, searchString)) @@ -628,9 +479,164 @@ public static List SearchProfilePropertyValues(int portalId, string prop res.Add(Convert.ToString(ir[0])); } } - + return res; - } + } + + [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) + { + return CBO.FillObject(_dataProvider.GetPropertyDefinition(definitionId)); + } + + internal static void AddDefaultDefinition(int portalId, string category, string name, string type, int length, int viewOrder, UserVisibilityMode defaultVisibility, + Dictionary types) + { + ListEntryInfo typeInfo = types["DataType:" + type] ?? types["DataType:Unknown"]; + var propertyDefinition = new ProfilePropertyDefinition(portalId) + { + DataType = typeInfo.EntryID, + DefaultValue = string.Empty, + ModuleDefId = Null.NullInteger, + PropertyCategory = category, + PropertyName = name, + Required = false, + ViewOrder = viewOrder, + Visible = true, + Length = length, + DefaultVisibility = defaultVisibility, + }; + 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) + { + ProfilePropertyDefinition definition = null; + try + { + definition = FillPropertyDefinitionInfo(dr, true); + } + catch (Exception ex) + { + Logger.Error(ex); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return definition; + } + + private static ProfilePropertyDefinition FillPropertyDefinitionInfo(IDataReader dr, bool checkForOpenDataReader) + { + ProfilePropertyDefinition definition = null; + + // read datareader + bool canContinue = true; + if (checkForOpenDataReader) + { + canContinue = false; + if (dr.Read()) + { + canContinue = true; + } + } + + if (canContinue) + { + int portalid = 0; + portalid = Convert.ToInt32(Null.SetNull(dr["PortalId"], portalid)); + definition = new ProfilePropertyDefinition(portalid); + definition.PropertyDefinitionId = Convert.ToInt32(Null.SetNull(dr["PropertyDefinitionId"], definition.PropertyDefinitionId)); + definition.ModuleDefId = Convert.ToInt32(Null.SetNull(dr["ModuleDefId"], definition.ModuleDefId)); + definition.DataType = Convert.ToInt32(Null.SetNull(dr["DataType"], definition.DataType)); + definition.DefaultValue = Convert.ToString(Null.SetNull(dr["DefaultValue"], definition.DefaultValue)); + definition.PropertyCategory = Convert.ToString(Null.SetNull(dr["PropertyCategory"], definition.PropertyCategory)); + definition.PropertyName = Convert.ToString(Null.SetNull(dr["PropertyName"], definition.PropertyName)); + definition.Length = Convert.ToInt32(Null.SetNull(dr["Length"], definition.Length)); + if (dr.GetSchemaTable().Select("ColumnName = 'ReadOnly'").Length > 0) + { + definition.ReadOnly = Convert.ToBoolean(Null.SetNull(dr["ReadOnly"], definition.ReadOnly)); + } + + definition.Required = Convert.ToBoolean(Null.SetNull(dr["Required"], definition.Required)); + definition.ValidationExpression = Convert.ToString(Null.SetNull(dr["ValidationExpression"], definition.ValidationExpression)); + definition.ViewOrder = Convert.ToInt32(Null.SetNull(dr["ViewOrder"], definition.ViewOrder)); + definition.Visible = Convert.ToBoolean(Null.SetNull(dr["Visible"], definition.Visible)); + definition.DefaultVisibility = (UserVisibilityMode)Convert.ToInt32(Null.SetNull(dr["DefaultVisibility"], definition.DefaultVisibility)); + definition.ProfileVisibility = new ProfileVisibility + { + VisibilityMode = definition.DefaultVisibility, + }; + definition.Deleted = Convert.ToBoolean(Null.SetNull(dr["Deleted"], definition.Deleted)); + } + + return definition; + } + + private static List FillPropertyDefinitionInfoCollection(IDataReader dr) + { + var arr = new List(); + try + { + while (dr.Read()) + { + // fill business object + ProfilePropertyDefinition definition = FillPropertyDefinitionInfo(dr, false); + + // add to collection + arr.Add(definition); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + + return arr; + } + + private static int GetEffectivePortalId(int portalId) + { + return PortalController.GetEffectivePortalId(portalId); + } + + private static IEnumerable GetPropertyDefinitions(int portalId) + { + // Get the Cache Key + string key = string.Format(DataCache.ProfileDefinitionsCacheKey, portalId); + + // Try fetching the List from the Cache + var definitions = (List)DataCache.GetCache(key); + if (definitions == null) + { + // definitions caching settings + int timeOut = DataCache.ProfileDefinitionsCacheTimeOut * Convert.ToInt32(Host.Host.PerformanceSetting); + + // Get the List from the database + definitions = FillPropertyDefinitionInfoCollection(_dataProvider.GetPropertyDefinitionsByPortal(portalId)); + + // Cache the List + if (timeOut > 0) + { + DataCache.SetCache(key, definitions, TimeSpan.FromMinutes(timeOut)); + } + } + + return definitions; + } private static void CreateThumbnails(int fileId) { @@ -658,11 +664,5 @@ private static void CreateThumbnail(int fileId, string type, int width, int heig } } } - - [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) - { - return CBO.FillObject(_dataProvider.GetPropertyDefinition(definitionId)); - } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs index 150b1897082..69a758ca375 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinition.cs @@ -28,7 +28,7 @@ namespace DotNetNuke.Entities.Profile [XmlRoot("profiledefinition", IsNullable = false)] [Serializable] public class ProfilePropertyDefinition : BaseEntityInfo - { + { private int _dataType = Null.NullInteger; private string _defaultValue; private UserVisibilityMode _defaultVisibility = UserVisibilityMode.AdminOnly; @@ -36,11 +36,12 @@ 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; private string _propertyValue; @@ -48,12 +49,12 @@ public class ProfilePropertyDefinition : BaseEntityInfo private bool _required; private string _ValidationExpression; private int _viewOrder; - private bool _visible; - + private bool _visible; + public ProfilePropertyDefinition() { this.PropertyDefinitionId = Null.NullInteger; - + // Get the default PortalSettings PortalSettings _Settings = PortalController.Instance.GetCurrentPortalSettings(); this.PortalId = _Settings.PortalId; @@ -63,8 +64,8 @@ public ProfilePropertyDefinition(int portalId) { this.PropertyDefinitionId = Null.NullInteger; this.PortalId = portalId; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Data Type of the Profile Property. @@ -82,14 +83,14 @@ public int DataType { return this._dataType; } - + set { if (this._dataType != value) { this.IsDirty = true; } - + this._dataType = value; } } @@ -107,14 +108,14 @@ public string DefaultValue { return this._defaultValue; } - + set { if (this._defaultValue != value) { this.IsDirty = true; } - + this._defaultValue = value; } } @@ -132,14 +133,14 @@ public UserVisibilityMode DefaultVisibility { return this._defaultVisibility; } - + set { if (this._defaultVisibility != value) { this.IsDirty = true; } - + this._defaultVisibility = value; } } @@ -157,7 +158,7 @@ public bool Deleted { return this._deleted; } - + set { this._deleted = value; @@ -186,14 +187,14 @@ public int Length { return this._length; } - + set { if (this._length != value) { this.IsDirty = true; } - + this._length = value; } } @@ -211,7 +212,7 @@ public int ModuleDefId { return this._moduleDefId; } - + set { this._moduleDefId = value; @@ -231,7 +232,7 @@ public int PortalId { return this._portalId; } - + set { this._portalId = value; @@ -252,14 +253,14 @@ public string PropertyCategory { return this._propertyCategory; } - + set { if (this._propertyCategory != value) { this.IsDirty = true; } - + this._propertyCategory = value; } } @@ -289,14 +290,14 @@ public string PropertyName { return this._propertyName; } - + set { if (this._propertyName != value) { this.IsDirty = true; } - + this._propertyName = value; } } @@ -314,14 +315,14 @@ public string PropertyValue { return this._propertyValue; } - + set { if (this._propertyValue != value) { this.IsDirty = true; } - + this._propertyValue = value; } } @@ -339,14 +340,14 @@ public bool ReadOnly { return this._readOnly; } - + set { if (this._readOnly != value) { this.IsDirty = true; } - + this._readOnly = value; } } @@ -364,14 +365,14 @@ public bool Required { return this._required; } - + set { if (this._required != value) { this.IsDirty = true; } - + this._required = value; } } @@ -389,14 +390,14 @@ public string ValidationExpression { return this._ValidationExpression; } - + set { if (this._ValidationExpression != value) { this.IsDirty = true; } - + this._ValidationExpression = value; } } @@ -415,14 +416,14 @@ public int ViewOrder { return this._viewOrder; } - + set { if (this._viewOrder != value) { this.IsDirty = true; } - + this._viewOrder = value; } } @@ -440,14 +441,14 @@ public bool Visible { return this._visible; } - + set { if (this._visible != value) { this.IsDirty = true; } - + this._visible = value; } } @@ -465,18 +466,18 @@ public ProfileVisibility ProfileVisibility { return this._profileVisibility; } - + set { if (this._profileVisibility != value) { this.IsDirty = true; } - + this._profileVisibility = value; } - } - + } + [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] @@ -486,18 +487,18 @@ public UserVisibilityMode Visibility { return this.ProfileVisibility.VisibilityMode; } - + set { if (this.ProfileVisibility.VisibilityMode != value) { this.IsDirty = true; } - + this.ProfileVisibility.VisibilityMode = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Clears the IsDirty Flag. @@ -514,27 +515,27 @@ public void ClearIsDirty() /// 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, + 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/ProfilePropertyDefinitionCollection.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs index 436f61f3ff7..bea73d0bdfb 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionCollection.cs @@ -20,19 +20,19 @@ namespace DotNetNuke.Entities.Profile /// ----------------------------------------------------------------------------- [Serializable] public class ProfilePropertyDefinitionCollection : CollectionBase - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new default collection. /// /// ----------------------------------------------------------------------------- public ProfilePropertyDefinitionCollection() { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new Collection from an ArrayList of ProfilePropertyDefinition objects. /// @@ -41,10 +41,10 @@ public ProfilePropertyDefinitionCollection() public ProfilePropertyDefinitionCollection(ArrayList definitionsList) { this.AddRange(definitionsList); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new Collection from a ProfilePropertyDefinitionCollection. /// @@ -57,38 +57,38 @@ public ProfilePropertyDefinitionCollection(ProfilePropertyDefinitionCollection c /// ----------------------------------------------------------------------------- /// - /// Gets and sets an item in the collection. + /// Gets an item in the collection. /// - /// This overload returns the item by its index. - /// The index to get. + /// This overload returns the item by its name. + /// The name of the Property to get. /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- - public ProfilePropertyDefinition this[int index] + public ProfilePropertyDefinition this[string name] { get { - return (ProfilePropertyDefinition)this.List[index]; - } - - set - { - this.List[index] = value; + return this.GetByName(name); } } /// ----------------------------------------------------------------------------- /// - /// Gets an item in the collection. + /// Gets and sets an item in the collection. /// - /// This overload returns the item by its name. - /// The name of the Property to get. + /// This overload returns the item by its index. + /// The index to get. /// A ProfilePropertyDefinition object. /// ----------------------------------------------------------------------------- - public ProfilePropertyDefinition this[string name] + public ProfilePropertyDefinition this[int index] { get { - return this.GetByName(name); + return (ProfilePropertyDefinition)this.List[index]; + } + + set + { + this.List[index] = value; } } @@ -161,7 +161,7 @@ public ProfilePropertyDefinitionCollection GetByCategory(string category) collection.Add(profileProperty); } } - + return collection; } @@ -182,7 +182,7 @@ public ProfilePropertyDefinition GetById(int id) profileItem = profileProperty; } } - + return profileItem; } @@ -204,7 +204,7 @@ public ProfilePropertyDefinition GetByName(string name) profileItem = profileProperty; } } - + return profileItem; } diff --git a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs index 6ec3fca6964..5b6b69809c2 100644 --- a/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs +++ b/DNN Platform/Library/Entities/Profile/ProfilePropertyDefinitionComparer.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Entities.Profile /// /// ----------------------------------------------------------------------------- public class ProfilePropertyDefinitionComparer : IComparer - { + { /// ----------------------------------------------------------------------------- /// /// Compares two ProfilePropertyDefinition objects. @@ -30,6 +30,6 @@ public class ProfilePropertyDefinitionComparer : IComparer public int Compare(object x, object y) { return ((ProfilePropertyDefinition)x).ViewOrder.CompareTo(((ProfilePropertyDefinition)y).ViewOrder); - } + } } } diff --git a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs index 44baf3c7f44..ce4c30a9eca 100644 --- a/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs +++ b/DNN Platform/Library/Entities/Profile/ProfileVisibility.cs @@ -23,7 +23,7 @@ public ProfileVisibility() this.RelationshipVisibilities = new List(); } - public ProfileVisibility(int portalId, string extendedVisibility) + public ProfileVisibility(int portalId, string extendedVisibility) : this() { if (!string.IsNullOrEmpty(extendedVisibility)) @@ -42,7 +42,7 @@ public ProfileVisibility(int portalId, string extendedVisibility) this.RoleVisibilities.Add(userRole); } } - + if (!string.IsNullOrEmpty(lists[1].Substring(2).TrimEnd(','))) { var relationships = lists[1].Substring(2).TrimEnd(',').Split(','); @@ -63,11 +63,11 @@ 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; } @@ -82,7 +82,7 @@ public string ExtendedVisibilityString() { sb.Append(role.RoleID.ToString(CultureInfo.InvariantCulture) + ","); } - + sb.Append(";R:"); foreach (var relationship in this.RelationshipVisibilities) { diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs index 1014a19205b..7f8baeda5b4 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabEventHandler.cs @@ -7,15 +7,15 @@ namespace DotNetNuke.Entities.Tabs.Actions public interface ITabEventHandler { void TabCreated(object sender, TabEventArgs args); - + void TabUpdated(object sender, TabEventArgs args); - + void TabRemoved(object sender, TabEventArgs args); - + void TabDeleted(object sender, TabEventArgs args); - + void TabRestored(object sender, TabEventArgs args); - + void TabMarkedAsPublished(object sender, TabEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs index 14a78ebbf30..7088c7c754b 100644 --- a/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs +++ b/DNN Platform/Library/Entities/Tabs/Actions/ITabSyncEventHandler.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Tabs.Actions public interface ITabSyncEventHandler { void TabSerialize(object sender, TabSyncEventArgs args); - + void TabDeserialize(object sender, TabSyncEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs b/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs index 4199a3638f3..9b0f4650f90 100644 --- a/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs +++ b/DNN Platform/Library/Entities/Tabs/Dto/ChangeControlState.cs @@ -14,6 +14,17 @@ namespace DotNetNuke.Entities.Tabs.Dto /// public class ChangeControlState { + /// + /// Gets a value indicating whether gets if change control is enabled for the tab. + /// + /// + /// True if versioning or workflow are enabled, false otherwise. + /// + public bool IsChangeControlEnabledForTab + { + get { return this.IsVersioningEnabledForTab || this.IsWorkflowEnabledForTab; } + } + /// /// Gets or sets the portal id. /// @@ -30,17 +41,6 @@ public class ChangeControlState /// public int TabId { get; set; } - /// - /// Gets a value indicating whether gets if change control is enabled for the tab. - /// - /// - /// True if versioning or workflow are enabled, false otherwise. - /// - public bool IsChangeControlEnabledForTab - { - get { return this.IsVersioningEnabledForTab || this.IsWorkflowEnabledForTab; } - } - /// /// Gets or sets a value indicating whether gets if versioning is enabled for the tab. /// @@ -48,7 +48,7 @@ public bool IsChangeControlEnabledForTab /// True if versioning is enabled, false otherwise. /// public bool IsVersioningEnabledForTab { get; set; } - + /// /// Gets or sets a value indicating whether gets if workflow is enabled for the tab. /// diff --git a/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs b/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs index b86e1515c0b..b89068b171d 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabChangeSettings.cs @@ -23,7 +23,7 @@ public interface ITabChangeSettings /// Get the full state of the tab changes control in a specific tab and its master portal. /// /// Portal Id. - /// Tab Id. + /// Tab Id. /// ChangeControlState GetChangeControlState(int portalId, int tabId); } diff --git a/DNN Platform/Library/Entities/Tabs/ITabController.cs b/DNN Platform/Library/Entities/Tabs/ITabController.cs index 15297f65202..9bc79089dfd 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabController.cs @@ -28,7 +28,7 @@ public interface ITabController /// Adds a tab. /// /// The tab to be added. - /// The tab is added to the end of the current Level. + /// The tab is added to the end of the current Level. /// int AddTab(TabInfo tab); @@ -38,7 +38,7 @@ public interface ITabController /// The tab to be added. /// Flag that indicates whether to add the "AllTabs" /// Modules. - /// The tab is added to the end of the current Level. + /// The tab is added to the end of the current Level. /// int AddTab(TabInfo tab, bool includeAllTabsModules); @@ -46,7 +46,7 @@ public interface ITabController /// Adds a tab after the specified tab. /// /// The tab to be added. - /// Id of the tab after which this tab is added. + /// Id of the tab after which this tab is added. /// int AddTabAfter(TabInfo tab, int afterTabId); @@ -54,7 +54,7 @@ public interface ITabController /// Adds a tab before the specified tab. /// /// The tab to be added. - /// Id of the tab before which this tab is added. + /// Id of the tab before which this tab is added. /// int AddTabBefore(TabInfo objTab, int beforeTabId); @@ -139,7 +139,7 @@ public interface ITabController /// /// /// - /// + /// /// bool DeleteTranslatedTabs(int portalId, string cultureCode, bool clearCache); @@ -233,7 +233,7 @@ public interface ITabController /// The portal id. /// tab collection. TabCollection GetUserTabsByPortal(int portalId); - + /// /// Get the actual visible tabs for a given portal id. /// System Tabs and Admin Tabs are excluded from the result set. diff --git a/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs b/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs index 8dd0174c309..9062d6aee15 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabModulesController.cs @@ -14,7 +14,7 @@ public interface ITabModulesController /// /// Returns an array of Modules well configured to be used into a Skin. /// - /// TabInfo object. + /// TabInfo object. /// ArrayList GetTabModules(TabInfo tab); @@ -22,7 +22,7 @@ public interface ITabModulesController /// Gets a collection of all setting values of that contains the /// setting name in its collection of settings. /// - /// Name of the setting to look for. + /// Name of the setting to look for. /// Dictionary GetTabModuleSettingsByName(string settingName); @@ -31,7 +31,7 @@ public interface ITabModulesController /// specific value in its collection of settings. /// /// Name of the setting to look for. - /// Value of the setting to look for. + /// Value of the setting to look for. /// IList GetTabModuleIdsBySetting(string settingName, string expectedValue); } diff --git a/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs index 62f2abcd520..2e4d49871e4 100644 --- a/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/ITabPublishingController.cs @@ -12,7 +12,7 @@ public interface ITabPublishingController /// Check if a page is published or not. /// /// Tha tab Id. - /// The portal ID where the tab is. + /// The portal ID where the tab is. /// bool IsTabPublished(int tabID, int portalID); @@ -28,7 +28,7 @@ public interface ITabPublishingController /// Check if Publish/Unpublish page actions can be performed. /// /// The tab ID. - /// The portal ID where the tab is. + /// The portal ID where the tab is. /// bool CanPublishingBePerformed(int tabID, int portalID); } diff --git a/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs b/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs index 4cb6359980c..f33aa31be13 100644 --- a/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs +++ b/DNN Platform/Library/Entities/Tabs/PermissionsNotMetException.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Tabs public class PermissionsNotMetException : TabException { - public PermissionsNotMetException(int tabId, string message) + public PermissionsNotMetException(int tabId, string message) : base(tabId, message) { } diff --git a/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs b/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs index b39d71d24f4..c4c801872e1 100644 --- a/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabAliasSkinInfo.cs @@ -14,17 +14,17 @@ namespace DotNetNuke.Entities.Tabs /// [Serializable] public class TabAliasSkinInfo : BaseEntityInfo, IHydratable - { + { public int TabAliasSkinId { get; set; } - + public string HttpAlias { get; set; } - + public int PortalAliasId { get; set; } - + public string SkinSrc { get; set; } - - public int TabId { get; set; } - + + public int TabId { get; set; } + public int KeyID { get { return this.TabAliasSkinId; } diff --git a/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs b/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs index f8220845720..9ced008de23 100644 --- a/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabChangeSettings.cs @@ -12,14 +12,14 @@ namespace DotNetNuke.Entities.Tabs using DotNetNuke.Framework; public class TabChangeSettings : ServiceLocator, ITabChangeSettings - { + { public bool IsChangeControlEnabled(int portalId, int tabId) { if (portalId == Null.NullInteger) { return false; } - + var isVersioningEnabled = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId); var isWorkflowEnable = TabWorkflowSettings.Instance.IsWorkflowEnabled(portalId, tabId); return isVersioningEnabled || isWorkflowEnable; @@ -34,11 +34,11 @@ public ChangeControlState GetChangeControlState(int portalId, int tabId) IsVersioningEnabledForTab = TabVersionSettings.Instance.IsVersioningEnabled(portalId, tabId), IsWorkflowEnabledForTab = TabWorkflowSettings.Instance.IsWorkflowEnabled(portalId, tabId), }; - } - + } + protected override Func GetFactory() { return () => new TabChangeSettings(); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs b/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs index fd51404dd1c..a073f0546de 100644 --- a/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabChangeTracker.cs @@ -21,7 +21,7 @@ public void TrackModuleAddition(ModuleInfo module, int moduleVersion, int userId { TabVersionTracker.Instance.TrackModuleAddition(module, moduleVersion, userId); } - + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(module.PortalID, module.TabID) && unPublishedVersion == null) { TabWorkflowTracker.Instance.TrackModuleAddition(module, moduleVersion, userId); @@ -32,7 +32,7 @@ public void TrackModuleModification(ModuleInfo module, int moduleVersion, int us { if (ModuleController.Instance.IsSharedModule(module) && moduleVersion != Null.NullInteger) { - throw new InvalidOperationException(Localization.GetExceptionMessage( + throw new InvalidOperationException(Localization.GetExceptionMessage( "ModuleDoesNotBelongToPage", "This module does not belong to the page. Please, move to its master page to change the module")); } @@ -56,7 +56,7 @@ public void TrackModuleDeletion(ModuleInfo module, int moduleVersion, int userId { TabVersionTracker.Instance.TrackModuleDeletion(module, moduleVersion, userId); } - + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(module.PortalID, module.TabID) && unPublishedVersion == null) { TabWorkflowTracker.Instance.TrackModuleDeletion(module, moduleVersion, userId); diff --git a/DNN Platform/Library/Entities/Tabs/TabCollection.cs b/DNN Platform/Library/Entities/Tabs/TabCollection.cs index d5009f5ee78..5e74cfa8c5b 100644 --- a/DNN Platform/Library/Entities/Tabs/TabCollection.cs +++ b/DNN Platform/Library/Entities/Tabs/TabCollection.cs @@ -32,8 +32,8 @@ public class TabCollection : Dictionary // This is used to provide a culture based set of tabs [NonSerialized] - private readonly Dictionary> _localizedTabs; - + private readonly Dictionary> _localizedTabs; + public TabCollection() { this._list = new List(); @@ -50,11 +50,11 @@ public TabCollection(SerializationInfo info, StreamingContext context) this._localizedTabs = new Dictionary>(); } - public TabCollection(IEnumerable tabs) + public TabCollection(IEnumerable tabs) : this() { this.AddRange(tabs); - } + } public override void OnDeserialization(object sender) { @@ -66,7 +66,7 @@ public override void OnDeserialization(object sender) this.AddInternal(tab); } } - + public void Add(TabInfo tab) { // Call base class to add to base Dictionary @@ -84,131 +84,6 @@ public void AddRange(IEnumerable tabs) } } - 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) - { - if (tab.ParentId == Null.NullInteger) - { - // Add tab to Children collection - this.AddToChildren(tab); - - // Add to end of List as all zero-level tabs are returned in order first - this._list.Add(tab); - } - else - { - // Find Parent in list - for (int index = 0; index <= this._list.Count - 1; index++) - { - TabInfo parentTab = this._list[index]; - if (parentTab.TabID == tab.ParentId) - { - int childCount = this.AddToChildren(tab); - - // Insert tab in master List - this._list.Insert(index + childCount, tab); - } - } - } - - // Add to localized tabs - if (tab.PortalID == Null.NullInteger || IsLocalizationEnabled(tab.PortalID)) - { - this.AddToLocalizedTabs(tab); - } - } - - private int AddToChildren(TabInfo tab) - { - List childList; - if (!this._children.TryGetValue(tab.ParentId, out childList)) - { - childList = new List(); - this._children.Add(tab.ParentId, childList); - } - - // Add tab to end of child list as children are returned in order - childList.Add(tab); - return childList.Count; - } - - private void AddToLocalizedTabCollection(TabInfo tab, string cultureCode) - { - List localizedTabCollection; - - var key = cultureCode.ToLowerInvariant(); - if (!this._localizedTabs.TryGetValue(key, out localizedTabCollection)) - { - localizedTabCollection = new List(); - this._localizedTabs.Add(key, localizedTabCollection); - } - - // Add tab to end of localized tabs - localizedTabCollection.Add(tab); - } - - private void AddToLocalizedTabs(TabInfo tab) - { - if (string.IsNullOrEmpty(tab.CultureCode)) - { - // Add to all cultures - foreach (var locale in LocaleController.Instance.GetLocales(tab.PortalID).Values) - { - this.AddToLocalizedTabCollection(tab, locale.Code); - } - } - else - { - this.AddToLocalizedTabCollection(tab, tab.CultureCode); - } - } - - private List GetDescendants(int tabId, int tabLevel) - { - var descendantTabs = new List(); - for (int index = 0; index <= this._list.Count - 1; index++) - { - TabInfo parentTab = this._list[index]; - if (parentTab.TabID == tabId) - { - // Found Parent - so add descendents - for (int descendantIndex = index + 1; descendantIndex <= this._list.Count - 1; descendantIndex++) - { - TabInfo descendantTab = this._list[descendantIndex]; - - if (tabLevel == Null.NullInteger) - { - tabLevel = parentTab.Level; - } - - if (descendantTab.Level > tabLevel) - { - // Descendant so add to collection - descendantTabs.Add(descendantTab); - } - else - { - break; - } - } - - break; - } - } - - return descendantTabs; - } - public List AsList() { return this._list; @@ -238,7 +113,7 @@ public TabCollection WithCulture(string cultureCode, bool includeNeutral) { return this.WithCulture(cultureCode, includeNeutral, IsLocalizationEnabled()); } - + public TabCollection WithCulture(string cultureCode, bool includeNeutral, bool localizationEnabled) { TabCollection collection; @@ -272,7 +147,7 @@ where t.CultureCode.ToLowerInvariant() == cultureCode // Return all tabs collection = this; } - + return collection; } @@ -283,7 +158,7 @@ public List WithParentId(int parentId) { tabs = new List(); } - + return tabs; } @@ -294,7 +169,7 @@ public TabInfo WithTabId(int tabId) { t = this[tabId]; } - + return t; } @@ -341,6 +216,131 @@ internal void RefreshCache(int tabId, TabInfo updatedTab) }); } } - } + } + + 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) + { + if (tab.ParentId == Null.NullInteger) + { + // Add tab to Children collection + this.AddToChildren(tab); + + // Add to end of List as all zero-level tabs are returned in order first + this._list.Add(tab); + } + else + { + // Find Parent in list + for (int index = 0; index <= this._list.Count - 1; index++) + { + TabInfo parentTab = this._list[index]; + if (parentTab.TabID == tab.ParentId) + { + int childCount = this.AddToChildren(tab); + + // Insert tab in master List + this._list.Insert(index + childCount, tab); + } + } + } + + // Add to localized tabs + if (tab.PortalID == Null.NullInteger || IsLocalizationEnabled(tab.PortalID)) + { + this.AddToLocalizedTabs(tab); + } + } + + private int AddToChildren(TabInfo tab) + { + List childList; + if (!this._children.TryGetValue(tab.ParentId, out childList)) + { + childList = new List(); + this._children.Add(tab.ParentId, childList); + } + + // Add tab to end of child list as children are returned in order + childList.Add(tab); + return childList.Count; + } + + private void AddToLocalizedTabCollection(TabInfo tab, string cultureCode) + { + List localizedTabCollection; + + var key = cultureCode.ToLowerInvariant(); + if (!this._localizedTabs.TryGetValue(key, out localizedTabCollection)) + { + localizedTabCollection = new List(); + this._localizedTabs.Add(key, localizedTabCollection); + } + + // Add tab to end of localized tabs + localizedTabCollection.Add(tab); + } + + private void AddToLocalizedTabs(TabInfo tab) + { + if (string.IsNullOrEmpty(tab.CultureCode)) + { + // Add to all cultures + foreach (var locale in LocaleController.Instance.GetLocales(tab.PortalID).Values) + { + this.AddToLocalizedTabCollection(tab, locale.Code); + } + } + else + { + this.AddToLocalizedTabCollection(tab, tab.CultureCode); + } + } + + private List GetDescendants(int tabId, int tabLevel) + { + var descendantTabs = new List(); + for (int index = 0; index <= this._list.Count - 1; index++) + { + TabInfo parentTab = this._list[index]; + if (parentTab.TabID == tabId) + { + // Found Parent - so add descendents + for (int descendantIndex = index + 1; descendantIndex <= this._list.Count - 1; descendantIndex++) + { + TabInfo descendantTab = this._list[descendantIndex]; + + if (tabLevel == Null.NullInteger) + { + tabLevel = parentTab.Level; + } + + if (descendantTab.Level > tabLevel) + { + // Descendant so add to collection + descendantTabs.Add(descendantTab); + } + else + { + break; + } + } + + break; + } + } + + return descendantTabs; + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabController.cs b/DNN Platform/Library/Entities/Tabs/TabController.cs index 0bd83530206..ed916811049 100644 --- a/DNN Platform/Library/Entities/Tabs/TabController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabController.cs @@ -52,11 +52,6 @@ public partial class TabController : ServiceLocator GetFactory() - { - return () => new TabController(); - } - /// /// Gets the current page in current http request. /// @@ -155,870 +150,940 @@ public static void CopyDesignToChildren(TabInfo parentTab, string skinSrc, strin } /// - /// Adds localized copies of the page in all missing languages. + /// Copies the permissions to children. /// - /// - /// - public void AddMissingLanguages(int portalId, int tabId) + /// The parent tab. + /// The new permissions. + public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCollection newPermissions) { - var currentTab = this.GetTab(tabId, portalId, false); - if (currentTab.CultureCode != null) + bool clearCache = Null.NullBoolean; + List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); + foreach (TabInfo tab in childTabs) { - var defaultLocale = LocaleController.Instance.GetDefaultLocale(portalId); - var workingTab = currentTab; - if (workingTab.CultureCode != defaultLocale.Code && workingTab.DefaultLanguageTab == null) + if (TabPermissionController.CanAdminPage(tab)) { - // 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); + tab.TabPermissions.Clear(); + tab.TabPermissions.AddRange(newPermissions); + TabPermissionController.SaveTabPermissions(tab); + UpdateTabVersion(tab.TabID); + clearCache = true; } + } - if (currentTab.DefaultLanguageTab != null) + if (clearCache) + { + DataCache.ClearTabsCache(childTabs[0].PortalID); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Processes all panes and modules in the template file. + /// + /// Template file node for the panes is current tab. + /// PortalId of the new portal. + /// Tab being processed. + /// Tabs need to merge. + /// Modules Hashtable. + /// + /// + public static void DeserializePanes(XmlNode nodePanes, int portalId, int tabId, + PortalTemplateModuleAction mergeTabs, Hashtable hModules) + { + Dictionary dicModules = ModuleController.Instance.GetTabModules(tabId); + + // If Mode is Replace remove all the modules already on this Tab + if (mergeTabs == PortalTemplateModuleAction.Replace) + { + foreach (KeyValuePair kvp in dicModules) { - workingTab = currentTab.DefaultLanguageTab; + var module = kvp.Value; + + // when the modules show on all pages are included by the same import process, it need removed. + if (!module.AllTabs || hModules.ContainsValue(module.ModuleID)) + { + ModuleController.Instance.DeleteTabModule(tabId, kvp.Value.ModuleID, false); + } } + } - foreach (Locale locale in LocaleController.Instance.GetLocales(portalId).Values) + // iterate through the panes + foreach (XmlNode nodePane in nodePanes.ChildNodes) + { + // iterate through the modules + if (nodePane.SelectSingleNode("modules") != null) { - if (!LocaleController.Instance.IsDefaultLanguage(locale.Code)) + XmlNode selectSingleNode = nodePane.SelectSingleNode("modules"); + if (selectSingleNode != null) { - bool missing = true; - foreach (var localizedTab in workingTab.LocalizedTabs.Values.Where(localizedTab => localizedTab.CultureCode == locale.Code)) - { - missing = false; - } - - if (missing) + foreach (XmlNode nodeModule in selectSingleNode) { - this.CreateLocalizedCopyInternal(workingTab, locale, false, true, insertAfterOriginal: true); + ModuleController.DeserializeModule(nodeModule, nodePane, portalId, tabId, mergeTabs, + hModules); } } } } + + // if deserialize tab from install wizard, we need parse desiralize handlers first. + var installFromWizard = HttpContext.Current != null && HttpContext.Current.Items.Contains("InstallFromWizard"); + if (installFromWizard) + { + HttpContext.Current.Items.Remove("InstallFromWizard"); + EventManager.Instance.RefreshTabSyncHandlers(); + } + + EventManager.Instance.OnTabDeserialize(new TabSyncEventArgs { Tab = Instance.GetTab(tabId, portalId), TabNode = nodePanes.ParentNode }); } /// - /// Adds a tab. + /// Deserializes the tab. /// - /// The tab to be added. - /// The tab is added to the end of the current Level. + /// The node tab. + /// The obj tab. + /// The portal id. + /// The merge tabs. /// - public int AddTab(TabInfo tab) - { - return this.AddTab(tab, true); - } - - internal Dictionary> GetTabUrls(int portalId) + public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, int portalId, + PortalTemplateModuleAction mergeTabs) { - string cacheKey = string.Format(DataCache.TabUrlCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabUrlCacheTimeOut, - DataCache.TabUrlCachePriority, - portalId), - this.GetTabUrlsCallback); + return DeserializeTab(tabNode, tab, new Hashtable(), portalId, false, mergeTabs, new Hashtable()); } - private static void AddAllTabsModules(TabInfo tab) + /// + /// Deserializes the tab. + /// + /// The node tab. + /// The obj tab. + /// The h tabs. + /// The portal id. + /// if set to true [is admin template]. + /// The merge tabs. + /// The h modules. + /// + public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tabs, int portalId, + bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, + Hashtable modules) { - var portalSettings = new PortalSettings(tab.TabID, tab.PortalID); - foreach (ModuleInfo allTabsModule in ModuleController.Instance.GetAllTabsModules(tab.PortalID, true)) + string tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "name"); + if (!string.IsNullOrEmpty(tabName)) { - // [DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages - // that are all "deleted" then even if the Module itself is not deleted, we would not expect the - // Module to be added - var canAdd = - (from ModuleInfo allTabsInstance in ModuleController.Instance.GetTabModulesByModule(allTabsModule.ModuleID) select Instance.GetTab(allTabsInstance.TabID, tab.PortalID, false)).Any( - t => !t.IsDeleted) && (!portalSettings.ContentLocalizationEnabled || allTabsModule.CultureCode == tab.CultureCode); - if (canAdd) + if (tab == null) { - ModuleController.Instance.CopyModule(allTabsModule, tab, Null.NullString, true); + tab = new TabInfo { TabID = Null.NullInteger, ParentId = Null.NullInteger, TabName = tabName }; } - } - } - 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; - } - } + tab.PortalID = portalId; + if (string.IsNullOrEmpty(tab.Title)) + { + tab.Title = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "title"); + } - 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++) + if (string.IsNullOrEmpty(tab.Description)) { - var permission = (PermissionInfo)arrPermissions[i]; - permissionID = permission.PermissionID; + tab.Description = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "description"); } - int roleID = int.MinValue; - switch (roleName) + tab.KeyWords = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "keywords"); + tab.IsVisible = XmlUtils.GetNodeValueBoolean(tabNode, "visible", true); + tab.DisableLink = XmlUtils.GetNodeValueBoolean(tabNode, "disabled"); + tab.IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfile")); + tab.IconFileLarge = Globals.ImportFile( + portalId, + XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); + tab.Url = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "url"); + tab.StartDate = XmlUtils.GetNodeValueDate(tabNode, "startdate", Null.NullDate); + tab.EndDate = XmlUtils.GetNodeValueDate(tabNode, "enddate", Null.NullDate); + tab.RefreshInterval = XmlUtils.GetNodeValueInt(tabNode, "refreshinterval", Null.NullInteger); + tab.PageHeadText = XmlUtils.GetNodeValue(tabNode, "pageheadtext", Null.NullString); + tab.IsSecure = XmlUtils.GetNodeValueBoolean(tabNode, "issecure", false); + tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", 0.5F); + tab.CultureCode = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "cultureCode"); + + // objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); + // objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); + tab.UseBaseFriendlyUrls = XmlUtils.GetNodeValueBoolean(tabNode, "UseBaseFriendlyUrls", false); + + tab.TabPermissions.Clear(); + DeserializeTabPermissions(tabNode.SelectNodes("tabpermissions/permission"), tab, isAdminTemplate); + + DeserializeTabSettings(tabNode.SelectNodes("tabsettings/tabsetting"), tab); + + // set tab skin and container + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty))) { - 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; - } - } + tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty); + } - break; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty))) + { + tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty); } - if (roleID != int.MinValue) + tabName = tab.TabName; + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) { - var tabPermission = new TabPermissionInfo + if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")] != null) { - 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) + // parent node specifies the path (tab1/tab2/tab3), use saved tabid + tab.ParentId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")]); + tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent") + "/" + tab.TabName; + } + else { - tab.TabPermissions.Add(tabPermission); + // Parent node doesn't spcecify the path, search by name. + // Possible incoherence if tabname not unique + TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"), portalId); + if (objParent != null) + { + tab.ParentId = objParent.TabID; + tabName = objParent.TabName + "/" + tab.TabName; + } + else + { + // parent tab not found! + tab.ParentId = Null.NullInteger; + tabName = tab.TabName; + } } } - } - } - - 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); - - // First create ContentItem as we need the ContentItemID - this.CreateContentItem(tab); - - // Add Tab - if (afterTabId > 0) - { - tab.TabID = this._dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); - } - else - { - tab.TabID = beforeTabId > 0 - ? this._dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) - : this._dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); - } - - // Clear the Cache - this.ClearCache(tab.PortalID); - - ITermController termController = Util.GetTermController(); - termController.RemoveTermsFromContent(tab); - foreach (Term term in tab.Terms) - { - termController.AddTermToContent(term, tab); - } - - EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, EventLogController.EventLogType.TAB_CREATED); - - // Add Tab Permissions - TabPermissionController.SaveTabPermissions(tab); - - // Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist - try - { - this.UpdateTabSettings(ref tab); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - // Add AllTabs Modules - if (includeAllTabsModules && tab.PortalID != Null.NullInteger) - { - AddAllTabsModules(tab); - } - - // Check Tab Versioning - if (tab.PortalID == Null.NullInteger || !TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID, tab.TabID)) - { - this.MarkAsPublished(tab); - } - - EventManager.Instance.OnTabCreated(new TabEventArgs { Tab = tab }); - - return tab.TabID; - } - - private void CreateLocalizedCopyInternal(TabInfo originalTab, Locale locale, bool allTabsModulesFromDefault, bool clearCache, bool insertAfterOriginal = false) - { - try - { - Logger.TraceFormat("Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); - var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); - - // First Clone the Tab - TabInfo localizedCopy = originalTab.Clone(); - localizedCopy.TabID = Null.NullInteger; - localizedCopy.StateID = Null.NullInteger; - localizedCopy.ContentItemId = Null.NullInteger; - - // Set Guids and Culture Code - localizedCopy.UniqueId = Guid.NewGuid(); - localizedCopy.VersionGuid = Guid.NewGuid(); - localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); - localizedCopy.CultureCode = locale.Code; - localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; - - // copy page tags - foreach (var term in originalTab.Terms) - { - localizedCopy.Terms.Add(term); - } - if (locale == defaultLocale) - { - originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; - this.UpdateTab(originalTab); - } - else + if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) { - localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; + if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")] != null) + { + // parent node specifies the path (tab1/tab2/tab3), use saved tabid + int defaultLanguageTabId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")]); + TabInfo defaultLanguageTab = Instance.GetTab(defaultLanguageTabId, portalId, false); + if (defaultLanguageTab != null) + { + tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; + } + } + else + { + // Parent node doesn't spcecify the path, search by name. + // Possible incoherence if tabname not unique + TabInfo defaultLanguageTab = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"), portalId); + if (defaultLanguageTab != null) + { + tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; + } + } } - // Copy Permissions from original Tab for Admins only - // If original tab is user tab or its parent tab is user tab, then copy full permission - // from original tab. - PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); - if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) + // create/update tab + if (tab.TabID == Null.NullInteger) { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); + tab.TabID = TabController.Instance.AddTab(tab); } else { - localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); - } - - // Get the original Tabs Parent - // check the original whether have parent. - if (!Null.IsNull(originalTab.ParentId)) - { - TabInfo originalParent = this.GetTab(originalTab.ParentId, originalTab.PortalID, false); - - // Get the localized parent - TabInfo localizedParent = this.GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); - localizedCopy.ParentId = localizedParent.TabID; - } - - // Save Tab - var afterTabId = insertAfterOriginal ? originalTab.TabID : -1; - const int beforeTabId = -1; - const bool includeAllModules = false; - this.AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); // not include modules show on all page, it will handled in copy modules action. - - // if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. - if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) - { - this.UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); + Instance.UpdateTab(tab); } - /* Tab versioning and workflow is disabled - * during the creation of the Localized copy - */ - DisableTabVersioningAndWorkflow(localizedCopy); - - // Make shallow copies of all modules - ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); - - // Convert these shallow copies to deep copies - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) + // UpdateTabUrls + foreach (XmlNode oTabUrlNode in tabNode.SelectNodes("tabUrls/tabUrl")) { - ModuleController.Instance.LocalizeModule(kvp.Value, locale); + var tabUrl = new TabUrlInfo(); + DeserializeTabUrls(oTabUrlNode, tabUrl); + DataProvider.Instance().SaveTabUrl(tab.TabID, tabUrl.SeqNum, tabUrl.PortalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); } - // if not copy modules which show on all pages from default language, we need add all modules in current culture. - if (!allTabsModulesFromDefault) + // extra check for duplicate tabs in same level + if (tabs[tabName] == null) { - AddAllTabsModules(localizedCopy); + tabs.Add(tabName, tab.TabID); } - - // Add Translator Role - this.GiveTranslatorRoleEditRights(localizedCopy, null); - - /* Tab versioning and workflow is re-enabled - * when the Localized copy is created - */ - EnableTabVersioningAndWorkflow(localizedCopy); - this.MarkAsPublished(localizedCopy); - } - catch (Exception ex) - { - Exceptions.LogException(ex); - throw; } - // Clear the Cache - if (clearCache) + // Parse Panes + if (tabNode.SelectSingleNode("panes") != null) { - this.ClearCache(originalTab.PortalID); + DeserializePanes(tabNode.SelectSingleNode("panes"), portalId, tab.TabID, mergeTabs, modules); } - } - private void ClearTabSettingsCache(int tabId) - { - var portalId = GetPortalId(tabId, -1); - string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); - DataCache.RemoveCache(cacheKey); + // Finally add "tabid" to node + tabNode.AppendChild(XmlUtils.CreateElement(tabNode.OwnerDocument, "tabid", tab.TabID.ToString())); + return tab; + } - // aslo clear the settings from tab object in cache. - var tab = this.GetTab(tabId, portalId, false); - if (tab != null) - { - tab.ClearSettingsCache(); - } - } - - private void CreateTabRedirect(TabInfo tab) + /// + /// Gets the portal tabs. + /// + /// The portal id. + /// The exclude tab id. + /// if set to true [include none specified]. + /// if set to true [include hidden]. + /// + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, + bool includeHidden) { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - - if (settings != null && tab.TabID != settings.HomeTabId && tab.TabUrls.Count(u => u.HttpStatus == "200") == 0) - { - var domainRoot = TestableGlobals.Instance.AddHTTP(settings.PortalAlias.HTTPAlias); - - if (!string.IsNullOrEmpty(domainRoot)) - { - var url = TestableGlobals.Instance.NavigateURL(tab.TabID); - - url = url.Replace(domainRoot, string.Empty); - - var seqNum = (tab.TabUrls.Count > 0) ? tab.TabUrls.Max(t => t.SeqNum) + 1 : 1; - var tabUrl = new TabUrlInfo - { - TabId = tab.TabID, - SeqNum = seqNum, - PortalAliasId = -1, - PortalAliasUsage = PortalAliasUsageType.Default, - Url = url, - QueryString = string.Empty, - CultureCode = tab.CultureCode, - HttpStatus = "301", - IsSystem = true, - }; - - this.SaveTabUrl(tabUrl, tab.PortalID, false); - } - } + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + false, + false, + false, + false, + true); } - private void CreateTabRedirects(TabInfo tab) + /// + /// Gets the portal tabs. + /// + /// The portal id. + /// The exclude tab id. + /// if set to true [include none specified]. + /// if set to true [include hidden]. + /// if set to true [include deleted]. + /// if set to true [include URL]. + /// + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, + bool includeHidden, bool includeDeleted, bool includeURL) { - this.CreateTabRedirect(tab); - - var descendants = this.GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); - - // Create Redirect for descendant tabs - foreach (TabInfo descendantTab in descendants) - { - this.CreateTabRedirect(descendantTab); - } + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + "<" + Localization.GetString("None_Specified") + ">", + includeHidden, + includeDeleted, + includeURL, + false, + false, + true); } - private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) + /// + /// Gets the portal tabs. + /// + /// The portal id. + /// The exclude tab id. + /// if set to true [include none specified]. + /// The none specified text. + /// if set to true [include hidden]. + /// if set to true [include deleted]. + /// if set to true [include URL]. + /// if set to true [check view permisison]. + /// if set to true [check edit permission]. + /// + public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, + string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, + bool checkViewPermisison, bool checkEditPermission) { - objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); - objTabUrl.Url = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url"); - objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); - objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); - objTabUrl.HttpStatus = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); - objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); - objTabUrl.PortalAliasId = Null.NullInteger; - objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; + return GetPortalTabs( + GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), + excludeTabId, + includeNoneSpecified, + noneSpecifiedText, + includeHidden, + includeDeleted, + includeURL, + checkViewPermisison, + checkEditPermission, + true); } - private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) + /// + /// Gets the portal tabs. + /// + /// The tabs. + /// The exclude tab id. + /// if set to true [include none specified]. + /// The none specified text. + /// if set to true [include hidden]. + /// if set to true [include deleted]. + /// if set to true [include URL]. + /// if set to true [check view permisison]. + /// if set to true [check edit permission]. + /// + public static List GetPortalTabs(List tabs, int excludeTabId, bool includeNoneSpecified, + string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, + bool checkViewPermisison, bool checkEditPermission) { - return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); + return GetPortalTabs( + tabs, + excludeTabId, + includeNoneSpecified, + noneSpecifiedText, + includeHidden, + includeDeleted, + includeURL, + checkViewPermisison, + checkEditPermission, + true); } - private static int GetPortalId(int tabId, int portalId) + /// + /// Gets the portal tabs. + /// + /// The tabs. + /// The exclude tab id. + /// if set to true [include none specified]. + /// The none specified text. + /// if set to true [include hidden]. + /// if set to true [include deleted]. + /// if set to true [include URL]. + /// if set to true [check view permisison]. + /// if set to true [check edit permission]. + /// The value of this parameter affects property. + /// + public static List GetPortalTabs( + List tabs, + int excludeTabId, + bool includeNoneSpecified, + string noneSpecifiedText, + bool includeHidden, + bool includeDeleted, + bool includeURL, + bool checkViewPermisison, + bool checkEditPermission, + bool includeDeletedChildren) { - if (Null.IsNull(portalId)) + var listTabs = new List(); + if (includeNoneSpecified) { - Dictionary portalDic = PortalController.GetPortalDictionary(); - if (portalDic != null && portalDic.ContainsKey(tabId)) - { - portalId = portalDic[tabId]; - } + var tab = new TabInfo { TabID = -1, TabName = noneSpecifiedText, TabOrder = 0, ParentId = -2 }; + listTabs.Add(tab); } - return portalId; - } - - private Dictionary> GetAliasSkins(int portalId) - { - string cacheKey = string.Format(DataCache.TabAliasSkinCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabAliasSkinCacheTimeOut, - DataCache.TabAliasSkinCachePriority, - portalId), - this.GetAliasSkinsCallback); - } - - private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) - { - var portalID = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); - if (portalID > -1) + foreach (TabInfo tab in tabs) { - IDataReader dr = DataProvider.Instance().GetTabAliasSkins(portalID); - try + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + if (((excludeTabId < 0) || (tab.TabID != excludeTabId)) && + (!tab.IsSuperTab || objUserInfo.IsSuperUser)) { - while (dr.Read()) + if ((tab.IsVisible || includeHidden) && tab.HasAVisibleVersion && (tab.IsDeleted == false || includeDeleted) && + (tab.TabType == TabType.Normal || includeURL)) { - // fill business object - var tabAliasSkin = CBO.FillObject(dr, false); - - // add Tab Alias Skin to dictionary - if (dic.ContainsKey(tabAliasSkin.TabId)) + // Check if User has View/Edit Permission for this tab + if (checkEditPermission || checkViewPermisison) { - // Add Tab Alias Skin to Tab Alias Skin Collection already in dictionary for TabId - dic[tabAliasSkin.TabId].Add(tabAliasSkin); + const string permissionList = "ADD,COPY,EDIT,MANAGE"; + if (checkEditPermission && + TabPermissionController.HasTabPermission(tab.TabPermissions, permissionList)) + { + listTabs.Add(tab); + } + else if (checkViewPermisison && TabPermissionController.CanViewPage(tab)) + { + listTabs.Add(tab); + } } else { - // Create new Tab Alias Skin Collection for TabId - var collection = new List { tabAliasSkin }; - - // Add Collection to Dictionary - dic.Add(tabAliasSkin.TabId, collection); + // Add Tab to List + listTabs.Add(tab); } } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); + + // HasChildren should be true in case there is at least one not deleted child + tab.HasChildren = tab.HasChildren && (includeDeletedChildren || GetTabsByParent(tab.TabID, tab.PortalID).Any(a => !a.IsDeleted)); } } - return dic; - } - - private Dictionary> GetCustomAliases(int portalId) - { - string cacheKey = string.Format(DataCache.TabCustomAliasCacheKey, portalId); - return CBO.GetCachedObject>>( - new CacheItemArgs( - cacheKey, - DataCache.TabCustomAliasCacheTimeOut, - DataCache.TabCustomAliasCachePriority, - portalId), - this.GetCustomAliasesCallback); + return listTabs; } - private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) + /// + /// Gets the tab by tab path. + /// + /// The portal id. + /// The tab path. + /// The culture code. + /// + public static int GetTabByTabPath(int portalId, string tabPath, string cultureCode) { - var portalID = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); - if (portalID > -1) + Dictionary tabpathDic = GetTabPathDictionary(portalId, cultureCode); + if (tabpathDic.ContainsKey(tabPath)) { - IDataReader dr = DataProvider.Instance().GetTabCustomAliases(portalID); - try - { - while (dr.Read()) - { - // fill business object - var tabId = (int)dr["TabId"]; - var customAlias = (string)dr["httpAlias"]; - var cultureCode = (string)dr["cultureCode"]; - - // add Custom Alias to dictionary - if (dic.ContainsKey(tabId)) - { - // Add Custom Alias to Custom Alias Collection already in dictionary for TabId - dic[tabId][cultureCode] = customAlias; - } - else - { - // Create new Custom Alias Collection for TabId - var collection = new Dictionary { { cultureCode, customAlias } }; - - // Add Collection to Dictionary - dic.Add(tabId, collection); - } - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } + return tabpathDic[tabPath]; } - return dic; + return -1; } - private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) + /// + /// Gets the tab path dictionary. + /// + /// The portal id. + /// The culture code. + /// + public static Dictionary GetTabPathDictionary(int portalId, string cultureCode) { - string cultureCode = Convert.ToString(cacheItemArgs.ParamList[0]); - var portalID = (int)cacheItemArgs.ParamList[1]; - var tabpathDic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); - IDataReader dr = DataProvider.Instance().GetTabPaths(portalID, cultureCode); - try - { - while (dr.Read()) - { - tabpathDic[Null.SetNullString(dr["TabPath"])] = Null.SetNullInteger(dr["TabID"]); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - CBO.CloseDataReader(dr, true); - } + string cacheKey = string.Format(DataCache.TabPathCacheKey, cultureCode, portalId); + return + CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, DataCache.TabPathCacheTimeOut, DataCache.TabPathCachePriority, + cultureCode, portalId), + GetTabPathDictionaryCallback); + } - return tabpathDic; + /// + /// Gets the tabs by parent. + /// + /// The parent id. + /// The portal id. + /// + public static List GetTabsByParent(int parentId, int portalId) + { + return Instance.GetTabsByPortal(portalId).WithParentId(parentId); } - private static void UpdateTabVersion(int tabId) + /// + /// Gets the tabs by sort order. + /// + /// The portal id. + /// The culture code. + /// if set to true [include neutral]. + /// + public static List GetTabsBySortOrder(int portalId, string cultureCode, bool includeNeutral) { - DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); + return Instance.GetTabsByPortal(portalId).WithCulture(cultureCode, includeNeutral).AsList(); } - private static void ValidateTabPath(TabInfo tab) + /// + /// Get all TabInfo for the current culture in SortOrder. + /// + /// The portalid to load tabs for. + /// + /// List of TabInfo oredered by default SortOrder. + /// + /// + /// This method uses the Active culture. There is an overload + /// which allows the culture information to be specified. + /// + public static List GetTabsBySortOrder(int portalId) { - string tabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - int tabId = GetTabByTabPath(tab.PortalID, tabPath, tab.CultureCode); - if (tabId > Null.NullInteger) + return GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true); + } + + /// + /// Determines whether is special tab. + /// + /// The tab id. + /// The portal id. + /// + public static bool IsSpecialTab(int tabId, int portalId) + { + Dictionary locales = LocaleController.Instance.GetLocales(portalId); + bool isSpecial = false; + foreach (Locale locale in locales.Values) { - // 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)); + PortalInfo portal = PortalController.Instance.GetPortal(portalId, locale.Code); + var portalSettings = new PortalSettings(portal); + isSpecial = IsSpecialTab(tabId, portalSettings); + + if (isSpecial) + { + break; + } } + + return isSpecial; } - private IEnumerable GetSiblingTabs(TabInfo objTab) + /// + /// Determines whether is special tab. + /// + /// The tab id. + /// The portal settings. + /// + /// true if is special tab; otherwise, false. + /// + public static bool IsSpecialTab(int tabId, PortalSettings portalSettings) { - return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); + return tabId == portalSettings.SplashTabId || tabId == portalSettings.HomeTabId || + tabId == portalSettings.LoginTabId || tabId == portalSettings.UserTabId || + tabId == portalSettings.AdminTabId || tabId == portalSettings.SuperTabId; } - private Dictionary GetTabSettingsByPortal(int portalId) + /// + /// SerializeTab. + /// + /// The Xml Document to use for the Tab. + /// The TabInfo object to serialize. + /// A flag used to determine if the Module content is included. + /// + public static XmlNode SerializeTab(XmlDocument tabXml, TabInfo objTab, bool includeContent) { - string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); - return CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - DataCache.TabCacheTimeOut, - DataCache.TabCachePriority), - c => - { - var tabSettings = new Dictionary(); - using (var dr = this._dataProvider.GetTabSettings(portalId)) - { - while (dr.Read()) - { - int tabId = dr.GetInt32(0); - Hashtable settings; - if (!tabSettings.TryGetValue(tabId, out settings)) - { - settings = new Hashtable(); - tabSettings[tabId] = settings; - } - - if (!dr.IsDBNull(2)) - { - settings[dr.GetString(1)] = dr.GetString(2); - } - else - { - settings[dr.GetString(1)] = string.Empty; - } - } - } - - return tabSettings; - }); + return SerializeTab(tabXml, null, objTab, null, includeContent); } - private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) + /// + /// SerializeTab. + /// + /// The Xml Document to use for the Tab. + /// A Hashtable used to store the names of the tabs. + /// The TabInfo object to serialize. + /// The Portal object to which the tab belongs. + /// A flag used to determine if the Module content is included. + /// + public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo tab, PortalInfo portal, + bool includeContent) { - var portalID = (int)cacheItemArgs.ParamList[0]; - var dic = new Dictionary>(); + XmlNode newnode; + CBO.SerializeObject(tab, tabXml); - if (portalID > -1) + XmlNode tabNode = tabXml.SelectSingleNode("tab"); + if (tabNode != null) { - IDataReader dr = DataProvider.Instance().GetTabUrls(portalID); - try + if (tabNode.Attributes != null) { - while (dr.Read()) - { - // fill business object - var tabRedirect = CBO.FillObject(dr, false); + tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsd"]); + tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsi"]); + } - // add Tab Redirect to dictionary - if (dic.ContainsKey(tabRedirect.TabId)) - { - // Add Tab Redirect to Tab Redirect Collection already in dictionary for TabId - dic[tabRedirect.TabId].Add(tabRedirect); - } - else - { - // Create new Tab Redirect Collection for TabId - var collection = new List { tabRedirect }; + // remove unwanted elements + // ReSharper disable AssignNullToNotNullAttribute + tabNode.RemoveChild(tabNode.SelectSingleNode("tabid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("moduleID")); + tabNode.RemoveChild(tabNode.SelectSingleNode("taborder")); + tabNode.RemoveChild(tabNode.SelectSingleNode("portalid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("parentid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("isdeleted")); + tabNode.RemoveChild(tabNode.SelectSingleNode("tabpath")); + tabNode.RemoveChild(tabNode.SelectSingleNode("haschildren")); + tabNode.RemoveChild(tabNode.SelectSingleNode("skindoctype")); + tabNode.RemoveChild(tabNode.SelectSingleNode("uniqueid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("versionguid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("defaultLanguageGuid")); + tabNode.RemoveChild(tabNode.SelectSingleNode("localizedVersionGuid")); + XmlNodeList xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); + if (xmlNodeList != null && xmlNodeList.Count == 0) + { + // for some reason serialization of permissions did not work + // we are using a different method here to make sure that + // permissions are included in the tabinfo xml + XmlDocument tabPermissions = new XmlDocument { XmlResolver = null }; + CBO.SerializeObject(tab.TabPermissions, tabPermissions); - // Add Collection to Dictionary - dic.Add(tabRedirect.TabId, collection); + XmlNode permissionsNode = tabXml.CreateElement("tabpermissions"); + var tabPermissionsNodeList = tabPermissions.SelectNodes("tabpermissions/TabPermissionInfo"); + if (tabPermissionsNodeList != null) + { + foreach (XmlNode nodePermission in tabPermissionsNodeList) + { + var newNode = tabXml.CreateElement("permission"); + newNode.InnerXml = nodePermission.InnerXml; + permissionsNode.AppendChild(newNode); } } + + tabNode.AppendChild(permissionsNode); + + // re-select the permissions node + xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally + + if (xmlNodeList != null) { - // close datareader - CBO.CloseDataReader(dr, true); + foreach (XmlNode nodePermission in xmlNodeList) + { + nodePermission.RemoveChild(nodePermission.SelectSingleNode("tabpermissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("tabid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); + nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); + } } - } - - return dic; - } - private void HardDeleteTabInternal(int tabId, int portalId) - { - // Delete all tabModule Instances - foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabId).Values) - { - ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, false); + // ReSharper restore AssignNullToNotNullAttribute } - var tab = this.GetTab(tabId, portalId, false); - - // Delete Tab - this._dataProvider.DeleteTab(tabId); - - // Log deletion - EventLogController.Instance.AddLog( - "TabID", - tabId.ToString(), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.TAB_DELETED); - - // queue remove tab/page from search index - var document = new SearchDocumentToDelete + // Manage Url + XmlNode urlNode = tabXml.SelectSingleNode("tab/url"); + switch (tab.TabType) { - TabId = tabId, - }; + case TabType.Normal: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Normal")); + break; + case TabType.Tab: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Tab")); - DataProvider.Instance().AddSearchDeletedItems(document); + // Get the tab being linked to + TabInfo tempTab = TabController.Instance.GetTab(int.Parse(tab.Url), tab.PortalID, false); + if (tempTab != null) + { + urlNode.InnerXml = tempTab.TabPath; + } - // Remove the Content Item - if (tab != null && tab.ContentItemId > Null.NullInteger) - { - IContentController contentController = Util.GetContentController(); - contentController.DeleteContentItem(tab); + break; + case TabType.File: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "File")); + IFileInfo file = FileManager.Instance.GetFile(int.Parse(tab.Url.Substring(7))); + urlNode.InnerXml = file.RelativePath; + break; + case TabType.Url: + urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Url")); + break; } - EventManager.Instance.OnTabDeleted(new TabEventArgs { Tab = tab }); - } - - private bool SoftDeleteChildTabs(int intTabid, PortalSettings portalSettings) - { - bool bDeleted = true; - foreach (TabInfo objtab in GetTabsByParent(intTabid, portalSettings.PortalId)) + // serialize TabSettings + XmlUtils.SerializeHashtable(tab.TabSettings, tabXml, tabNode, "tabsetting", "settingname", "settingvalue"); + if (portal != null) { - bDeleted = this.SoftDeleteTabInternal(objtab, portalSettings); - if (!bDeleted) + if (tab.TabID == portal.SplashTabId) { - break; + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "splashtab"; + tabNode.AppendChild(newnode); } - } - - return bDeleted; - } - - private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSettings) - { - Dto.ChangeControlState changeControlStateForTab = null; - if (tabToDelete.PortalID > -1) - { - changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState( - tabToDelete.PortalID, - tabToDelete.TabID); - if (changeControlStateForTab.IsChangeControlEnabledForTab) + else if (tab.TabID == portal.HomeTabId) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, false); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, false); + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "hometab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.UserTabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "usertab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.LoginTabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "logintab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.SearchTabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "searchtab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.Custom404TabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "404tab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.Custom500TabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "500tab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.TermsTabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "termstab"; + tabNode.AppendChild(newnode); + } + else if (tab.TabID == portal.PrivacyTabId) + { + newnode = tabXml.CreateElement("tabtype"); + newnode.InnerXml = "privacytab"; + tabNode.AppendChild(newnode); } } - var deleted = false; - if (!IsSpecialTab(tabToDelete.TabID, portalSettings)) + if (tabs != null) { - if (this.SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) + // Manage Parent Tab + if (!Null.IsNull(tab.ParentId)) { - tabToDelete.IsDeleted = true; - this.UpdateTab(tabToDelete); - - foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabToDelete.TabID).Values) - { - ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, true); - } - - EventLogController.Instance.AddLog(tabToDelete, portalSettings, portalSettings.UserId, string.Empty, - EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN); - deleted = true; + newnode = tabXml.CreateElement("parent"); + newnode.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.ParentId].ToString()); + tabNode.AppendChild(newnode); - EventManager.Instance.OnTabRemoved(new TabEventArgs { Tab = tabToDelete }); + // save tab as: ParentTabName/CurrentTabName + tabs.Add(tab.TabID, tabs[tab.ParentId] + "/" + tab.TabName); + } + else + { + // save tab as: CurrentTabName + tabs.Add(tab.TabID, tab.TabName); } } - if (changeControlStateForTab != null && changeControlStateForTab.IsChangeControlEnabledForTab) + // Manage Content Localization + if (tab.DefaultLanguageTab != null) { - TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, changeControlStateForTab.IsVersioningEnabledForTab); - TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); + try + { + newnode = tabXml.CreateElement("defaultLanguageTab"); + newnode.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.DefaultLanguageTab.TabID].ToString()); + tabNode.AppendChild(newnode); + } + catch + { + // ignore + } } - return deleted; - } + XmlNode panesNode; + XmlNode paneNode; + XmlNode nameNode; + XmlNode modulesNode; + XmlNode moduleNode; + XmlDocument moduleXml; + ModuleInfo module; - private void UpdateTabSettingInternal(int tabId, string settingName, string settingValue, bool clearCache) - { - using (var dr = this._dataProvider.GetTabSetting(tabId, settingName)) + // Serialize modules + panesNode = tabNode.AppendChild(tabXml.CreateElement("panes")); + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) { - if (dr.Read()) + module = kvp.Value; + if (!module.IsDeleted) { - if (dr.GetString(0) != settingValue) + moduleXml = new XmlDocument { XmlResolver = null }; + moduleNode = ModuleController.SerializeModule(moduleXml, module, includeContent); + if (panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']") == null) { - this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.TAB_SETTING_UPDATED, - "TabId", tabId, settingName, settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); + // new pane found + paneNode = moduleXml.CreateElement("pane"); + nameNode = paneNode.AppendChild(moduleXml.CreateElement("name")); + nameNode.InnerText = module.PaneName; + paneNode.AppendChild(moduleXml.CreateElement("modules")); + panesNode.AppendChild(tabXml.ImportNode(paneNode, true)); } + + modulesNode = panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']/modules"); + modulesNode.AppendChild(tabXml.ImportNode(moduleNode, true)); } - else - { - this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.AddSettingLog( - EventLogController.EventLogType.TAB_SETTING_CREATED, - "TabId", tabId, settingName, settingValue, - UserController.Instance.GetCurrentUserInfo().UserID); - } + } - dr.Close(); + // Serialize TabUrls + var tabUrlsNode = tabNode.AppendChild(tabXml.CreateElement("tabUrls")); + foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) + { + var tabUrlXml = new XmlDocument { XmlResolver = null }; + XmlNode tabUrlNode = tabUrlXml.CreateElement("tabUrl"); + tabUrlNode.AddAttribute("SeqNum", tabUrl.SeqNum.ToString(CultureInfo.InvariantCulture)); + tabUrlNode.AddAttribute("Url", tabUrl.Url); + tabUrlNode.AddAttribute("QueryString", tabUrl.QueryString); + tabUrlNode.AddAttribute("HttpStatus", tabUrl.HttpStatus); + tabUrlNode.AddAttribute("CultureCode", tabUrl.CultureCode); + tabUrlNode.AddAttribute("IsSystem", tabUrl.IsSystem.ToString()); + tabUrlsNode.AppendChild(tabXml.ImportNode(tabUrlNode, true)); } - UpdateTabVersion(tabId); - if (clearCache) + EventManager.Instance.OnTabSerialize(new TabSyncEventArgs { Tab = tab, TabNode = tabNode }); + + return tabNode; + } + + /// + /// check whether have conflict between tab path and portal alias. + /// + /// portal id. + /// tab path. + /// + public static bool IsDuplicateWithPortalAlias(int portalId, string tabPath) + { + var aliasLookup = PortalAliasController.Instance.GetPortalAliases(); + + foreach (PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId)) { - this.ClearTabSettingsCache(tabId); + string checkAlias = string.Format("{0}{1}", alias.HTTPAlias, tabPath.Replace("//", "/")); + + foreach (PortalAliasInfo a in aliasLookup.Values) + { + if (a.HTTPAlias.Equals(checkAlias, StringComparison.InvariantCultureIgnoreCase)) + { + return true; + } + } } + + return false; } - private void UpdateTabSettings(ref TabInfo updatedTab) + public static bool IsValidTabName(string tabName, out string invalidType) { - foreach (string sKeyLoopVariable in updatedTab.TabSettings.Keys) + invalidType = string.Empty; + + if (string.IsNullOrEmpty(tabName.Trim())) { - string sKey = sKeyLoopVariable; - this.UpdateTabSettingInternal(updatedTab.TabID, sKey, Convert.ToString(updatedTab.TabSettings[sKey]), false); + invalidType = "EmptyTabName"; + return false; + } + + var cleanTabName = HtmlUtils.StripNonWord(tabName, false); + if (TabNameCheck1.IsMatch(tabName) || TabNameCheck2.IsMatch(cleanTabName)) + { + invalidType = "InvalidTabName"; + return false; + } + + if (Config.GetFriendlyUrlProvider() == "advanced" && PortalSettings.Current != null) + { + var doNotRewriteRegex = new FriendlyUrlSettings(PortalSettings.Current.PortalId).DoNotRewriteRegex; + if (!string.IsNullOrEmpty(doNotRewriteRegex) && + (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) + || Regex.IsMatch("/" + cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) + || Regex.IsMatch("/" + cleanTabName + "/", doNotRewriteRegex, RegexOptions.IgnoreCase))) + { + invalidType = "InvalidTabName"; + return false; + } } + + return true; } /// - /// update content item for the tab when tab name changed. + /// Adds localized copies of the page in all missing languages. /// - /// The updated tab. - private void UpdateContentItem(TabInfo tab) + /// + /// + public void AddMissingLanguages(int portalId, int tabId) { - IContentController contentController = Util.GetContentController(); - var newContent = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; - if (tab.Content != newContent) + var currentTab = this.GetTab(tabId, portalId, false); + if (currentTab.CultureCode != null) { - tab.Content = newContent; - contentController.UpdateContentItem(tab); + 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. /// @@ -1214,32 +1279,6 @@ 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. /// @@ -2216,894 +2255,855 @@ public void MarkAsPublished(TabInfo tab) } /// - /// Copies the permissions to children. + /// Determines whether is host or admin tab. /// - /// The parent tab. - /// The new permissions. - public static void CopyPermissionsToChildren(TabInfo parentTab, TabPermissionCollection newPermissions) + /// The tab info. + /// + public bool IsHostOrAdminPage(TabInfo tab) { - bool clearCache = Null.NullBoolean; - List childTabs = Instance.GetTabsByPortal(parentTab.PortalID).DescendentsOf(parentTab.TabID); - foreach (TabInfo tab in childTabs) + return this.IsHostTab(tab) || this.IsAdminTab(tab); + } + + internal Dictionary> GetTabUrls(int portalId) + { + string cacheKey = string.Format(DataCache.TabUrlCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabUrlCacheTimeOut, + DataCache.TabUrlCachePriority, + portalId), + this.GetTabUrlsCallback); + } + + protected override Func GetFactory() + { + return () => new TabController(); + } + + private static void AddAllTabsModules(TabInfo tab) + { + var portalSettings = new PortalSettings(tab.TabID, tab.PortalID); + foreach (ModuleInfo allTabsModule in ModuleController.Instance.GetAllTabsModules(tab.PortalID, true)) { - if (TabPermissionController.CanAdminPage(tab)) + // [DNN-6276]We need to check that the Module is not implicitly deleted. ie If all instances are on Pages + // that are all "deleted" then even if the Module itself is not deleted, we would not expect the + // Module to be added + var canAdd = + (from ModuleInfo allTabsInstance in ModuleController.Instance.GetTabModulesByModule(allTabsModule.ModuleID) select Instance.GetTab(allTabsInstance.TabID, tab.PortalID, false)).Any( + t => !t.IsDeleted) && (!portalSettings.ContentLocalizationEnabled || allTabsModule.CultureCode == tab.CultureCode); + if (canAdd) { - tab.TabPermissions.Clear(); - tab.TabPermissions.AddRange(newPermissions); - TabPermissionController.SaveTabPermissions(tab); - UpdateTabVersion(tab.TabID); - clearCache = true; + ModuleController.Instance.CopyModule(allTabsModule, tab, Null.NullString, true); } } + } - if (clearCache) + private static void DeserializeTabSettings(XmlNodeList nodeTabSettings, TabInfo objTab) + { + foreach (XmlNode oTabSettingNode in nodeTabSettings) { - DataCache.ClearTabsCache(childTabs[0].PortalID); + string sKey = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingname"); + string sValue = XmlUtils.GetNodeValue(oTabSettingNode.CreateNavigator(), "settingvalue"); + objTab.TabSettings[sKey] = sValue; } } - /// ----------------------------------------------------------------------------- - /// - /// Processes all panes and modules in the template file. - /// - /// Template file node for the panes is current tab. - /// PortalId of the new portal. - /// Tab being processed. - /// Tabs need to merge. - /// Modules Hashtable. - /// - /// - public static void DeserializePanes(XmlNode nodePanes, int portalId, int tabId, - PortalTemplateModuleAction mergeTabs, Hashtable hModules) + private static void DeserializeTabPermissions(XmlNodeList nodeTabPermissions, TabInfo tab, bool isAdminTemplate) { - Dictionary dicModules = ModuleController.Instance.GetTabModules(tabId); - - // If Mode is Replace remove all the modules already on this Tab - if (mergeTabs == PortalTemplateModuleAction.Replace) + var permissionController = new PermissionController(); + int permissionID = 0; + foreach (XmlNode tabPermissionNode in nodeTabPermissions) { - foreach (KeyValuePair kvp in dicModules) + 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 module = kvp.Value; - - // when the modules show on all pages are included by the same import process, it need removed. - if (!module.AllTabs || hModules.ContainsValue(module.ModuleID)) - { - ModuleController.Instance.DeleteTabModule(tabId, kvp.Value.ModuleID, false); - } + var permission = (PermissionInfo)arrPermissions[i]; + permissionID = permission.PermissionID; } - } - // iterate through the panes - foreach (XmlNode nodePane in nodePanes.ChildNodes) - { - // iterate through the modules - if (nodePane.SelectSingleNode("modules") != null) + int roleID = int.MinValue; + switch (roleName) { - XmlNode selectSingleNode = nodePane.SelectSingleNode("modules"); - if (selectSingleNode != null) - { - foreach (XmlNode nodeModule in selectSingleNode) + 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) { - ModuleController.DeserializeModule(nodeModule, nodePane, portalId, tabId, mergeTabs, - hModules); + roleID = role.RoleID; } - } + else + { + if (isAdminTemplate && roleName.ToLowerInvariant() == "administrators") + { + roleID = portal.AdministratorRoleId; + } + } + + break; } - } - // if deserialize tab from install wizard, we need parse desiralize handlers first. - var installFromWizard = HttpContext.Current != null && HttpContext.Current.Items.Contains("InstallFromWizard"); - if (installFromWizard) - { - HttpContext.Current.Items.Remove("InstallFromWizard"); - EventManager.Instance.RefreshTabSyncHandlers(); + 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); + } + } } + } - EventManager.Instance.OnTabDeserialize(new TabSyncEventArgs { Tab = Instance.GetTab(tabId, portalId), TabNode = nodePanes.ParentNode }); + private static void DeserializeTabUrls(XmlNode nodeTabUrl, TabUrlInfo objTabUrl) + { + objTabUrl.SeqNum = XmlUtils.GetAttributeValueAsInteger(nodeTabUrl.CreateNavigator(), "SeqNum", 0); + objTabUrl.Url = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url")) ? "/" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "Url"); + objTabUrl.QueryString = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "QueryString"); + objTabUrl.CultureCode = XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "CultureCode"); + objTabUrl.HttpStatus = string.IsNullOrEmpty(XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus")) ? "200" : XmlUtils.GetAttributeValue(nodeTabUrl.CreateNavigator(), "HttpStatus"); + objTabUrl.IsSystem = XmlUtils.GetAttributeValueAsBoolean(nodeTabUrl.CreateNavigator(), "IsSystem", true); + objTabUrl.PortalAliasId = Null.NullInteger; + objTabUrl.PortalAliasUsage = PortalAliasUsageType.Default; } - /// - /// Deserializes the tab. - /// - /// The node tab. - /// The obj tab. - /// The portal id. - /// The merge tabs. - /// - public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, int portalId, - PortalTemplateModuleAction mergeTabs) + private static int GetIndexOfTab(TabInfo objTab, IEnumerable tabs) { - return DeserializeTab(tabNode, tab, new Hashtable(), portalId, false, mergeTabs, new Hashtable()); + return Null.NullInteger + tabs.TakeWhile(tab => tab.TabID != objTab.TabID).Count(); } - /// - /// Deserializes the tab. - /// - /// The node tab. - /// The obj tab. - /// The h tabs. - /// The portal id. - /// if set to true [is admin template]. - /// The merge tabs. - /// The h modules. - /// - public static TabInfo DeserializeTab(XmlNode tabNode, TabInfo tab, Hashtable tabs, int portalId, - bool isAdminTemplate, PortalTemplateModuleAction mergeTabs, - Hashtable modules) + private static int GetPortalId(int tabId, int portalId) { - string tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "name"); - if (!string.IsNullOrEmpty(tabName)) + if (Null.IsNull(portalId)) { - if (tab == null) + Dictionary portalDic = PortalController.GetPortalDictionary(); + if (portalDic != null && portalDic.ContainsKey(tabId)) { - tab = new TabInfo { TabID = Null.NullInteger, ParentId = Null.NullInteger, TabName = tabName }; + portalId = portalDic[tabId]; } + } - tab.PortalID = portalId; - if (string.IsNullOrEmpty(tab.Title)) - { - tab.Title = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "title"); - } + return portalId; + } - if (string.IsNullOrEmpty(tab.Description)) + private static object GetTabPathDictionaryCallback(CacheItemArgs cacheItemArgs) + { + string cultureCode = Convert.ToString(cacheItemArgs.ParamList[0]); + var portalID = (int)cacheItemArgs.ParamList[1]; + var tabpathDic = new Dictionary(StringComparer.CurrentCultureIgnoreCase); + IDataReader dr = DataProvider.Instance().GetTabPaths(portalID, cultureCode); + try + { + while (dr.Read()) { - tab.Description = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "description"); + tabpathDic[Null.SetNullString(dr["TabPath"])] = Null.SetNullInteger(dr["TabID"]); } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + CBO.CloseDataReader(dr, true); + } - tab.KeyWords = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "keywords"); - tab.IsVisible = XmlUtils.GetNodeValueBoolean(tabNode, "visible", true); - tab.DisableLink = XmlUtils.GetNodeValueBoolean(tabNode, "disabled"); - tab.IconFile = Globals.ImportFile(portalId, XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfile")); - tab.IconFileLarge = Globals.ImportFile( - portalId, - XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "iconfilelarge")); - tab.Url = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "url"); - tab.StartDate = XmlUtils.GetNodeValueDate(tabNode, "startdate", Null.NullDate); - tab.EndDate = XmlUtils.GetNodeValueDate(tabNode, "enddate", Null.NullDate); - tab.RefreshInterval = XmlUtils.GetNodeValueInt(tabNode, "refreshinterval", Null.NullInteger); - tab.PageHeadText = XmlUtils.GetNodeValue(tabNode, "pageheadtext", Null.NullString); - tab.IsSecure = XmlUtils.GetNodeValueBoolean(tabNode, "issecure", false); - tab.SiteMapPriority = XmlUtils.GetNodeValueSingle(tabNode, "sitemappriority", 0.5F); - tab.CultureCode = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "cultureCode"); + return tabpathDic; + } - // objTab.UniqueId = New Guid(XmlUtils.GetNodeValue(nodeTab, "guid", Guid.NewGuid.ToString())); - // objTab.VersionGuid = New Guid(XmlUtils.GetNodeValue(nodeTab, "versionGuid", Guid.NewGuid.ToString())); - tab.UseBaseFriendlyUrls = XmlUtils.GetNodeValueBoolean(tabNode, "UseBaseFriendlyUrls", false); + private static void UpdateTabVersion(int tabId) + { + DataProvider.Instance().UpdateTabVersion(tabId, Guid.NewGuid()); + } - tab.TabPermissions.Clear(); - DeserializeTabPermissions(tabNode.SelectNodes("tabpermissions/permission"), tab, isAdminTemplate); + 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)); + } + } - DeserializeTabSettings(tabNode.SelectNodes("tabsettings/tabsetting"), tab); + private static void EnableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, true); + } - // set tab skin and container - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty))) - { - tab.SkinSrc = XmlUtils.GetNodeValue(tabNode, "skinsrc", string.Empty); - } + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, true); + } + } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty))) - { - tab.ContainerSrc = XmlUtils.GetNodeValue(tabNode, "containersrc", string.Empty); - } + private static void DisableTabVersioningAndWorkflow(TabInfo tab) + { + if (TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID)) + { + TabVersionSettings.Instance.SetEnabledVersioningForTab(tab.TabID, false); + } - tabName = tab.TabName; - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"))) - { - if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")] != null) - { - // parent node specifies the path (tab1/tab2/tab3), use saved tabid - tab.ParentId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent")]); - tabName = XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent") + "/" + tab.TabName; - } - else - { - // Parent node doesn't spcecify the path, search by name. - // Possible incoherence if tabname not unique - TabInfo objParent = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "parent"), portalId); - if (objParent != null) - { - tab.ParentId = objParent.TabID; - tabName = objParent.TabName + "/" + tab.TabName; - } - else - { - // parent tab not found! - tab.ParentId = Null.NullInteger; - tabName = tab.TabName; - } - } + if (TabWorkflowSettings.Instance.IsWorkflowEnabled(tab.PortalID)) + { + TabWorkflowSettings.Instance.SetWorkflowEnabled(tab.PortalID, tab.TabID, false); + } + } + + 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); + + // First create ContentItem as we need the ContentItemID + this.CreateContentItem(tab); + + // Add Tab + if (afterTabId > 0) + { + tab.TabID = this._dataProvider.AddTabAfter(tab, afterTabId, UserController.Instance.GetCurrentUserInfo().UserID); + } + else + { + tab.TabID = beforeTabId > 0 + ? this._dataProvider.AddTabBefore(tab, beforeTabId, UserController.Instance.GetCurrentUserInfo().UserID) + : this._dataProvider.AddTabToEnd(tab, UserController.Instance.GetCurrentUserInfo().UserID); + } + + // Clear the Cache + this.ClearCache(tab.PortalID); + + ITermController termController = Util.GetTermController(); + termController.RemoveTermsFromContent(tab); + foreach (Term term in tab.Terms) + { + termController.AddTermToContent(term, tab); + } + + EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, EventLogController.EventLogType.TAB_CREATED); + + // Add Tab Permissions + TabPermissionController.SaveTabPermissions(tab); + + // Add TabSettings - use Try/catch as tabs are added during upgrade ptocess and the sproc may not exist + try + { + this.UpdateTabSettings(ref tab); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + // Add AllTabs Modules + if (includeAllTabsModules && tab.PortalID != Null.NullInteger) + { + AddAllTabsModules(tab); + } + + // Check Tab Versioning + if (tab.PortalID == Null.NullInteger || !TabVersionSettings.Instance.IsVersioningEnabled(tab.PortalID, tab.TabID)) + { + this.MarkAsPublished(tab); + } + + EventManager.Instance.OnTabCreated(new TabEventArgs { Tab = tab }); + + return tab.TabID; + } + + private void CreateLocalizedCopyInternal(TabInfo originalTab, Locale locale, bool allTabsModulesFromDefault, bool clearCache, bool insertAfterOriginal = false) + { + try + { + Logger.TraceFormat("Localizing TabId: {0}, TabPath: {1}, Locale: {2}", originalTab.TabID, originalTab.TabPath, locale.Code); + var defaultLocale = LocaleController.Instance.GetDefaultLocale(originalTab.PortalID); + + // First Clone the Tab + TabInfo localizedCopy = originalTab.Clone(); + localizedCopy.TabID = Null.NullInteger; + localizedCopy.StateID = Null.NullInteger; + localizedCopy.ContentItemId = Null.NullInteger; + + // Set Guids and Culture Code + localizedCopy.UniqueId = Guid.NewGuid(); + localizedCopy.VersionGuid = Guid.NewGuid(); + localizedCopy.LocalizedVersionGuid = Guid.NewGuid(); + localizedCopy.CultureCode = locale.Code; + localizedCopy.TabName = localizedCopy.TabName + " (" + locale.Code + ")"; + + // copy page tags + foreach (var term in originalTab.Terms) + { + localizedCopy.Terms.Add(term); } - if (!string.IsNullOrEmpty(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"))) + if (locale == defaultLocale) { - if (tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")] != null) - { - // parent node specifies the path (tab1/tab2/tab3), use saved tabid - int defaultLanguageTabId = Convert.ToInt32(tabs[XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab")]); - TabInfo defaultLanguageTab = Instance.GetTab(defaultLanguageTabId, portalId, false); - if (defaultLanguageTab != null) - { - tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; - } - } - else - { - // Parent node doesn't spcecify the path, search by name. - // Possible incoherence if tabname not unique - TabInfo defaultLanguageTab = Instance.GetTabByName(XmlUtils.GetNodeValue(tabNode.CreateNavigator(), "defaultLanguageTab"), portalId); - if (defaultLanguageTab != null) - { - tab.DefaultLanguageGuid = defaultLanguageTab.UniqueId; - } - } + originalTab.DefaultLanguageGuid = localizedCopy.UniqueId; + this.UpdateTab(originalTab); + } + else + { + localizedCopy.DefaultLanguageGuid = originalTab.UniqueId; } - // create/update tab - if (tab.TabID == Null.NullInteger) + // Copy Permissions from original Tab for Admins only + // If original tab is user tab or its parent tab is user tab, then copy full permission + // from original tab. + PortalInfo portal = PortalController.Instance.GetPortal(originalTab.PortalID); + if (originalTab.TabID == portal.UserTabId || originalTab.ParentId == portal.UserTabId) { - tab.TabID = TabController.Instance.AddTab(tab); + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions); } else { - Instance.UpdateTab(tab); + localizedCopy.TabPermissions.AddRange(originalTab.TabPermissions.Where(p => p.RoleID == portal.AdministratorRoleId)); } - // UpdateTabUrls - foreach (XmlNode oTabUrlNode in tabNode.SelectNodes("tabUrls/tabUrl")) + // Get the original Tabs Parent + // check the original whether have parent. + if (!Null.IsNull(originalTab.ParentId)) { - var tabUrl = new TabUrlInfo(); - DeserializeTabUrls(oTabUrlNode, tabUrl); - DataProvider.Instance().SaveTabUrl(tab.TabID, tabUrl.SeqNum, tabUrl.PortalAliasId, (int)tabUrl.PortalAliasUsage, tabUrl.Url, tabUrl.QueryString, tabUrl.CultureCode, tabUrl.HttpStatus, tabUrl.IsSystem, UserController.Instance.GetCurrentUserInfo().UserID); + TabInfo originalParent = this.GetTab(originalTab.ParentId, originalTab.PortalID, false); + + // Get the localized parent + TabInfo localizedParent = this.GetTabByCulture(originalParent.TabID, originalParent.PortalID, locale); + localizedCopy.ParentId = localizedParent.TabID; } - // extra check for duplicate tabs in same level - if (tabs[tabName] == null) + // Save Tab + var afterTabId = insertAfterOriginal ? originalTab.TabID : -1; + const int beforeTabId = -1; + const bool includeAllModules = false; + this.AddTabInternal(localizedCopy, afterTabId, beforeTabId, includeAllModules); // not include modules show on all page, it will handled in copy modules action. + + // if the tab has custom stylesheet defined, then also copy the stylesheet to the localized version. + if (originalTab.TabSettings.ContainsKey("CustomStylesheet")) { - tabs.Add(tabName, tab.TabID); + this.UpdateTabSetting(localizedCopy.TabID, "CustomStylesheet", originalTab.TabSettings["CustomStylesheet"].ToString()); } - } - // Parse Panes - if (tabNode.SelectSingleNode("panes") != null) + /* Tab versioning and workflow is disabled + * during the creation of the Localized copy + */ + DisableTabVersioningAndWorkflow(localizedCopy); + + // Make shallow copies of all modules + ModuleController.Instance.CopyModules(originalTab, localizedCopy, true, allTabsModulesFromDefault); + + // Convert these shallow copies to deep copies + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(localizedCopy.TabID)) + { + ModuleController.Instance.LocalizeModule(kvp.Value, locale); + } + + // if not copy modules which show on all pages from default language, we need add all modules in current culture. + if (!allTabsModulesFromDefault) + { + AddAllTabsModules(localizedCopy); + } + + // Add Translator Role + this.GiveTranslatorRoleEditRights(localizedCopy, null); + + /* Tab versioning and workflow is re-enabled + * when the Localized copy is created + */ + EnableTabVersioningAndWorkflow(localizedCopy); + this.MarkAsPublished(localizedCopy); + } + catch (Exception ex) { - DeserializePanes(tabNode.SelectSingleNode("panes"), portalId, tab.TabID, mergeTabs, modules); + Exceptions.LogException(ex); + throw; } - // Finally add "tabid" to node - tabNode.AppendChild(XmlUtils.CreateElement(tabNode.OwnerDocument, "tabid", tab.TabID.ToString())); - return tab; + // Clear the Cache + if (clearCache) + { + this.ClearCache(originalTab.PortalID); + } } - /// - /// Gets the portal tabs. - /// - /// The portal id. - /// The exclude tab id. - /// if set to true [include none specified]. - /// if set to true [include hidden]. - /// - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, - bool includeHidden) + private void ClearTabSettingsCache(int tabId) { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - false, - false, - false, - false, - true); - } - - /// - /// Gets the portal tabs. - /// - /// The portal id. - /// The exclude tab id. - /// if set to true [include none specified]. - /// if set to true [include hidden]. - /// if set to true [include deleted]. - /// if set to true [include URL]. - /// - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, - bool includeHidden, bool includeDeleted, bool includeURL) - { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - "<" + Localization.GetString("None_Specified") + ">", - includeHidden, - includeDeleted, - includeURL, - false, - false, - true); - } - - /// - /// Gets the portal tabs. - /// - /// The portal id. - /// The exclude tab id. - /// if set to true [include none specified]. - /// The none specified text. - /// if set to true [include hidden]. - /// if set to true [include deleted]. - /// if set to true [include URL]. - /// if set to true [check view permisison]. - /// if set to true [check edit permission]. - /// - public static List GetPortalTabs(int portalId, int excludeTabId, bool includeNoneSpecified, - string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, - bool checkViewPermisison, bool checkEditPermission) - { - return GetPortalTabs( - GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true), - excludeTabId, - includeNoneSpecified, - noneSpecifiedText, - includeHidden, - includeDeleted, - includeURL, - checkViewPermisison, - checkEditPermission, - true); - } - - /// - /// Gets the portal tabs. - /// - /// The tabs. - /// The exclude tab id. - /// if set to true [include none specified]. - /// The none specified text. - /// if set to true [include hidden]. - /// if set to true [include deleted]. - /// if set to true [include URL]. - /// if set to true [check view permisison]. - /// if set to true [check edit permission]. - /// - public static List GetPortalTabs(List tabs, int excludeTabId, bool includeNoneSpecified, - string noneSpecifiedText, bool includeHidden, bool includeDeleted, bool includeURL, - bool checkViewPermisison, bool checkEditPermission) - { - return GetPortalTabs( - tabs, - excludeTabId, - includeNoneSpecified, - noneSpecifiedText, - includeHidden, - includeDeleted, - includeURL, - checkViewPermisison, - checkEditPermission, - true); - } - - /// - /// Gets the portal tabs. - /// - /// The tabs. - /// The exclude tab id. - /// if set to true [include none specified]. - /// The none specified text. - /// if set to true [include hidden]. - /// if set to true [include deleted]. - /// if set to true [include URL]. - /// if set to true [check view permisison]. - /// if set to true [check edit permission]. - /// The value of this parameter affects property. - /// - public static List GetPortalTabs( - List tabs, - int excludeTabId, - bool includeNoneSpecified, - string noneSpecifiedText, - bool includeHidden, - bool includeDeleted, - bool includeURL, - bool checkViewPermisison, - bool checkEditPermission, - bool includeDeletedChildren) - { - var listTabs = new List(); - if (includeNoneSpecified) - { - var tab = new TabInfo { TabID = -1, TabName = noneSpecifiedText, TabOrder = 0, ParentId = -2 }; - listTabs.Add(tab); - } - - foreach (TabInfo tab in tabs) - { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - if (((excludeTabId < 0) || (tab.TabID != excludeTabId)) && - (!tab.IsSuperTab || objUserInfo.IsSuperUser)) - { - if ((tab.IsVisible || includeHidden) && tab.HasAVisibleVersion && (tab.IsDeleted == false || includeDeleted) && - (tab.TabType == TabType.Normal || includeURL)) - { - // Check if User has View/Edit Permission for this tab - if (checkEditPermission || checkViewPermisison) - { - const string permissionList = "ADD,COPY,EDIT,MANAGE"; - if (checkEditPermission && - TabPermissionController.HasTabPermission(tab.TabPermissions, permissionList)) - { - listTabs.Add(tab); - } - else if (checkViewPermisison && TabPermissionController.CanViewPage(tab)) - { - listTabs.Add(tab); - } - } - else - { - // Add Tab to List - listTabs.Add(tab); - } - } - - // HasChildren should be true in case there is at least one not deleted child - tab.HasChildren = tab.HasChildren && (includeDeletedChildren || GetTabsByParent(tab.TabID, tab.PortalID).Any(a => !a.IsDeleted)); - } - } - - return listTabs; - } - - /// - /// Gets the tab by tab path. - /// - /// The portal id. - /// The tab path. - /// The culture code. - /// - public static int GetTabByTabPath(int portalId, string tabPath, string cultureCode) - { - Dictionary tabpathDic = GetTabPathDictionary(portalId, cultureCode); - if (tabpathDic.ContainsKey(tabPath)) - { - return tabpathDic[tabPath]; - } - - return -1; - } - - /// - /// Gets the tab path dictionary. - /// - /// The portal id. - /// The culture code. - /// - public static Dictionary GetTabPathDictionary(int portalId, string cultureCode) - { - string cacheKey = string.Format(DataCache.TabPathCacheKey, cultureCode, portalId); - return - CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, DataCache.TabPathCacheTimeOut, DataCache.TabPathCachePriority, - cultureCode, portalId), - GetTabPathDictionaryCallback); - } - - /// - /// Gets the tabs by parent. - /// - /// The parent id. - /// The portal id. - /// - public static List GetTabsByParent(int parentId, int portalId) - { - return Instance.GetTabsByPortal(portalId).WithParentId(parentId); - } - - /// - /// Gets the tabs by sort order. - /// - /// The portal id. - /// The culture code. - /// if set to true [include neutral]. - /// - public static List GetTabsBySortOrder(int portalId, string cultureCode, bool includeNeutral) - { - return Instance.GetTabsByPortal(portalId).WithCulture(cultureCode, includeNeutral).AsList(); - } - - /// - /// Get all TabInfo for the current culture in SortOrder. - /// - /// The portalid to load tabs for. - /// - /// List of TabInfo oredered by default SortOrder. - /// - /// - /// This method uses the Active culture. There is an overload - /// which allows the culture information to be specified. - /// - public static List GetTabsBySortOrder(int portalId) - { - return GetTabsBySortOrder(portalId, PortalController.GetActivePortalLanguage(portalId), true); - } + var portalId = GetPortalId(tabId, -1); + string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); + DataCache.RemoveCache(cacheKey); - /// - /// Determines whether is special tab. - /// - /// The tab id. - /// The portal id. - /// - public static bool IsSpecialTab(int tabId, int portalId) - { - Dictionary locales = LocaleController.Instance.GetLocales(portalId); - bool isSpecial = false; - foreach (Locale locale in locales.Values) + // aslo clear the settings from tab object in cache. + var tab = this.GetTab(tabId, portalId, false); + if (tab != null) { - PortalInfo portal = PortalController.Instance.GetPortal(portalId, locale.Code); - var portalSettings = new PortalSettings(portal); - isSpecial = IsSpecialTab(tabId, portalSettings); - - if (isSpecial) - { - break; - } + tab.ClearSettingsCache(); } - - return isSpecial; - } - - /// - /// Determines whether is special tab. - /// - /// The tab id. - /// The portal settings. - /// - /// true if is special tab; otherwise, false. - /// - public static bool IsSpecialTab(int tabId, PortalSettings portalSettings) - { - return tabId == portalSettings.SplashTabId || tabId == portalSettings.HomeTabId || - tabId == portalSettings.LoginTabId || tabId == portalSettings.UserTabId || - tabId == portalSettings.AdminTabId || tabId == portalSettings.SuperTabId; - } - - /// - /// SerializeTab. - /// - /// The Xml Document to use for the Tab. - /// The TabInfo object to serialize. - /// A flag used to determine if the Module content is included. - /// - public static XmlNode SerializeTab(XmlDocument tabXml, TabInfo objTab, bool includeContent) - { - 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. - /// - /// The Xml Document to use for the Tab. - /// A Hashtable used to store the names of the tabs. - /// The TabInfo object to serialize. - /// The Portal object to which the tab belongs. - /// A flag used to determine if the Module content is included. - /// - public static XmlNode SerializeTab(XmlDocument tabXml, Hashtable tabs, TabInfo tab, PortalInfo portal, - bool includeContent) + private void CreateTabRedirect(TabInfo tab) { - XmlNode newnode; - CBO.SerializeObject(tab, tabXml); - - XmlNode tabNode = tabXml.SelectSingleNode("tab"); - if (tabNode != null) - { - if (tabNode.Attributes != null) - { - tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsd"]); - tabNode.Attributes.Remove(tabNode.Attributes["xmlns:xsi"]); - } - - // remove unwanted elements - // ReSharper disable AssignNullToNotNullAttribute - tabNode.RemoveChild(tabNode.SelectSingleNode("tabid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("moduleID")); - tabNode.RemoveChild(tabNode.SelectSingleNode("taborder")); - tabNode.RemoveChild(tabNode.SelectSingleNode("portalid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("parentid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("isdeleted")); - tabNode.RemoveChild(tabNode.SelectSingleNode("tabpath")); - tabNode.RemoveChild(tabNode.SelectSingleNode("haschildren")); - tabNode.RemoveChild(tabNode.SelectSingleNode("skindoctype")); - tabNode.RemoveChild(tabNode.SelectSingleNode("uniqueid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("versionguid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("defaultLanguageGuid")); - tabNode.RemoveChild(tabNode.SelectSingleNode("localizedVersionGuid")); - XmlNodeList xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); - if (xmlNodeList != null && xmlNodeList.Count == 0) - { - // for some reason serialization of permissions did not work - // we are using a different method here to make sure that - // permissions are included in the tabinfo xml - XmlDocument tabPermissions = new XmlDocument { XmlResolver = null }; - CBO.SerializeObject(tab.TabPermissions, tabPermissions); - - XmlNode permissionsNode = tabXml.CreateElement("tabpermissions"); - var tabPermissionsNodeList = tabPermissions.SelectNodes("tabpermissions/TabPermissionInfo"); - if (tabPermissionsNodeList != null) - { - foreach (XmlNode nodePermission in tabPermissionsNodeList) - { - var newNode = tabXml.CreateElement("permission"); - newNode.InnerXml = nodePermission.InnerXml; - permissionsNode.AppendChild(newNode); - } - } - - tabNode.AppendChild(permissionsNode); + var settings = PortalController.Instance.GetCurrentPortalSettings(); - // re-select the permissions node - xmlNodeList = tabNode.SelectNodes("tabpermissions/permission"); - } + if (settings != null && tab.TabID != settings.HomeTabId && tab.TabUrls.Count(u => u.HttpStatus == "200") == 0) + { + var domainRoot = TestableGlobals.Instance.AddHTTP(settings.PortalAlias.HTTPAlias); - if (xmlNodeList != null) + if (!string.IsNullOrEmpty(domainRoot)) { - foreach (XmlNode nodePermission in xmlNodeList) + var url = TestableGlobals.Instance.NavigateURL(tab.TabID); + + url = url.Replace(domainRoot, string.Empty); + + var seqNum = (tab.TabUrls.Count > 0) ? tab.TabUrls.Max(t => t.SeqNum) + 1 : 1; + var tabUrl = new TabUrlInfo { - nodePermission.RemoveChild(nodePermission.SelectSingleNode("tabpermissionid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("permissionid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("tabid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("roleid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("userid")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("username")); - nodePermission.RemoveChild(nodePermission.SelectSingleNode("displayname")); - } - } + TabId = tab.TabID, + SeqNum = seqNum, + PortalAliasId = -1, + PortalAliasUsage = PortalAliasUsageType.Default, + Url = url, + QueryString = string.Empty, + CultureCode = tab.CultureCode, + HttpStatus = "301", + IsSystem = true, + }; - // ReSharper restore AssignNullToNotNullAttribute + this.SaveTabUrl(tabUrl, tab.PortalID, false); + } } + } - // Manage Url - XmlNode urlNode = tabXml.SelectSingleNode("tab/url"); - switch (tab.TabType) - { - case TabType.Normal: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Normal")); - break; - case TabType.Tab: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Tab")); + private void CreateTabRedirects(TabInfo tab) + { + this.CreateTabRedirect(tab); - // Get the tab being linked to - TabInfo tempTab = TabController.Instance.GetTab(int.Parse(tab.Url), tab.PortalID, false); - if (tempTab != null) - { - urlNode.InnerXml = tempTab.TabPath; - } + var descendants = this.GetTabsByPortal(tab.PortalID).DescendentsOf(tab.TabID); - break; - case TabType.File: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "File")); - IFileInfo file = FileManager.Instance.GetFile(int.Parse(tab.Url.Substring(7))); - urlNode.InnerXml = file.RelativePath; - break; - case TabType.Url: - urlNode.Attributes.Append(XmlUtils.CreateAttribute(tabXml, "type", "Url")); - break; + // Create Redirect for descendant tabs + foreach (TabInfo descendantTab in descendants) + { + this.CreateTabRedirect(descendantTab); } + } - // serialize TabSettings - XmlUtils.SerializeHashtable(tab.TabSettings, tabXml, tabNode, "tabsetting", "settingname", "settingvalue"); - if (portal != null) + private Dictionary> GetAliasSkins(int portalId) + { + string cacheKey = string.Format(DataCache.TabAliasSkinCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabAliasSkinCacheTimeOut, + DataCache.TabAliasSkinCachePriority, + portalId), + this.GetAliasSkinsCallback); + } + + private object GetAliasSkinsCallback(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + if (portalID > -1) { - if (tab.TabID == portal.SplashTabId) + IDataReader dr = DataProvider.Instance().GetTabAliasSkins(portalID); + try { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "splashtab"; - tabNode.AppendChild(newnode); + while (dr.Read()) + { + // fill business object + var tabAliasSkin = CBO.FillObject(dr, false); + + // add Tab Alias Skin to dictionary + if (dic.ContainsKey(tabAliasSkin.TabId)) + { + // Add Tab Alias Skin to Tab Alias Skin Collection already in dictionary for TabId + dic[tabAliasSkin.TabId].Add(tabAliasSkin); + } + else + { + // Create new Tab Alias Skin Collection for TabId + var collection = new List { tabAliasSkin }; + + // Add Collection to Dictionary + dic.Add(tabAliasSkin.TabId, collection); + } + } } - else if (tab.TabID == portal.HomeTabId) + catch (Exception exc) { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "hometab"; - tabNode.AppendChild(newnode); + Exceptions.LogException(exc); } - else if (tab.TabID == portal.UserTabId) + finally { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "usertab"; - tabNode.AppendChild(newnode); + // close datareader + CBO.CloseDataReader(dr, true); } - else if (tab.TabID == portal.LoginTabId) + } + + return dic; + } + + private Dictionary> GetCustomAliases(int portalId) + { + string cacheKey = string.Format(DataCache.TabCustomAliasCacheKey, portalId); + return CBO.GetCachedObject>>( + new CacheItemArgs( + cacheKey, + DataCache.TabCustomAliasCacheTimeOut, + DataCache.TabCustomAliasCachePriority, + portalId), + this.GetCustomAliasesCallback); + } + + private object GetCustomAliasesCallback(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + if (portalID > -1) + { + IDataReader dr = DataProvider.Instance().GetTabCustomAliases(portalID); + try { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "logintab"; - tabNode.AppendChild(newnode); + while (dr.Read()) + { + // fill business object + var tabId = (int)dr["TabId"]; + var customAlias = (string)dr["httpAlias"]; + var cultureCode = (string)dr["cultureCode"]; + + // add Custom Alias to dictionary + if (dic.ContainsKey(tabId)) + { + // Add Custom Alias to Custom Alias Collection already in dictionary for TabId + dic[tabId][cultureCode] = customAlias; + } + else + { + // Create new Custom Alias Collection for TabId + var collection = new Dictionary { { cultureCode, customAlias } }; + + // Add Collection to Dictionary + dic.Add(tabId, collection); + } + } } - else if (tab.TabID == portal.SearchTabId) + catch (Exception exc) { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "searchtab"; - tabNode.AppendChild(newnode); + Exceptions.LogException(exc); } - else if (tab.TabID == portal.Custom404TabId) + finally { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "404tab"; - tabNode.AppendChild(newnode); + // close datareader + CBO.CloseDataReader(dr, true); } - else if (tab.TabID == portal.Custom500TabId) + } + + return dic; + } + + private IEnumerable GetSiblingTabs(TabInfo objTab) + { + return this.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, true).WithParentId(objTab.ParentId); + } + + private Dictionary GetTabSettingsByPortal(int portalId) + { + string cacheKey = string.Format(DataCache.TabSettingsCacheKey, portalId); + return CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + DataCache.TabCacheTimeOut, + DataCache.TabCachePriority), + c => + { + var tabSettings = new Dictionary(); + using (var dr = this._dataProvider.GetTabSettings(portalId)) + { + while (dr.Read()) + { + int tabId = dr.GetInt32(0); + Hashtable settings; + if (!tabSettings.TryGetValue(tabId, out settings)) + { + settings = new Hashtable(); + tabSettings[tabId] = settings; + } + + if (!dr.IsDBNull(2)) + { + settings[dr.GetString(1)] = dr.GetString(2); + } + else + { + settings[dr.GetString(1)] = string.Empty; + } + } + } + + return tabSettings; + }); + } + + private object GetTabUrlsCallback(CacheItemArgs cacheItemArgs) + { + var portalID = (int)cacheItemArgs.ParamList[0]; + var dic = new Dictionary>(); + + if (portalID > -1) + { + IDataReader dr = DataProvider.Instance().GetTabUrls(portalID); + try { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "500tab"; - tabNode.AppendChild(newnode); + while (dr.Read()) + { + // fill business object + var tabRedirect = CBO.FillObject(dr, false); + + // add Tab Redirect to dictionary + if (dic.ContainsKey(tabRedirect.TabId)) + { + // Add Tab Redirect to Tab Redirect Collection already in dictionary for TabId + dic[tabRedirect.TabId].Add(tabRedirect); + } + else + { + // Create new Tab Redirect Collection for TabId + var collection = new List { tabRedirect }; + + // Add Collection to Dictionary + dic.Add(tabRedirect.TabId, collection); + } + } } - else if (tab.TabID == portal.TermsTabId) + catch (Exception exc) { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "termstab"; - tabNode.AppendChild(newnode); + Exceptions.LogException(exc); } - else if (tab.TabID == portal.PrivacyTabId) + finally { - newnode = tabXml.CreateElement("tabtype"); - newnode.InnerXml = "privacytab"; - tabNode.AppendChild(newnode); + // close datareader + CBO.CloseDataReader(dr, true); } } - if (tabs != null) + return dic; + } + + private void HardDeleteTabInternal(int tabId, int portalId) + { + // Delete all tabModule Instances + foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabId).Values) { - // Manage Parent Tab - if (!Null.IsNull(tab.ParentId)) - { - newnode = tabXml.CreateElement("parent"); - newnode.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.ParentId].ToString()); - tabNode.AppendChild(newnode); + ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, false); + } - // save tab as: ParentTabName/CurrentTabName - tabs.Add(tab.TabID, tabs[tab.ParentId] + "/" + tab.TabName); - } - else - { - // save tab as: CurrentTabName - tabs.Add(tab.TabID, tab.TabName); - } + var tab = this.GetTab(tabId, portalId, false); + + // Delete Tab + this._dataProvider.DeleteTab(tabId); + + // Log deletion + EventLogController.Instance.AddLog( + "TabID", + tabId.ToString(), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.TAB_DELETED); + + // queue remove tab/page from search index + var document = new SearchDocumentToDelete + { + TabId = tabId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + + // Remove the Content Item + if (tab != null && tab.ContentItemId > Null.NullInteger) + { + IContentController contentController = Util.GetContentController(); + contentController.DeleteContentItem(tab); } - // Manage Content Localization - if (tab.DefaultLanguageTab != null) + EventManager.Instance.OnTabDeleted(new TabEventArgs { Tab = tab }); + } + + private bool SoftDeleteChildTabs(int intTabid, PortalSettings portalSettings) + { + bool bDeleted = true; + foreach (TabInfo objtab in GetTabsByParent(intTabid, portalSettings.PortalId)) { - try + bDeleted = this.SoftDeleteTabInternal(objtab, portalSettings); + if (!bDeleted) { - newnode = tabXml.CreateElement("defaultLanguageTab"); - newnode.InnerXml = HttpContext.Current.Server.HtmlEncode(tabs[tab.DefaultLanguageTab.TabID].ToString()); - tabNode.AppendChild(newnode); + break; } - catch + } + + return bDeleted; + } + + private bool SoftDeleteTabInternal(TabInfo tabToDelete, PortalSettings portalSettings) + { + Dto.ChangeControlState changeControlStateForTab = null; + if (tabToDelete.PortalID > -1) + { + changeControlStateForTab = TabChangeSettings.Instance.GetChangeControlState( + tabToDelete.PortalID, + tabToDelete.TabID); + if (changeControlStateForTab.IsChangeControlEnabledForTab) { - // ignore + TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, false); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, false); } } - XmlNode panesNode; - XmlNode paneNode; - XmlNode nameNode; - XmlNode modulesNode; - XmlNode moduleNode; - XmlDocument moduleXml; - ModuleInfo module; - - // Serialize modules - panesNode = tabNode.AppendChild(tabXml.CreateElement("panes")); - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(tab.TabID)) + var deleted = false; + if (!IsSpecialTab(tabToDelete.TabID, portalSettings)) { - module = kvp.Value; - if (!module.IsDeleted) + if (this.SoftDeleteChildTabs(tabToDelete.TabID, portalSettings)) { - moduleXml = new XmlDocument { XmlResolver = null }; - moduleNode = ModuleController.SerializeModule(moduleXml, module, includeContent); - if (panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']") == null) + tabToDelete.IsDeleted = true; + this.UpdateTab(tabToDelete); + + foreach (ModuleInfo m in ModuleController.Instance.GetTabModules(tabToDelete.TabID).Values) { - // new pane found - paneNode = moduleXml.CreateElement("pane"); - nameNode = paneNode.AppendChild(moduleXml.CreateElement("name")); - nameNode.InnerText = module.PaneName; - paneNode.AppendChild(moduleXml.CreateElement("modules")); - panesNode.AppendChild(tabXml.ImportNode(paneNode, true)); + ModuleController.Instance.DeleteTabModule(m.TabID, m.ModuleID, true); } - modulesNode = panesNode.SelectSingleNode("descendant::pane[name='" + module.PaneName + "']/modules"); - modulesNode.AppendChild(tabXml.ImportNode(moduleNode, true)); + EventLogController.Instance.AddLog(tabToDelete, portalSettings, portalSettings.UserId, string.Empty, + EventLogController.EventLogType.TAB_SENT_TO_RECYCLE_BIN); + deleted = true; + + EventManager.Instance.OnTabRemoved(new TabEventArgs { Tab = tabToDelete }); } } - // Serialize TabUrls - var tabUrlsNode = tabNode.AppendChild(tabXml.CreateElement("tabUrls")); - foreach (var tabUrl in TabController.Instance.GetTabUrls(tab.TabID, tab.PortalID)) + if (changeControlStateForTab != null && changeControlStateForTab.IsChangeControlEnabledForTab) { - var tabUrlXml = new XmlDocument { XmlResolver = null }; - XmlNode tabUrlNode = tabUrlXml.CreateElement("tabUrl"); - tabUrlNode.AddAttribute("SeqNum", tabUrl.SeqNum.ToString(CultureInfo.InvariantCulture)); - tabUrlNode.AddAttribute("Url", tabUrl.Url); - tabUrlNode.AddAttribute("QueryString", tabUrl.QueryString); - tabUrlNode.AddAttribute("HttpStatus", tabUrl.HttpStatus); - tabUrlNode.AddAttribute("CultureCode", tabUrl.CultureCode); - tabUrlNode.AddAttribute("IsSystem", tabUrl.IsSystem.ToString()); - tabUrlsNode.AppendChild(tabXml.ImportNode(tabUrlNode, true)); + TabVersionSettings.Instance.SetEnabledVersioningForTab(tabToDelete.TabID, changeControlStateForTab.IsVersioningEnabledForTab); + TabWorkflowSettings.Instance.SetWorkflowEnabled(tabToDelete.PortalID, tabToDelete.TabID, changeControlStateForTab.IsWorkflowEnabledForTab); } - EventManager.Instance.OnTabSerialize(new TabSyncEventArgs { Tab = tab, TabNode = tabNode }); - - return tabNode; + return deleted; } - /// - /// check whether have conflict between tab path and portal alias. - /// - /// portal id. - /// tab path. - /// - public static bool IsDuplicateWithPortalAlias(int portalId, string tabPath) + private void UpdateTabSettingInternal(int tabId, string settingName, string settingValue, bool clearCache) { - var aliasLookup = PortalAliasController.Instance.GetPortalAliases(); - - foreach (PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId)) + using (var dr = this._dataProvider.GetTabSetting(tabId, settingName)) { - string checkAlias = string.Format("{0}{1}", alias.HTTPAlias, tabPath.Replace("//", "/")); - - foreach (PortalAliasInfo a in aliasLookup.Values) + if (dr.Read()) { - if (a.HTTPAlias.Equals(checkAlias, StringComparison.InvariantCultureIgnoreCase)) + if (dr.GetString(0) != settingValue) { - return true; + this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_UPDATED, + "TabId", tabId, settingName, settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); } } - } - - return false; - } + else + { + this._dataProvider.UpdateTabSetting(tabId, settingName, settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + EventLogController.AddSettingLog( + EventLogController.EventLogType.TAB_SETTING_CREATED, + "TabId", tabId, settingName, settingValue, + UserController.Instance.GetCurrentUserInfo().UserID); + } - public static bool IsValidTabName(string tabName, out string invalidType) - { - invalidType = string.Empty; + dr.Close(); + } - if (string.IsNullOrEmpty(tabName.Trim())) + UpdateTabVersion(tabId); + if (clearCache) { - invalidType = "EmptyTabName"; - return false; + this.ClearTabSettingsCache(tabId); } + } - var cleanTabName = HtmlUtils.StripNonWord(tabName, false); - if (TabNameCheck1.IsMatch(tabName) || TabNameCheck2.IsMatch(cleanTabName)) + private void UpdateTabSettings(ref TabInfo updatedTab) + { + foreach (string sKeyLoopVariable in updatedTab.TabSettings.Keys) { - invalidType = "InvalidTabName"; - return false; + string sKey = sKeyLoopVariable; + this.UpdateTabSettingInternal(updatedTab.TabID, sKey, Convert.ToString(updatedTab.TabSettings[sKey]), false); } + } - if (Config.GetFriendlyUrlProvider() == "advanced" && PortalSettings.Current != null) + /// + /// update content item for the tab when tab name changed. + /// + /// The updated tab. + private void UpdateContentItem(TabInfo tab) + { + IContentController contentController = Util.GetContentController(); + var newContent = string.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; + if (tab.Content != newContent) { - var doNotRewriteRegex = new FriendlyUrlSettings(PortalSettings.Current.PortalId).DoNotRewriteRegex; - if (!string.IsNullOrEmpty(doNotRewriteRegex) && - (Regex.IsMatch(cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) - || Regex.IsMatch("/" + cleanTabName, doNotRewriteRegex, RegexOptions.IgnoreCase) - || Regex.IsMatch("/" + cleanTabName + "/", doNotRewriteRegex, RegexOptions.IgnoreCase))) - { - invalidType = "InvalidTabName"; - return false; - } + tab.Content = newContent; + contentController.UpdateContentItem(tab); } - - return true; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabException.cs b/DNN Platform/Library/Entities/Tabs/TabException.cs index 43e3c569481..b457b331ac8 100644 --- a/DNN Platform/Library/Entities/Tabs/TabException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabException.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Tabs public class TabException : Exception { - public TabException(int tabId, string message) + public TabException(int tabId, string message) : base(message) { this.TabId = tabId; diff --git a/DNN Platform/Library/Entities/Tabs/TabExistsException.cs b/DNN Platform/Library/Entities/Tabs/TabExistsException.cs index 1f24cec22ab..a94db484998 100644 --- a/DNN Platform/Library/Entities/Tabs/TabExistsException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabExistsException.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Tabs public class TabExistsException : TabException { - public TabExistsException(int tabId, string message) + public TabExistsException(int tabId, string message) : base(tabId, message) { } diff --git a/DNN Platform/Library/Entities/Tabs/TabExtensions.cs b/DNN Platform/Library/Entities/Tabs/TabExtensions.cs index 50a7fc2fb1a..1a761e5757c 100644 --- a/DNN Platform/Library/Entities/Tabs/TabExtensions.cs +++ b/DNN Platform/Library/Entities/Tabs/TabExtensions.cs @@ -29,7 +29,7 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p if (redirect.SeqNum >= seqNum) { seqNum = redirect.SeqNum + 1; - + // 602 : when seqnum == 0, then duplicate key problems arise if (seqNum == 0) { @@ -43,7 +43,7 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p if (redirect.SeqNum <= seqNum) { seqNum = redirect.SeqNum - 1; - + // 602 : don't allow seqnum to become zero if (seqNum == 0) { @@ -52,7 +52,7 @@ public static int GetNextAvailableSeqNum(this List redirects, bool p } } } - + return seqNum; } @@ -80,7 +80,7 @@ public static TabUrlInfo CurrentUrl(this List redirects, string cult } } } - + // look at the results if (lastCustomUrl != null) { @@ -90,7 +90,7 @@ public static TabUrlInfo CurrentUrl(this List redirects, string cult { result = lastSystemUrl; } - + return result; } } diff --git a/DNN Platform/Library/Entities/Tabs/TabInfo.cs b/DNN Platform/Library/Entities/Tabs/TabInfo.cs index 47e49957304..ed87840c606 100644 --- a/DNN Platform/Library/Entities/Tabs/TabInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabInfo.cs @@ -39,6 +39,8 @@ 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 readonly SharedDictionary _localizedTabNameDictionary; + private readonly SharedDictionary _fullUrlDictionary; private string _administratorRoles; private string _authorizedRoles; @@ -49,8 +51,6 @@ public class TabInfo : ContentItem, IPropertyAccess private Hashtable _settings; private string _skinDoctype; private bool _superTabIdSet = Null.NullBoolean; - private readonly SharedDictionary _localizedTabNameDictionary; - private readonly SharedDictionary _fullUrlDictionary; private string _iconFile; private string _iconFileLarge; @@ -106,54 +106,6 @@ private TabInfo(SharedDictionary localizedTabNameDictionary, Sha this.IsSystem = false; } - [XmlIgnore] - public ArrayList BreadCrumbs { get; set; } - - [XmlIgnore] - public string ContainerPath { get; set; } - - [XmlElement("containersrc")] - public string ContainerSrc { get; set; } - - [XmlElement("cultureCode")] - public string CultureCode { get; set; } - - [XmlElement("defaultLanguageGuid")] - public Guid DefaultLanguageGuid { get; set; } - - [XmlElement("description")] - public string Description { get; set; } - - [XmlElement("disabled")] - public bool DisableLink { get; set; } - - [XmlElement("enddate")] - public DateTime EndDate { get; set; } - - [XmlElement("haschildren")] - public bool HasChildren { get; set; } - - [XmlIgnore] - public string IconFileRaw { get; private set; } - - [XmlIgnore] - public string IconFileLargeRaw { get; private set; } - - [XmlElement("isdeleted")] - public bool IsDeleted { get; set; } - - [XmlElement("issecure")] - public bool IsSecure { get; set; } - - [XmlElement("visible")] - public bool IsVisible { get; set; } - - [XmlElement("issystem")] - public bool IsSystem { get; set; } - - [XmlIgnore] - public bool HasBeenPublished { get; set; } - [XmlIgnore] public bool HasAVisibleVersion { @@ -163,77 +115,6 @@ public bool HasAVisibleVersion } } - [XmlElement("keywords")] - public string KeyWords { get; set; } - - [XmlIgnore] - public int Level { get; set; } - - [XmlElement("localizedVersionGuid")] - public Guid LocalizedVersionGuid { get; set; } - - [XmlIgnore] - public ArrayList Modules - { - get - { - return this._modules ?? (this._modules = TabModulesController.Instance.GetTabModules(this)); - } - - set - { - this._modules = value; - } - } - - [XmlElement("pageheadtext")] - public string PageHeadText { get; set; } - - [XmlIgnore] - public ArrayList Panes { get; private set; } - - [XmlElement("parentid")] - public int ParentId { get; set; } - - [XmlElement("permanentredirect")] - public bool PermanentRedirect { get; set; } - - [XmlElement("portalid")] - public int PortalID { get; set; } - - [XmlElement("refreshinterval")] - public int RefreshInterval { get; set; } - - [XmlElement("sitemappriority")] - public float SiteMapPriority { get; set; } - - [XmlIgnore] - public string SkinPath { get; set; } - - [XmlElement("skinsrc")] - public string SkinSrc { get; set; } - - [XmlElement("startdate")] - public DateTime StartDate { get; set; } - - [XmlElement("name")] - public string TabName { get; set; } - - [XmlElement("taborder")] - public int TabOrder { get; set; } - - [XmlElement("tabpath")] - public string TabPath { get; set; } - - [XmlElement("title")] - public string Title { get; set; } - - [XmlElement("uniqueid")] - public Guid UniqueId { get; set; } - - [XmlElement("versionguid")] - public Guid VersionGuid { get; set; } - [XmlIgnore] public Dictionary ChildModules { @@ -276,38 +157,6 @@ public bool DoNotRedirect } } - [XmlElement("iconfile")] - public string IconFile - { - get - { - this.IconFileGetter(ref this._iconFile, this.IconFileRaw); - return this._iconFile; - } - - set - { - this.IconFileRaw = value; - this._iconFile = null; - } - } - - [XmlElement("iconfilelarge")] - public string IconFileLarge - { - get - { - this.IconFileGetter(ref this._iconFileLarge, this.IconFileLargeRaw); - return this._iconFileLarge; - } - - set - { - this.IconFileLargeRaw = value; - this._iconFileLarge = null; - } - } - [XmlIgnore] public string IndentedTabName { @@ -342,26 +191,6 @@ public bool IsNeutralCulture } } - [XmlIgnore] - public bool IsSuperTab - { - get - { - if (this._superTabIdSet) - { - return this._isSuperTab; - } - - return this.PortalID == Null.NullInteger; - } - - set - { - this._isSuperTab = value; - this._superTabIdSet = true; - } - } - [XmlIgnore] public bool IsTranslated { @@ -378,20 +207,6 @@ public bool IsTranslated } } - [XmlIgnore] - public override int KeyID - { - get - { - return this.TabID; - } - - set - { - this.TabID = value; - } - } - [XmlIgnore] public string LocalizedTabName { @@ -447,29 +262,6 @@ public Dictionary LocalizedTabs } } - [XmlElement("skindoctype")] - public string SkinDoctype - { - get - { - if (string.IsNullOrEmpty(this.SkinSrc) == false && string.IsNullOrEmpty(this._skinDoctype)) - { - this._skinDoctype = this.CheckIfDoctypeConfigExists(); - if (string.IsNullOrEmpty(this._skinDoctype)) - { - this._skinDoctype = Host.Host.DefaultDocType; - } - } - - return this._skinDoctype; - } - - set - { - this._skinDoctype = value; - } - } - [XmlArray("tabpermissions")] [XmlArrayItem("permission")] public TabPermissionCollection TabPermissions @@ -583,20 +375,228 @@ public List TabUrls } } - [XmlElement("url")] - public string Url { get; set; } + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } [XmlIgnore] - public bool UseBaseFriendlyUrls { get; set; } + public ArrayList BreadCrumbs { get; set; } - public CacheLevel Cacheability + [XmlIgnore] + public string ContainerPath { get; set; } + + [XmlElement("containersrc")] + public string ContainerSrc { get; set; } + + [XmlElement("cultureCode")] + public string CultureCode { get; set; } + + [XmlElement("defaultLanguageGuid")] + public Guid DefaultLanguageGuid { get; set; } + + [XmlElement("description")] + public string Description { get; set; } + + [XmlElement("disabled")] + public bool DisableLink { get; set; } + + [XmlElement("enddate")] + public DateTime EndDate { get; set; } + + [XmlElement("haschildren")] + public bool HasChildren { get; set; } + + [XmlIgnore] + public string IconFileRaw { get; private set; } + + [XmlIgnore] + public string IconFileLargeRaw { get; private set; } + + [XmlElement("isdeleted")] + public bool IsDeleted { get; set; } + + [XmlElement("issecure")] + public bool IsSecure { get; set; } + + [XmlElement("visible")] + public bool IsVisible { get; set; } + + [XmlElement("issystem")] + public bool IsSystem { get; set; } + + [XmlIgnore] + public bool HasBeenPublished { get; set; } + + [XmlElement("keywords")] + public string KeyWords { get; set; } + + [XmlIgnore] + public int Level { get; set; } + + [XmlElement("localizedVersionGuid")] + public Guid LocalizedVersionGuid { get; set; } + + [XmlIgnore] + public ArrayList Modules { get { - return CacheLevel.fullyCacheable; + return this._modules ?? (this._modules = TabModulesController.Instance.GetTabModules(this)); + } + + set + { + this._modules = value; + } + } + + [XmlElement("pageheadtext")] + public string PageHeadText { get; set; } + + [XmlIgnore] + public ArrayList Panes { get; private set; } + + [XmlElement("parentid")] + public int ParentId { get; set; } + + [XmlElement("permanentredirect")] + public bool PermanentRedirect { get; set; } + + [XmlElement("portalid")] + public int PortalID { get; set; } + + [XmlElement("refreshinterval")] + public int RefreshInterval { get; set; } + + [XmlElement("sitemappriority")] + public float SiteMapPriority { get; set; } + + [XmlIgnore] + public string SkinPath { get; set; } + + [XmlElement("skinsrc")] + public string SkinSrc { get; set; } + + [XmlElement("startdate")] + public DateTime StartDate { get; set; } + + [XmlElement("name")] + public string TabName { get; set; } + + [XmlElement("taborder")] + public int TabOrder { get; set; } + + [XmlElement("tabpath")] + public string TabPath { get; set; } + + [XmlElement("title")] + public string Title { get; set; } + + [XmlElement("uniqueid")] + public Guid UniqueId { get; set; } + + [XmlElement("versionguid")] + public Guid VersionGuid { get; set; } + + [XmlElement("iconfile")] + public string IconFile + { + get + { + this.IconFileGetter(ref this._iconFile, this.IconFileRaw); + return this._iconFile; + } + + set + { + this.IconFileRaw = value; + this._iconFile = null; } } + [XmlElement("iconfilelarge")] + public string IconFileLarge + { + get + { + this.IconFileGetter(ref this._iconFileLarge, this.IconFileLargeRaw); + return this._iconFileLarge; + } + + set + { + this.IconFileLargeRaw = value; + this._iconFileLarge = null; + } + } + + [XmlIgnore] + public bool IsSuperTab + { + get + { + if (this._superTabIdSet) + { + return this._isSuperTab; + } + + return this.PortalID == Null.NullInteger; + } + + set + { + this._isSuperTab = value; + this._superTabIdSet = true; + } + } + + [XmlIgnore] + public override int KeyID + { + get + { + return this.TabID; + } + + set + { + this.TabID = value; + } + } + + [XmlElement("skindoctype")] + public string SkinDoctype + { + get + { + if (string.IsNullOrEmpty(this.SkinSrc) == false && string.IsNullOrEmpty(this._skinDoctype)) + { + this._skinDoctype = this.CheckIfDoctypeConfigExists(); + if (string.IsNullOrEmpty(this._skinDoctype)) + { + this._skinDoctype = Host.Host.DefaultDocType; + } + } + + return this._skinDoctype; + } + + set + { + this._skinDoctype = value; + } + } + + [XmlElement("url")] + public string Url { get; set; } + + [XmlIgnore] + public bool UseBaseFriendlyUrls { get; set; } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { string outputFormat = string.Empty; @@ -869,6 +869,26 @@ public override void Fill(IDataReader dr) this.IsSystem = Null.SetNullBoolean(dr["IsSystem"]); } + public string GetCurrentUrl(string cultureCode) + { + string url = null; + if (this._tabUrls != null && this._tabUrls.Count > 0) + { + TabUrlInfo tabUrl = this._tabUrls.CurrentUrl(cultureCode); + if (tabUrl != null) + { + url = tabUrl.Url; + } + } + + return url ?? string.Empty; + } + + public string GetTags() + { + return string.Join(",", this.Terms.Select(t => t.Name)); + } + internal void ClearTabUrls() { this._tabUrls = null; @@ -971,25 +991,5 @@ private void IconFileGetter(ref string iconFile, string iconRaw) iconFile = fileInfo != null ? FileManager.Instance.GetUrl(fileInfo) : iconRaw; } } - - public string GetCurrentUrl(string cultureCode) - { - string url = null; - if (this._tabUrls != null && this._tabUrls.Count > 0) - { - TabUrlInfo tabUrl = this._tabUrls.CurrentUrl(cultureCode); - if (tabUrl != null) - { - url = tabUrl.Url; - } - } - - return url ?? string.Empty; - } - - public string GetTags() - { - return string.Join(",", this.Terms.Select(t => t.Name)); - } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs index 0c430ba545f..365dacbb51f 100644 --- a/DNN Platform/Library/Entities/Tabs/TabModulesController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabModulesController.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Entities.Tabs using DotNetNuke.UI.Skins; public class TabModulesController : ServiceLocator, ITabModulesController - { + { public ArrayList GetTabModules(TabInfo tab) { var objPaneModules = new Dictionary(); @@ -34,17 +34,17 @@ public ArrayList GetTabModules(TabInfo tab) { objPaneModules.Add(configuringModule.PaneName, 0); } - + configuringModule.PaneModuleCount = 0; if (!configuringModule.IsDeleted) { objPaneModules[configuringModule.PaneName] = objPaneModules[configuringModule.PaneName] + 1; configuringModule.PaneModuleIndex = objPaneModules[configuringModule.PaneName] - 1; } - + configuredModules.Add(configuringModule); } - + foreach (ModuleInfo module in configuredModules) { module.PaneModuleCount = objPaneModules[module.PaneName]; @@ -69,7 +69,7 @@ public Dictionary GetTabModuleSettingsByName(string settingName) { result[dr.GetInt32(0)] = dr.GetString(1); } - + return result; } }); @@ -96,28 +96,28 @@ public IList GetTabModuleIdsBySetting(string settingName, string expectedVa { result.Add(dr.GetInt32(0)); } - + return result; } - } - + } + protected override Func GetFactory() { return () => new TabModulesController(); } - + private static void ConfigureModule(ModuleInfo cloneModule, TabInfo tab) { if (Null.IsNull(cloneModule.StartDate)) { cloneModule.StartDate = DateTime.MinValue; } - + if (Null.IsNull(cloneModule.EndDate)) { cloneModule.EndDate = DateTime.MaxValue; } - + if (string.IsNullOrEmpty(cloneModule.ContainerSrc)) { cloneModule.ContainerSrc = tab.ContainerSrc; @@ -141,6 +141,6 @@ private static IEnumerable GetModules(TabInfo tab) } return TabVersionBuilder.Instance.GetCurrentModules(tab.TabID); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs index 58b0ece57eb..5c22aba39b7 100644 --- a/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabPublishingController.cs @@ -70,13 +70,13 @@ public bool CanPublishingBePerformed(int tabID, int portalID) var workflowID = Convert.ToInt32(PortalController.GetPortalSetting("WorkflowID", portalID, "-1")); return (workflowID == 1) || (workflowID == -1); - } - + } + protected override Func GetFactory() { return () => new TabPublishingController(); } - + private void PublishTabInternal(TabInfo tab) { var allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); @@ -101,7 +101,7 @@ private void UnpublishTabInternal(TabInfo tab) { tab.TabPermissions.Remove(tab.TabPermissions.Cast().SingleOrDefault(p => p.TabPermissionID == tabPermissionId)); } - + TabPermissionController.SaveTabPermissions(tab); this.ClearTabCache(tab); } @@ -109,7 +109,7 @@ private void UnpublishTabInternal(TabInfo tab) private void ClearTabCache(TabInfo tabInfo) { TabController.Instance.ClearCache(tabInfo.PortalID); - + // Clear the Tab's Cached modules DataCache.ClearModuleCache(tabInfo.TabID); } @@ -126,17 +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; - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs b/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs index af4ce973ff1..c1e559e1569 100644 --- a/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs +++ b/DNN Platform/Library/Entities/Tabs/TabUrlInfo.cs @@ -11,32 +11,32 @@ namespace DotNetNuke.Entities.Tabs /// [Serializable] // 584 support sql session state public class TabUrlInfo - { + { public TabUrlInfo() { this.PortalAliasUsage = PortalAliasUsageType.Default; - } - + } + public string CultureCode { get; set; } - + public string HttpStatus { get; set; } - + public bool IsSystem { get; set; } - + public int PortalAliasId { get; set; } - + public PortalAliasUsageType PortalAliasUsage { get; set; } - + public string QueryString { get; set; } - + public int SeqNum { get; set; } - + public int TabId { get; set; } - + public int? CreatedByUserId { get; set; } - + public int? LastModifiedByUserId { get; set; } - public string Url { get; set; } + public string Url { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs index dab4342acfc..493490b2ed3 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/Exceptions/DnnTabVersionException.cs @@ -10,25 +10,25 @@ namespace DotNetNuke.Entities.Tabs.TabVersions.Exceptions /// Exception to notify error about managing tab versions. /// public class DnnTabVersionException : ApplicationException - { - /// + { + /// /// Initializes a new instance of the class. /// Constructs an instance of class with the specified message. /// /// The message to associate with the exception. - public DnnTabVersionException(string message) + public DnnTabVersionException(string message) : base(message) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Constructs an instance of class with the specified message and /// inner exception. /// /// The message to associate with the exception. /// The exception which caused this error. - public DnnTabVersionException(string message, Exception innerException) + public DnnTabVersionException(string message, Exception innerException) : base(message, innerException) { } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs index ab49c4277c5..7dba78e0230 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/ITabVersionBuilder.cs @@ -26,7 +26,7 @@ public interface ITabVersionBuilder /// User Id which creates the version. /// TabVersion filled with the new version data. TabVersion CreateNewVersion(int portalid, int tabId, int createdByUserId); - + /// /// Publish a Tab Version. /// @@ -86,7 +86,7 @@ public interface ITabVersionBuilder /// /// The Tab Id to be queried. /// User Id which rolls back the version. - /// Version Number of the version to be rolled back. + /// Version Number of the version to be rolled back. /// TabVersion RollBackVesion(int tabId, int createdByUserId, int versionNumber); diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs index c7c1c6890f3..bcb60bc85a1 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersion.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Entities.Tabs.TabVersions /// [Serializable] public class TabVersion : BaseEntityInfo - { + { /// /// Gets or sets id of the TabVersion object. /// @@ -35,6 +35,6 @@ public class TabVersion : BaseEntityInfo /// /// Gets or sets a value indicating whether true if the version is published. False if it is not published yet. /// - public bool IsPublished { get; set; } + public bool IsPublished { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs index bc3a2f92985..02920941de0 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionBuilder.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 DotNetNuke.Entities.Tabs.TabVersions { using System; @@ -20,15 +19,15 @@ namespace DotNetNuke.Entities.Tabs.TabVersions public class TabVersionBuilder : ServiceLocator, ITabVersionBuilder { - private const int DefaultVersionNumber = 1; + 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; private readonly ITabVersionController _tabVersionController; private readonly ITabVersionDetailController _tabVersionDetailController; - private readonly PortalSettings _portalSettings; - + private readonly PortalSettings _portalSettings; + public TabVersionBuilder() { this._tabController = TabController.Instance; @@ -37,8 +36,8 @@ public TabVersionBuilder() this._tabVersionController = TabVersionController.Instance; this._tabVersionDetailController = TabVersionDetailController.Instance; this._portalSettings = PortalSettings.Current; - } - + } + public void SetupFirstVersionForExistingTab(int portalId, int tabId) { if (!this._tabVersionSettings.IsVersioningEnabled(portalId, tabId)) @@ -71,7 +70,7 @@ public void Publish(int portalId, int tabId, int createdByUserId) { throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } - + if (tabVersion.IsPublished) { throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); @@ -94,12 +93,12 @@ public void Discard(int tabId, int createdByUserId) { throw new InvalidOperationException(string.Format(Localization.GetString("TabHasNotAnUnpublishedVersion", Localization.ExceptionsResourceFile), tabId)); } - + if (tabVersion.IsPublished) { throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionAlreadyPublished", Localization.ExceptionsResourceFile), tabId, tabVersion.Version)); } - + this.DiscardVersion(tabId, tabVersion); } @@ -109,7 +108,7 @@ public void DeleteVersion(int tabId, int createdByUserId, int version) this.ForceDeleteVersion(tabId, version); } - + public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) { this.CheckVersioningEnabled(tabId); @@ -145,7 +144,7 @@ public TabVersion RollBackVesion(int tabId, int createdByUserId, int version) Logger.Error(string.Format("There was a problem making rollbak of the module {0}. Message: {1}.", rollbackDetail.ModuleId, e.Message)); continue; } - + this._tabVersionDetailController.SaveTabVersionDetail(rollbackDetail, createdByUserId); // Check if restoring version contains modules to restore @@ -169,33 +168,6 @@ 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); @@ -253,8 +225,8 @@ public TabVersion GetUnPublishedVersion(int tabId) public IEnumerable GetCurrentModules(int tabId) { var cacheKey = string.Format(DataCache.PublishedTabModuleCacheKey, tabId); - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( cacheKey, DataCache.PublishedTabModuleCacheTimeOut, DataCache.PublishedTabModuleCachePriority), @@ -270,8 +242,8 @@ public int GetModuleContentLatestVersion(ModuleInfo module) { var versionableController = this.GetVersionableController(module); return versionableController != null ? versionableController.GetLatestVersion(module.ModuleID) : DefaultVersionNumber; - } - + } + protected override Func GetFactory() { return () => new TabVersionBuilder(); @@ -294,14 +266,14 @@ private static IEnumerable GetSnapShot(IEnumerable GetCurrentModulesInternal(int tabId) { var versioningEnabled = this._portalSettings != null && @@ -360,12 +359,11 @@ private void DiscardDetailWithoutPublishedTabVersions(int tabId, TabVersionDetai { this.DiscardDetail(tabId, unPublishedDetail); } - + this._moduleController.DeleteTabModule(tabId, unPublishedDetail.ModuleId, true); } - private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail unPublishedDetail, - TabVersionDetail[] publishedChanges) + private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail unPublishedDetail, TabVersionDetail[] publishedChanges) { if (unPublishedDetail.Action == TabVersionDetailAction.Deleted) { @@ -374,7 +372,7 @@ private void DiscardDetailWithPublishedTabVersions(int tabId, TabVersionDetail u { this.RestoreModuleInfo(tabId, restoredModuleDetail); } - + return; } @@ -409,7 +407,7 @@ private void ForceDeleteVersion(int tabId, int version) { throw new InvalidOperationException( string.Format( - Localization.GetString( + Localization.GetString( "TabVersionCannotBeDeleted_UnpublishedVersion", Localization.ExceptionsResourceFile), tabId, version)); } @@ -468,11 +466,11 @@ private void ForceDeleteVersion(int tabId, int version) { this.DiscardDetail(tabId, versionToDeleteDetail); } - + break; } } - + this.DeleteTmpVersionIfExists(tabId, versionToDelete); this._tabVersionController.DeleteTabVersion(tabId, versionToDelete.TabVersionId); this.ManageModulesToBeRestored(tabId, previousVersionDetails); @@ -526,12 +524,12 @@ private void DeleteOldestVersionIfTabHasMaxNumberOfVersions(int portalId, int ta var maxVersionsAllowed = this.GetMaxNumberOfVersions(portalId); var tabVersionsOrdered = this._tabVersionController.GetTabVersions(tabId).OrderByDescending(tv => tv.Version); - if (tabVersionsOrdered.Count() < maxVersionsAllowed) - { - return; - } - - // The last existing version is going to be deleted, therefore we need to add the snapshot to the previous one + if (tabVersionsOrdered.Count() < maxVersionsAllowed) + { + return; + } + + // The last existing version is going to be deleted, therefore we need to add the snapshot to the previous one var snapShotTabVersion = tabVersionsOrdered.ElementAtOrDefault(maxVersionsAllowed - 2); this.CreateSnapshotOverVersion(tabId, snapShotTabVersion); this.DeleteOldVersions(tabVersionsOrdered, snapShotTabVersion); @@ -604,20 +602,20 @@ private TabVersion PublishVersion(int portalId, int tabId, int createdByUserID, { TabController.Instance.MarkAsPublished(tab); } - + this._moduleController.ClearCache(tabId); return tabVersion; } 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, + return tabVersionDetails.Select(tabVersionDetail => new TabVersionDetail + { + ModuleId = tabVersionDetail.ModuleId, + ModuleOrder = tabVersionDetail.ModuleOrder, + ModuleVersion = tabVersionDetail.ModuleVersion, + PaneName = tabVersionDetail.PaneName, + Action = tabVersionDetail.Action, }).ToList(); } @@ -652,7 +650,7 @@ private void CreateSnapshotOverVersion(int tabId, TabVersion snapshotTabVersion, { if (snapShotTabVersionDetails.All(tvd => tvd.TabVersionDetailId != existingDetail.TabVersionDetailId)) { - this._tabVersionDetailController.DeleteTabVersionDetail( + this._tabVersionDetailController.DeleteTabVersionDetail( existingDetail.TabVersionId, existingDetail.TabVersionDetailId); } @@ -666,7 +664,7 @@ private void CreateSnapshotOverVersion(int tabId, TabVersion snapshotTabVersion, deleteDetail.Action == TabVersionDetailAction.Added); if (moduleAddedAndDeleted) { - this._tabVersionDetailController.DeleteTabVersionDetail( + this._tabVersionDetailController.DeleteTabVersionDetail( existingDetail.TabVersionId, existingDetail.TabVersionDetailId); } @@ -711,7 +709,7 @@ private void DeleteOldVersions(IEnumerable tabVersionsOrdered, TabVe var oldVersionDetail = oldVersionDetails.ElementAtOrDefault(j - 1); this._tabVersionDetailController.DeleteTabVersionDetail(oldVersionDetail.TabVersionId, oldVersionDetail.TabVersionDetailId); } - + this._tabVersionController.DeleteTabVersion(oldVersion.TabId, oldVersion.TabVersionId); } } @@ -728,7 +726,7 @@ private IEnumerable ConvertToModuleInfo(IEnumerable ConvertToModuleInfo(IEnumerable, ITabVersionController { - private static readonly DataProvider Provider = DataProvider.Instance(); - + private static readonly DataProvider Provider = DataProvider.Instance(); + public TabVersion GetTabVersion(int tabVersionId, int tabId, bool ignoreCache = false) { return this.GetTabVersions(tabId, ignoreCache).SingleOrDefault(tv => tv.TabVersionId == tabVersionId); @@ -32,9 +32,9 @@ public IEnumerable GetTabVersions(int tabId, bool ignoreCache = fals { DataCache.RemoveCache(tabCacheKey); } - - var tabVersions = CBO.Instance.GetCachedObject>( - new CacheItemArgs( + + var tabVersions = CBO.Instance.GetCachedObject>( + new CacheItemArgs( tabCacheKey, DataCache.TabVersionsCacheTimeOut, DataCache.TabVersionsCachePriority), @@ -43,7 +43,7 @@ public IEnumerable GetTabVersions(int tabId, bool ignoreCache = fals return tabVersions; } - + public void SaveTabVersion(TabVersion tabVersion) { this.SaveTabVersion(tabVersion, tabVersion.CreatedByUserID, tabVersion.LastModifiedByUserID); @@ -71,7 +71,7 @@ public TabVersion CreateTabVersion(int tabId, int createdByUserID, bool isPublis { throw new InvalidOperationException(string.Format(Localization.GetString("TabVersionCannotBeCreated_UnpublishedVersionAlreadyExists", Localization.ExceptionsResourceFile))); } - + newVersion = lastTabVersion.Version + 1; } @@ -90,8 +90,8 @@ public void DeleteTabVersion(int tabId, int tabVersionId) public void DeleteTabVersionDetailByModule(int moduleId) { Provider.DeleteTabVersionDetailByModule(moduleId); - } - + } + protected override Func GetFactory() { return () => new TabVersionController(); @@ -100,8 +100,8 @@ protected override Func GetFactory() private static string GetTabVersionsCacheKey(int tabId) { return string.Format(DataCache.TabVersionsCacheKey, tabId); - } - + } + private void ClearCache(int tabId) { DataCache.RemoveCache(GetTabVersionsCacheKey(tabId)); diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs index 20da0efa000..c7a96ae0c3f 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetail.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Entities.Tabs.TabVersions ///
    [Serializable] public class TabVersionDetail : BaseEntityInfo - { + { /// /// Gets or sets id of TabVersionDetail. /// @@ -45,6 +45,6 @@ public class TabVersionDetail : BaseEntityInfo /// /// Gets or sets action which provoked the detail. /// - public TabVersionDetailAction Action { get; set; } + public TabVersionDetailAction Action { get; set; } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs index 79cddbc2617..f084392a189 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionDetailController.cs @@ -14,8 +14,8 @@ namespace DotNetNuke.Entities.Tabs.TabVersions public class TabVersionDetailController : ServiceLocator, ITabVersionDetailController { - private static readonly DataProvider Provider = DataProvider.Instance(); - + private static readonly DataProvider Provider = DataProvider.Instance(); + public TabVersionDetail GetTabVersionDetail(int tabVersionDetailId, int tabVersionId, bool ignoreCache = false) { return this.GetTabVersionDetails(tabVersionId, ignoreCache).SingleOrDefault(tvd => tvd.TabVersionDetailId == tabVersionDetailId); @@ -29,8 +29,8 @@ public IEnumerable GetTabVersionDetails(int tabVersionId, bool return CBO.FillCollection(Provider.GetTabVersionDetails(tabVersionId)); } - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( GetTabVersionDetailCacheKey(tabVersionId), DataCache.TabVersionDetailsCacheTimeOut, DataCache.TabVersionDetailsCachePriority), @@ -54,7 +54,7 @@ public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdB public void SaveTabVersionDetail(TabVersionDetail tabVersionDetail, int createdByUserID, int modifiedByUserID) { - tabVersionDetail.TabVersionDetailId = Provider.SaveTabVersionDetail( + tabVersionDetail.TabVersionDetailId = Provider.SaveTabVersionDetail( tabVersionDetail.TabVersionDetailId, tabVersionDetail.TabVersionId, tabVersionDetail.ModuleId, tabVersionDetail.ModuleVersion, tabVersionDetail.PaneName, tabVersionDetail.ModuleOrder, (int)tabVersionDetail.Action, createdByUserID, @@ -71,16 +71,16 @@ public void DeleteTabVersionDetail(int tabVersionId, int tabVersionDetailId) public void ClearCache(int tabVersionId) { DataCache.RemoveCache(GetTabVersionDetailCacheKey(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/TabVersionSettings.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs index f268091876e..a3901ab9715 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionSettings.cs @@ -13,11 +13,11 @@ namespace DotNetNuke.Entities.Tabs.TabVersions using DotNetNuke.Framework; public class TabVersionSettings : ServiceLocator, ITabVersionSettings - { + { private const int TabVersionsMaxNumber = 5; private const string TabVersionQueryStringParam = "DnnTabVersion"; - private const string TabVersioningSettingKey = "TabVersioningSettingKey"; - + private const string TabVersioningSettingKey = "TabVersioningSettingKey"; + public int GetMaxNumberOfVersions(int portalId) { Requires.NotNegative("portalId", portalId); @@ -73,7 +73,7 @@ public bool IsVersioningEnabled(int portalId, int tabId) return isVersioningEnableForTab; } - + public string GetTabVersionQueryStringParameter(int portalId) { Requires.NotNegative("portalId", portalId); diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs index 96f15b8950d..819695632ab 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionTracker.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Tabs.TabVersions using DotNetNuke.Framework; internal class TabVersionTracker : ServiceLocator, ITabChangeTracker - { + { /// /// Tracks a version detail when a module is added to a page. /// @@ -161,13 +161,13 @@ public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int original { Services.Exceptions.Exceptions.LogException(ex); } - } - + } + protected override Func GetFactory() { return () => new TabVersionTracker(); - } - + } + private static void ProcessAdditionDetail(ModuleInfo module, int moduleVersion, int userId, TabVersion targetVersion) { if (IsHostModule(module)) @@ -181,7 +181,7 @@ private static void ProcessAdditionDetail(ModuleInfo module, int moduleVersion, .Where(tvd => tvd.ModuleId == module.ModuleID); foreach (var existingTabDetail in existingTabDetails) { - TabVersionDetailController.Instance.DeleteTabVersionDetail( + TabVersionDetailController.Instance.DeleteTabVersionDetail( existingTabDetail.TabVersionId, existingTabDetail.TabVersionDetailId); } @@ -203,7 +203,7 @@ private static void ProcessDeletionDetail(ModuleInfo module, int moduleVersion, .SingleOrDefault(tvd => tvd.ModuleId == module.ModuleID); if (existingTabDetail != null) { - TabVersionDetailController.Instance.DeleteTabVersionDetail( + TabVersionDetailController.Instance.DeleteTabVersionDetail( existingTabDetail.TabVersionId, existingTabDetail.TabVersionDetailId); @@ -263,6 +263,6 @@ private static TabVersionDetail CreateNewTabVersionDetailObjectFromModule(int ta PaneName = paneName, Action = action, }; - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs index 611f6855525..8ac637a44ed 100644 --- a/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs +++ b/DNN Platform/Library/Entities/Tabs/TabVersions/TabVersionUtils.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Entities.Tabs.TabVersions /// This Class ofers a set of methods useful and reusable along the Tab Version API. ///
    internal static class TabVersionUtils - { + { /// /// Try to get the version number from the current URL. /// @@ -31,7 +31,7 @@ internal static bool TryGetUrlVersion(out int versionInt) versionInt = Null.NullInteger; return false; } - + return int.TryParse(version, out versionInt); } @@ -61,7 +61,7 @@ internal static bool CanSeeVersionedPages(TabInfo tab) { return false; } - + var isAdminUser = currentPortalSettings.UserInfo.IsSuperUser || PortalSecurity.IsInRole(currentPortalSettings.AdministratorRoleName); if (isAdminUser) { @@ -69,14 +69,14 @@ internal static bool CanSeeVersionedPages(TabInfo tab) } return TabPermissionController.HasTabPermission(tab.TabPermissions, "EDIT,CONTENT,MANAGE"); - } - + } + private static string GetTabVersionQueryStringValue() { var currentPortal = PortalController.Instance.GetCurrentPortalSettings(); return currentPortal == null ? string.Empty : HttpContext.Current.Request.QueryString[TabVersionSettings.Instance.GetTabVersionQueryStringParameter(currentPortal.PortalId)]; - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs index 2d17f3ea904..fa04ce72866 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowSettings.cs @@ -14,18 +14,18 @@ namespace DotNetNuke.Entities.Tabs using DotNetNuke.Framework; public class TabWorkflowSettings : ServiceLocator, ITabWorkflowSettings - { + { private const string DefaultTabWorkflowKey = "DefaultTabWorkflowKey"; - private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; + private const string TabWorkflowEnableKey = "TabWorkflowEnabledKey"; private readonly ITabController _tabController; - private readonly ISystemWorkflowManager _systemWorkflowManager; - + private readonly ISystemWorkflowManager _systemWorkflowManager; + public TabWorkflowSettings() { this._tabController = TabController.Instance; this._systemWorkflowManager = SystemWorkflowManager.Instance; - } - + } + public int GetDefaultTabWorkflowId(int portalId) { var workflowId = PortalController.GetPortalSettingAsInteger(DefaultTabWorkflowKey, portalId, Null.NullInteger); @@ -38,7 +38,7 @@ public int GetDefaultTabWorkflowId(int portalId) PortalController.UpdatePortalSetting(portalId, DefaultTabWorkflowKey, workflowId.ToString(CultureInfo.InvariantCulture), true); } } - + return workflowId; } @@ -82,11 +82,11 @@ public bool IsWorkflowEnabled(int portalId) } return Convert.ToBoolean(PortalController.GetPortalSetting(TabWorkflowEnableKey, portalId, bool.FalseString)); - } - + } + protected override Func GetFactory() { return () => new TabWorkflowSettings(); - } + } } } diff --git a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs index 01318ca0ac3..93fa620399b 100644 --- a/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs +++ b/DNN Platform/Library/Entities/Tabs/TabWorkflowTracker.cs @@ -17,12 +17,12 @@ namespace DotNetNuke.Entities.Tabs internal class TabWorkflowTracker : ServiceLocator, ITabChangeTracker { - private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(TabWorkflowTracker)); + private static readonly DnnLogger Logger = DnnLogger.GetClassLogger(typeof(TabWorkflowTracker)); private readonly ITabController _tabController; private readonly IWorkflowEngine _workflowEngine; private readonly IWorkflowManager _workflowManager; - private readonly ITabWorkflowSettings _tabWorkflowSettings; - + private readonly ITabWorkflowSettings _tabWorkflowSettings; + public TabWorkflowTracker() { this._tabController = TabController.Instance; @@ -30,7 +30,7 @@ public TabWorkflowTracker() this._workflowManager = WorkflowManager.Instance; this._tabWorkflowSettings = TabWorkflowSettings.Instance; } - + /// /// Tracks a workflow instance when a module is added to a page. /// @@ -53,11 +53,6 @@ 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. /// @@ -80,7 +75,7 @@ public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTa { this.TrackModuleAddition(module, moduleVersion, userId); } - + /// /// Tracks a workflow instance when a copied module is deleted from an exisitng page. /// @@ -91,8 +86,13 @@ public void TrackModuleCopy(ModuleInfo module, int moduleVersion, int originalTa public void TrackModuleUncopy(ModuleInfo module, int moduleVersion, int originalTabId, int userId) { this.TrackModuleDeletion(module, moduleVersion, userId); - } - + } + + protected override Func GetFactory() + { + return () => new TabWorkflowTracker(); + } + private void NotifyWorkflowAboutChanges(int portalId, int tabId, int userId) { try @@ -126,6 +126,6 @@ private Workflow GetCurrentOrDefaultWorkflow(ContentItem item, int portalId) var defaultWorkflow = this._tabWorkflowSettings.GetDefaultTabWorkflowId(portalId); return this._workflowManager.GetWorkflow(defaultWorkflow); - } + } } } diff --git a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs index 458d69258d7..f170ce46b03 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedFriendlyUrlProvider.cs @@ -137,31 +137,6 @@ 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; @@ -219,6 +194,31 @@ internal static string ForceLowerCaseIfAllowed(TabInfo tab, string url, Friendly return url; } + 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); + } + private static string AddPage(string path, string pageName) { string friendlyPath = path; @@ -492,82 +492,6 @@ private static string GetCultureOfSettings(PortalSettings portalSettings) return cultureCode; } - private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, string portalAlias, PortalSettings portalSettings) - { - Guid parentTraceId = Guid.Empty; - int portalId = (portalSettings != null) ? portalSettings.PortalId : tab.PortalID; - bool cultureSpecificAlias; - var localSettings = new FriendlyUrlSettings(portalId); - - // Call GetFriendlyAlias to get the Alias part of the url - if (string.IsNullOrEmpty(portalAlias) && portalSettings != null) - { - portalAlias = portalSettings.PortalAlias.HTTPAlias; - } - - string friendlyPath = GetFriendlyAlias( - path, - ref portalAlias, - portalId, - localSettings, - portalSettings, - out cultureSpecificAlias); - - if (portalSettings != null) - { - portalSettings = CheckAndUpdatePortalSettingsForNewAlias(portalSettings, cultureSpecificAlias, portalAlias); - } - - if (tab == null && path == "~/" && string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) == 0) - { - // this is a request for the site root for he dnn logo skin object (642) - // do nothing, the friendly alias is already correct - we don't want to append 'default.aspx' on the end - } - else - { - // Get friendly path gets the standard dnn-style friendly path - friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, localSettings); - - if (portalSettings == null) - { - PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(portalAlias, tab.PortalID); - - portalSettings = new PortalSettings(tab.TabID, alias); - } - - // ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url - friendlyPath = ImproveFriendlyUrl( - tab, - friendlyPath, - pageName, - portalSettings, - false, - cultureSpecificAlias, - localSettings, - parentTraceId); - } - - // set it to lower case if so allowed by settings - friendlyPath = ForceLowerCaseIfAllowed(tab, friendlyPath, localSettings); - - // Replace http:// by https:// if SSL is enabled and site is marked as secure - // (i.e. requests to http://... will be redirected to https://...) - if (tab != null && portalSettings.SSLEnabled && tab.IsSecure && - friendlyPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) - { - 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)) - { - friendlyPath = friendlyPath.Replace("https://" + portalAlias, "https://" + sslUrl); - } - } - - return friendlyPath; - } - private static string GetFriendlyAlias( string path, ref string httpAlias, @@ -1464,5 +1388,81 @@ private static bool TransformStandardPath(ref string newPath, ref string newTabP return builtInUrl; } + + private string FriendlyUrlInternal(TabInfo tab, string path, string pageName, string portalAlias, PortalSettings portalSettings) + { + Guid parentTraceId = Guid.Empty; + int portalId = (portalSettings != null) ? portalSettings.PortalId : tab.PortalID; + bool cultureSpecificAlias; + var localSettings = new FriendlyUrlSettings(portalId); + + // Call GetFriendlyAlias to get the Alias part of the url + if (string.IsNullOrEmpty(portalAlias) && portalSettings != null) + { + portalAlias = portalSettings.PortalAlias.HTTPAlias; + } + + string friendlyPath = GetFriendlyAlias( + path, + ref portalAlias, + portalId, + localSettings, + portalSettings, + out cultureSpecificAlias); + + if (portalSettings != null) + { + portalSettings = CheckAndUpdatePortalSettingsForNewAlias(portalSettings, cultureSpecificAlias, portalAlias); + } + + if (tab == null && path == "~/" && string.Compare(pageName, Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) == 0) + { + // this is a request for the site root for he dnn logo skin object (642) + // do nothing, the friendly alias is already correct - we don't want to append 'default.aspx' on the end + } + else + { + // Get friendly path gets the standard dnn-style friendly path + friendlyPath = GetFriendlyQueryString(tab, friendlyPath, pageName, localSettings); + + if (portalSettings == null) + { + PortalAliasInfo alias = PortalAliasController.Instance.GetPortalAlias(portalAlias, tab.PortalID); + + portalSettings = new PortalSettings(tab.TabID, alias); + } + + // ImproveFriendlyUrl will attempt to remove tabid/nn and other information from the Url + friendlyPath = ImproveFriendlyUrl( + tab, + friendlyPath, + pageName, + portalSettings, + false, + cultureSpecificAlias, + localSettings, + parentTraceId); + } + + // set it to lower case if so allowed by settings + friendlyPath = ForceLowerCaseIfAllowed(tab, friendlyPath, localSettings); + + // Replace http:// by https:// if SSL is enabled and site is marked as secure + // (i.e. requests to http://... will be redirected to https://...) + if (tab != null && portalSettings.SSLEnabled && tab.IsSecure && + friendlyPath.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) + { + 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)) + { + friendlyPath = friendlyPath.Replace("https://" + portalAlias, "https://" + sslUrl); + } + } + + return friendlyPath; + } } } diff --git a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs index 84b7d9d416c..5e12f83a714 100644 --- a/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.cs +++ b/DNN Platform/Library/Entities/Urls/AdvancedUrlRewriter.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 DotNetNuke.Entities.Urls { using System; @@ -31,14 +30,152 @@ 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; + } + + /// + /// 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; + } + internal override void RewriteUrl(object sender, EventArgs e) { Guid parentTraceId = Guid.Empty; @@ -98,3013 +235,2877 @@ 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; - } - - // we are fine here, lets prepare URL to be validated in regex - urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); - } + 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); - // 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 (cpa != null) + { + httpAlias = cpa.HTTPAlias; + continueLoop = false; + } - isPrimaryAlias = aliasEx.IsPrimary; - aliasInfo = aliasEx; - break; - } - } + 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); - return aliasInfo; - } + // 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; + } + } + } + } - 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; - - HttpRequest request = context.Request; - HttpResponse response = context.Response; - string requestType = request.RequestType; - NameValueCollection queryStringCol = request.QueryString; + // 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; - try - { - string fullUrl, querystring; + // 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; + } + } + } + } + } + } + } - // 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); + // 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; + } + } + } - showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); - string ignoreRegex = settings.IgnoreRegex; - bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - bool redirectAlias = false; - if (!ignoreRequest) - { - // set original path - context.Items["UrlRewrite:OriginalUrl"] = requestUri.AbsoluteUri; + return incorrectAlias; + } - // set the path of the result object, and determine if a redirect is allowed on this request - result.SetOriginalPath(requestUri.ToString(), settings); + private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) + { + if (context != null) + { + HttpResponse response = context.Response; - // 737 : set the mobile browser - result.SetBrowserType(request, response, settings); + // 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"; + } - // 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) + portalSettings = ps.PortalId.ToString(); + if (ps.PortalAlias != null) { - settings = new FriendlyUrlSettings(requestedAlias.PortalID); - result.SetRedirectAllowed(result.OriginalPath, settings); + portalSettings += ":" + ps.PortalAlias.HTTPAlias; } + } + } - 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 - { - // 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; - } - } - } + 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++; } } - ignoreRegex = settings.IgnoreRegex; - ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); - if (!ignoreRequest) + if (ex != null) { - // check to see if a post request - if (request.RequestType == "POST") + response.AppendHeader("X-" + _productName + "-Ex", ex.Message); + } + } + } + + 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)) { - postRequest = true; + result.DomainName = Globals.GetDomainName(context.Request); // parse the domain name out of the request } - // 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)) + // Get all the existing aliases + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + + bool autoaddAlias; + bool isPrimary = false; + if (!aliases.Any()) { - // it was an incorrect alias - PortalAliasInfo primaryAlias = PortalAliasController.Instance.GetPortalAlias(primaryHttpAlias); - if (primaryAlias != null) + autoaddAlias = true; + isPrimary = true; + } + else + { + autoaddAlias = true; + foreach (var alias in aliases) { - result.PrimaryAlias = primaryAlias; + if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 + && result.DomainName.Length >= alias.HTTPAlias.Length) + { + autoaddAlias = false; + break; + } } - - // try and redirect the alias if the settings allow it - redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); } - if (redirectAlias) + if (autoaddAlias) { - // 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; - } + var portalAliasInfo = new PortalAliasInfo + { + PortalID = portalId, + HTTPAlias = result.DomainName, + IsPrimary = isPrimary, + }; + PortalAliasController.Instance.AddPortalAlias(portalAliasInfo); - if (!finished) + 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 + { + ceSection = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); + } + +// 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") { - // 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 + isPostback = true; + } - // Check if we have a standard url - var uri = new Uri(fullUrl); - if (uri.PathAndQuery.StartsWith("/" + Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + if (result != null && ex != null) + { + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + if (ex.InnerException != null) { - result.DoRewrite = true; - result.Action = ActionType.CheckFor301; - result.RewritePath = Globals.glbDefaultPage + uri.Query; + result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); + result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); } else { - bool isPhysicalResource; - CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); - } - - // return 404 if there is no portal alias for a rewritten request - if (result.DoRewrite && result.PortalAlias == null) - { - // 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; - - Handle404OrException(settings, context, null, result, false, showDebug); - finished = true; // cannot fulfil request unless correct portal alias specified + result.DebugMessages.Add("Inner Ex : null"); } } - // now we may know the TabId. If the current alias is not the same as the primary alias, - // we should check if the current alias is indeed a valid custom alias for the current tab. - if (result.TabId > 0 && result.HttpAlias != result.PrimaryAlias.HTTPAlias && !CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) + string errRH; + string errRV; + int statusCode; + if (result != null && result.Action != ActionType.Output404) { - //it was an incorrect alias - //try and redirect the alias if the settings allow it - if( RedirectPortalAlias(result.PrimaryAlias.HTTPAlias, ref result, settings)) + // output everything but 404 (usually 500) + if (settings.TabId500 > -1) // tabid specified for 500 error page, use that { - //not correct alias for tab : 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; + useDNNTab = true; + errTabId = settings.TabId500; } - } - if (!finished && result.DoRewrite) + errUrl = settings.Url500; + errRH = "X-UrlRewriter-500"; + errRV = "500 Rewritten to {0} : {1}"; + statusCode = 500; + status = "500 Internal Server Error"; + } + else // output 404 error { - // 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) + if (settings.TabId404 > -1) // if the tabid is specified for a 404 page, then use that { - string culture; - string skin; - BrowserTypes browserType; - primaryAliases.GetSettingsByPortalIdAndAlias(result.PortalId, result.HttpAlias, - out culture, - out browserType, - out skin); - - // 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); - } + useDNNTab = true; + errTabId = settings.TabId404; } - } - if (!finished && result.DoRewrite) - { - // if so, do the rewrite - if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) + 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.RewritePath.Contains(Globals.glbDefaultPage) == false) - { - RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); - } - else + try { - // if there is no TabId and we have the domain - if (!result.RewritePath.ToLowerInvariant().Contains("tabId=")) + // 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); + requestedUrl = result.OriginalPath; } - else + + if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { - RewriterUtils.RewriteUrl(context, result.RewritePath); + useDNNTab = false; + + // if we have a match in the 404 regex value, then don't use the tabid } } - } - 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)) + catch (Exception regexEx) { - 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); + // .some type of exception : output in response header, and go back to using the tabid + response.AppendHeader("X-UrlRewriter-404Exception", regexEx.Message); } } + + errUrl = settings.Url404; + errRH = "X-UrlRewriter-404"; + errRV = "404 Rewritten to {0} : {1} : Reason {2}"; + status = "404 Not Found"; + statusCode = 404; } - if (!finished) + // check for 404 logging + if (result == null || result.Action == ActionType.Output404) { - // check to see if this tab has an external url that should be forwared or not - finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); + // Log 404 errors to Event Log + UrlRewriterUtils.Log404(request, settings, result); } - // 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))) + // 912 : use unhandled 404 switch + string reason404 = null; + bool unhandled404 = true; + if (useDNNTab && errTabId > -1) { - // 301 redirect to new location based on parameter match - if (response != null) + unhandled404 = false; // we're handling it here + TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); + if (errTab != null) { - switch (result.Action) + bool redirect = false; + + // 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) { - 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; + reason = result.Reason.ToString(); } - } - finished = true; - } + response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", + errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", + reason)); - // 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) - { - 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 - { - finished = true; - response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); + // show debug messages even if in debug mode + if (context != null && response != null && result != null && showDebug) + { + ShowDebugData(context, result.OriginalPath, result, null); + } - if (showDebug) + if (!isPostback) { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); + response.ClearContent(); + response.StatusCode = statusCode; + response.Status = status; } + else + { + redirect = true; - // show the 404 page if configured - result.Reason = RedirectReason.Requested_404; - Handle404OrException(settings, context, null, result, true, showDebug); - } - } + // redirect postbacks as you can't postback successfully to a server.transfer + } - 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) - { - finished = true; + errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, string.Empty); - if (showDebug) + // have to update the portal settings with the new tabid + PortalSettings ps = null; + if (context != null && context.Items != null) + { + if (context.Items.Contains("PortalSettings")) { - ShowDebugData(context, requestUri.AbsoluteUri, result, null); + ps = (PortalSettings)context.Items["PortalSettings"]; + context.Items.Remove("PortalSettings"); // nix it from the context } + } - // 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 (ps != null && ps.PortalAlias != null) + { + ps = new PortalSettings(errTabId, ps.PortalAlias); } else { - Globals.SetApplicationName(result.PortalId); - - // load the PortalSettings into current context - var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - - // set the primary alias if one was specified - if (result.PrimaryAlias != null) + if (result.HttpAlias != null && result.PortalId > -1) { - portalSettings.PrimaryAlias = result.PrimaryAlias; + PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); + ps = new PortalSettings(errTabId, pa); } - - if (result.CultureCode != null && fullUrl.Contains(result.CultureCode) && - portalSettings.DefaultLanguage == result.CultureCode) + else { - // 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; - } + // 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]; - int portalHomeTabId = portalSettings.HomeTabId; - if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) - { - context.Items.Add("PortalSettings", portalSettings); + // list of aliases from database + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(singlePortal.PortalID).ToList(); - // 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()); - } + // list of aliases from Advanced Url settings + List chosen = aliases.GetAliasesForPortalId(singlePortal.PortalID); + PortalAliasInfo useFor404 = null; - // 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) + // 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.FinalUrl.StartsWith("https://")) + if (useFor404 == null) { - if (showDebug) + useFor404 = pa; // first one by default + } + + // matching? + if (chosen != null && chosen.Count > 0) + { + if (chosen.Contains(pa.HTTPAlias)) { - /* - 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); + useFor404 = pa; } - - 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; - } + break; // no further checking } } - } - } - else - { - // check for, and do a 301 redirect if required - if (CheckForRedirects(requestUri, fullUrl, queryStringCol, result, requestType, settings, portalHomeTabId)) - { - if (response != null) + + // now configure that as the portal settings + if (useFor404 != 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; - } + // 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); } - } - } - // show debug messages after extensionless-url special 404 handling - if (showDebug) - { - ShowDebugData(context, fullUrl, result, null); + response.StatusCode = statusCode; + response.Status = status; + } } } - } - 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 (response != null) + else { - if (showDebug) + // fallback output if not valid settings + if (result != null && result.Action == ActionType.Output404) { - ShowDebugData(context, requestUri.AbsoluteUri, result, ex); + // 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"; } - - if (result != null) + else { - result.Ex = ex; - result.Reason = RedirectReason.Exception; + // 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; + } } - - Handle404OrException(settings, context, ex, result, false, showDebug); } - else + + if (ex != null) { - if (result != null && result.DebugMessages != null) + if (context != null) { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + if (context.Items.Contains("UrlRewrite:Exception") == false) + { + context.Items.Add("UrlRewrite:Exception", ex.Message); + context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); + } } - throw; + 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.
    "); + } + } + } } - } - finally - { - // 809 : add in new code copied from urlRewrite class in standard Url Rewrite module - if (context != null && context.Items["FirstRequest"] != null) + + string errorPageHtmlBody = errorPageHtml.ToString(); + if (errorPageHtmlBody.Length > 0) { - context.Items.Remove("FirstRequest"); + response.Write(errorPageHtmlHeader); + response.Write(errorPageHtmlBody); + response.Write(errorPageHtmlFooter); + } - // process any messages in the eventQueue for the Application_Start_FIrstRequest event - EventQueueController.ProcessMessages("Application_Start_FirstRequest"); + if (ex != null) + { + UrlRewriterUtils.LogExceptionInRequest(ex, status, result); } } } - private static void ShowDebugData(HttpContext context, string requestUri, UrlAction result, Exception ex) + private static IPrincipal GetCurrentPrincipal(HttpContext context) { - if (context != null) - { - HttpResponse response = context.Response; + // Extract the forms authentication cookie + var authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; + var currentPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty), new string[0]); - // handle null responses wherever they might be found - this routine must be tolerant to all kinds of invalid inputs - if (requestUri == null) + try + { + if (authCookie != null) { - requestUri = "null Uri"; + var authTicket = FormsAuthentication.Decrypt(authCookie.Value); + if (authTicket != null && !authTicket.Expired) + { + var roles = authTicket.UserData.Split('|'); + var id = new FormsIdentity(authTicket); + currentPrincipal = new GenericPrincipal(id, roles); + } } + } + catch (Exception) + { + // do nothing here. + } - 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; - } + return currentPrincipal; + } - // 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"; + private static bool CheckForDebug(HttpRequest request, NameValueCollection queryStringCol, bool debugEnabled) + { + string debugValue = string.Empty; + bool retVal = false; - // 949 : don't rely on 'result' being non-null - if (result != null) + if (debugEnabled) + { + const string debugToken = "_aumdebug"; + if (queryStringCol != null && queryStringCol[debugToken] != null) { - browser = result.BrowserType.ToString(); + debugValue = queryStringCol[debugToken]; } - - if (context.Items.Contains("PortalSettings")) + else { - var ps = (PortalSettings)context.Items["PortalSettings"]; - if (ps != null) + if (request != null) { - portalSettings = ps.PortalId.ToString(); - if (ps.PortalAlias != null) - { - portalSettings += ":" + ps.PortalAlias.HTTPAlias; - } + debugValue = request.Params.Get("HTTP_" + debugToken.ToUpper()); + } + + if (debugValue == null) + { + debugValue = "false"; } } + } - 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); - } + switch (debugValue.ToLowerInvariant()) + { + case "true": + retVal = true; + break; } + + return retVal; } - private static void Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, bool transfer, bool showDebug) + private static bool CheckForTabExternalForwardOrRedirect( + HttpContext context, + ref UrlAction result, + HttpResponse response, + FriendlyUrlSettings settings, + Guid parentTraceId) { - // handle Auto-Add Alias - if (result.Action == ActionType.Output404 && CanAutoAddPortalAlias()) + bool finished = false; + HttpRequest request = null; + if (context != null) { - // 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 all the existing aliases - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - - bool autoaddAlias; - bool isPrimary = false; - if (!aliases.Any()) - { - autoaddAlias = true; - isPrimary = true; - } - else - { - autoaddAlias = true; - foreach (var alias in aliases) - { - if (result.DomainName.ToLowerInvariant().IndexOf(alias.HTTPAlias, StringComparison.Ordinal) == 0 - && result.DomainName.Length >= alias.HTTPAlias.Length) - { - autoaddAlias = false; - break; - } - } - } - - 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); - } - } + request = context.Request; } - if (context != null) + try { - 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 - { - ceSection = (CustomErrorsSection)WebConfigurationManager.GetSection("system.web/customErrors"); - } - -// 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 - } + // 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")); - /* 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) + // 594 : do not redirect settings pages for external urls + if (allowRedirect) { - if (request.RequestType == "POST") - { - isPostback = true; - } - - if (result != null && ex != null) - { - result.DebugMessages.Add("Exception: " + ex.Message); - result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); - if (ex.InnerException != null) - { - result.DebugMessages.Add("Inner Ex : " + ex.InnerException.Message); - result.DebugMessages.Add("Stack Trace: " + ex.InnerException.StackTrace); - } - else - { - 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"; - } - else // output 404 error + TabInfo tab; + allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); + if (allowRedirect) { - if (settings.TabId404 > -1) // if the tabid is specified for a 404 page, then use that + // 772 : not redirecting file type Urls when requested. + bool permanentRedirect = false; + string redirectUrl = null; + string cleanPath = null; + bool doRedirect = false; + switch (tab.TabType) { - useDNNTab = true; - errTabId = settings.TabId404; - } + 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"); - if (!string.IsNullOrEmpty(settings.Regex404)) + // 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; + } + } - // with 404 errors, there's an option to catch certain urls and use an external url for extra processing. - { - try - { - // 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)) + if (redirectUrl != null) { - requestedUrl = result.OriginalPath; + doRedirect = true; } - if (Regex.IsMatch(requestedUrl, settings.Regex404, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + break; + case TabType.Url: + result.Reason = RedirectReason.Tab_External_Url; + redirectUrl = tab.Url; + if (redirectUrl != null) { - useDNNTab = false; - - // if we have a match in the 404 regex value, then don't use the tabid + 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; + } } - } - 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); - } - } - errUrl = settings.Url404; - errRH = "X-UrlRewriter-404"; - errRV = "404 Rewritten to {0} : {1} : Reason {2}"; - status = "404 Not Found"; - statusCode = 404; - } + break; + case TabType.Tab: + // if a tabType.tab is specified, it's either an external url or a permanent redirect - // check for 404 logging - if (result == null || result.Action == ActionType.Output404) - { - // Log 404 errors to Event Log - UrlRewriterUtils.Log404(request, settings, result); - } + // 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); - // 912 : use unhandled 404 switch - string reason404 = null; - bool unhandled404 = true; - if (useDNNTab && errTabId > -1) - { - unhandled404 = false; // we're handling it here - TabInfo errTab = TabController.Instance.GetTab(errTabId, result.PortalId, true); - if (errTab != null) - { - bool redirect = false; - - // 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) - { - reason = result.Reason.ToString(); - } - - response.AppendHeader(errRH, string.Format(errRV, "DNN Tab", - errTab.TabName + "(Tabid:" + errTabId.ToString() + ")", - reason)); - - // show debug messages even if in debug mode - if (context != null && response != null && result != null && showDebug) - { - ShowDebugData(context, result.OriginalPath, result, null); - } - - if (!isPostback) - { - response.ClearContent(); - response.StatusCode = statusCode; - response.Status = status; - } - else - { - redirect = true; - - // redirect postbacks as you can't postback successfully to a server.transfer - } - - errUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(errTab.TabID, string.Empty); + // 727 prevent redirectLoop with do301 in querystring + if (result.Action == ActionType.Redirect301 || + result.Action == ActionType.Redirect302) + { + cleanPath = RedirectTokens.RemoveAnyRedirectTokens( + cleanPath, + request.QueryString); + } - // have to update the portal settings with the new tabid - PortalSettings ps = null; - if (context != null && context.Items != null) - { - if (context.Items.Contains("PortalSettings")) - { - ps = (PortalSettings)context.Items["PortalSettings"]; - context.Items.Remove("PortalSettings"); // nix it from the context + // 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); } - } - if (ps != null && ps.PortalAlias != null) - { - ps = new PortalSettings(errTabId, ps.PortalAlias); - } - else - { - if (result.HttpAlias != null && result.PortalId > -1) + // check to make sure there isn't a blank redirect Url + if (redirectUrl == null) { - PortalAliasInfo pa = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias, result.PortalId); - ps = new PortalSettings(errTabId, pa); + // 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 { - // 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 there was a redirect Url, set the redirect action and set the type of redirect going to use + doRedirect = true; + if (permanentRedirect) { - // 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; + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_Permanent_Redirect; - // 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) + // should be already set, anyway + result.RewritePath = cleanPath; + } + else + { + // not a permanent redirect, check if the page forwarding is set + if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect301) { - if (useFor404 == null) - { - useFor404 = pa; // first one by default - } - - // matching? - if (chosen != null && chosen.Count > 0) - { - if (chosen.Contains(pa.HTTPAlias)) - { - useFor404 = pa; - } - } - else - { - break; // no further checking - } + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Tab_External_Url; } - - // now configure that as the portal settings - if (useFor404 != null) + else if (settings.ForwardExternalUrlsType == DNNPageForwardType.Redirect302) { - // create portal settings context for identified portal alias in single portal install - ps = new PortalSettings(errTabId, useFor404); + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Tab_External_Url; } } - else + } + + 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) { - reason404 = "Requested domain name is not configured as valid website"; - unhandled404 = true; + // 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); } } - } - if (ps != null) - { - // re-add the context items portal settings back in - context.Items.Add("PortalSettings", ps); - } + break; + } - if (redirect) + // do the redirect we have specified + if (doRedirect && + (result.Action == ActionType.Redirect301 || result.Action == ActionType.Redirect302)) + { + result.FinalUrl = redirectUrl; + if (result.Action == ActionType.Redirect301) { - 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 + 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); + } } else { - if (transfer) + if (result.Action == ActionType.Redirect302) { - // execute a server transfer to the default.aspx?tabid=xx url - // 767 : object not set error on extensionless 404 errors - if (context.User == null) + if (response != null) { - context.User = GetCurrentPrincipal(context); + // 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); } - - 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; } } + + 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 + // level try/catch block, so we handle it here. + } - // 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)) - { - 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); - } + return finished; + } - response.StatusCode = statusCode; - response.Status = status; - server.Transfer("~/" + errUrl, true); - } - else - { - errorPageHtml.Write(status + "
    The requested Url does not return any valid content."); - if (reason404 != null) - { - errorPageHtml.Write(status + "
    " + reason404); - } + /// + /// Redirects an alias if that is allowed by the settings. + /// + /// + /// + /// + /// + private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) + { + bool redirected = false; - 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) - { - reason = result.Reason.ToString(); - } - - if (!string.IsNullOrEmpty(errRH) && !string.IsNullOrEmpty(reason)) - { - response.AppendHeader(errRH, reason); - } - - response.StatusCode = statusCode; - response.Status = status; - } - } + // 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 { - // 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; - } - } + redirected = ConfigurePortalAliasRedirect(ref result, result.HttpAlias, httpAlias, false, settings.InternalAliasList, settings); } + } - if (ex != null) - { - if (context != null) - { - if (context.Items.Contains("UrlRewrite:Exception") == false) - { - context.Items.Add("UrlRewrite:Exception", ex.Message); - context.Items.Add("UrlRewrite:StackTrace", ex.StackTrace); - } - } + return redirected; + } - 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.
    "); - } - } - } - } + private static bool ConfigurePortalAliasRedirect( + ref UrlAction result, + string wrongAlias, + string rightAlias, + bool ignoreCustomAliasTabs, + List internalAliases, + FriendlyUrlSettings settings) + { + return ConfigurePortalAliasRedirect( + ref result, + wrongAlias, + rightAlias, + ignoreCustomAliasTabs, + RedirectReason.Wrong_Portal_Alias, + internalAliases, + settings); + } - string errorPageHtmlBody = errorPageHtml.ToString(); - if (errorPageHtmlBody.Length > 0) + /// + /// Checks to see whether the specified alias is a customTabAlias. + /// + /// + /// + /// + /// + private static bool CheckIfAliasIsCustomTabAlias(ref UrlAction result, string httpAlias, FriendlyUrlSettings settings) + { + List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); + bool isACustomTabAlias = false; + if (customAliasesForTabs != null && customAliasesForTabs.Count > 0) + { + // remove any customAliases that are also primary aliases. + foreach (var cpa in PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId)) { - response.Write(errorPageHtmlHeader); - response.Write(errorPageHtmlBody); - response.Write(errorPageHtmlFooter); + if (cpa.IsPrimary == true && customAliasesForTabs.Contains(cpa.HTTPAlias)) + { + customAliasesForTabs.Remove(cpa.HTTPAlias); + } } - if (ex != null) - { - UrlRewriterUtils.LogExceptionInRequest(ex, status, result); - } + isACustomTabAlias = customAliasesForTabs.Contains(httpAlias.ToLowerInvariant()); } + + return isACustomTabAlias; } - private static IPrincipal GetCurrentPrincipal(HttpContext context) + /// + /// Checks to see whether the specified alias is a customTabAlias for the TabId in result + /// + /// + /// + /// + /// + private static bool CheckIfAliasIsCurrentTabCustomTabAlias(ref UrlAction result, FriendlyUrlSettings settings) { - // Extract the forms authentication cookie - var authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; - var currentPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty), new string[0]); - - try + var customAliasesForTab = TabController.Instance.GetCustomAliases(result.TabId, result.PortalId); + bool isCurrentTabCustomTabAlias = false; + if (customAliasesForTab != null && customAliasesForTab.Count > 0) { - if (authCookie != null) + //see if we have a customAlias for the current CultureCode + if (customAliasesForTab.ContainsKey(result.CultureCode)) { - var authTicket = FormsAuthentication.Decrypt(authCookie.Value); - if (authTicket != null && !authTicket.Expired) + //if it is for the current culture, we need to know if it's a primary alias + var tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(customAliasesForTab[result.CultureCode]); + if (tabPortalAlias != null && !tabPortalAlias.IsPrimary) { - var roles = authTicket.UserData.Split('|'); - var id = new FormsIdentity(authTicket); - currentPrincipal = new GenericPrincipal(id, roles); + // it's not a primary alias, so must be a custom tab alias + isCurrentTabCustomTabAlias = true; } } } - catch (Exception) + // if it's not a custom alias for the current tab, we'll need to change the result + if (!isCurrentTabCustomTabAlias) { - // do nothing here. + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Wrong_Portal_Alias; } - - return currentPrincipal; + return isCurrentTabCustomTabAlias; } - private static bool CheckForDebug(HttpRequest request, NameValueCollection queryStringCol, bool debugEnabled) + /// + /// Configures the result object to set the correct Alias redirect + /// parameters and destination URL. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static bool ConfigurePortalAliasRedirect( + ref UrlAction result, + string wrongAlias, + string rightAlias, + bool ignoreCustomAliasTabs, + RedirectReason redirectReason, + List internalAliases, + FriendlyUrlSettings settings) { - string debugValue = string.Empty; - bool retVal = false; - - if (debugEnabled) + // wrong alias for the portal + // check to see if the wrong portal alias could be a custom alias for a tab + bool doRedirect; + if (ignoreCustomAliasTabs == false) // check out custom alias tabs collection { - const string debugToken = "_aumdebug"; - if (queryStringCol != null && queryStringCol[debugToken] != null) + // if an alias is a custom tab alias for a specific tab, then don't redirect + // if we have the TabId, we'll need to check if the alias is valid for the current tab + if (result.TabId > 0 && CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) { - debugValue = queryStringCol[debugToken]; + doRedirect = false; + } + else if (result.TabId < 0 && CheckIfAliasIsCustomTabAlias(ref result, wrongAlias, settings)) + { + doRedirect = false; } else { - if (request != null) - { - debugValue = request.Params.Get("HTTP_" + debugToken.ToUpper()); - } - - if (debugValue == null) - { - debugValue = "false"; - } + doRedirect = true; } } - - switch (debugValue.ToLowerInvariant()) + else { - case "true": - retVal = true; - break; + doRedirect = true; // do redirect, ignore custom alias entries for tabs } - return retVal; - } - - private static bool CheckForTabExternalForwardOrRedirect( - HttpContext context, - ref UrlAction result, - HttpResponse response, - FriendlyUrlSettings settings, - Guid parentTraceId) - { - bool finished = false; - HttpRequest request = null; - if (context != null) + // check to see if it is an internal alias. These are used to block redirects + // to allow for reverse proxy requests, which must change the rewritten alias + // while leaving the requested alias + bool internalAliasFound = false; + if (doRedirect && internalAliases != null && internalAliases.Count > 0) { - request = context.Request; + if (internalAliases.Any(ia => string.Compare(ia.HttpAlias, wrongAlias, StringComparison.OrdinalIgnoreCase) == 0)) + { + internalAliasFound = true; + doRedirect = false; + } } - 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)) + // if still need to do redirect, then set the settings that will cause the redirect (redirect not done here) + if (doRedirect) { - bool allowRedirect = !(result.RewritePath != null && result.RewritePath.ToLowerInvariant().Contains("&ctl=tab")); + result.Action = ActionType.Redirect301; + result.Reason = redirectReason; + var destUrl = result.OriginalPath; + if (result.OriginalPath.Contains(wrongAlias)) + { + destUrl = result.OriginalPath.Replace(wrongAlias, rightAlias); + } + else if (result.OriginalPath.ToLowerInvariant().Contains(wrongAlias)) + { + destUrl = result.OriginalPath.ToLowerInvariant().Replace(wrongAlias, rightAlias); + } - // 594 : do not redirect settings pages for external urls - if (allowRedirect) + if (redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture || + redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) { - TabInfo tab; - allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, false, out tab, settings); - 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) - { - 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"); + destUrl = destUrl.Replace("/language/" + result.CultureCode, string.Empty); + } - // 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; - } - } + destUrl = CheckForSiteRootRedirect(rightAlias, destUrl); + result.FinalUrl = destUrl; + } + else + { + // 838 : don't overwrite the reason if already have checkfor301 + // and don't do a check on the basis that an internal alias was found + if (result.Action != ActionType.CheckFor301 && internalAliasFound == false) + { + // set status to 'check for redirect' + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Custom_Tab_Alias; + } + } - if (redirectUrl != null) - { - doRedirect = true; - } + return doRedirect; + } - break; - case TabType.Url: - result.Reason = RedirectReason.Tab_External_Url; - redirectUrl = tab.Url; - if (redirectUrl != null) - { - 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; - } - } + private static string MakeUrlWithAlias(Uri requestUri, string httpAlias) + { + return requestUri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) + ? "https://" + httpAlias.Replace("*.", string.Empty) + "/" + : "http://" + httpAlias.Replace("*.", string.Empty) + "/"; + } - break; - case TabType.Tab: - // if a tabType.tab is specified, it's either an external url or a permanent redirect + private static string MakeUrlWithAlias(Uri requestUri, PortalAliasInfo alias) + { + return MakeUrlWithAlias(requestUri, alias.HTTPAlias); + } - // 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); + /// + /// Determines if this is a request from an install / upgrade url. + /// + /// + /// + /// + /// + /// + /// + /// //875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1. + /// + private static bool IgnoreRequestForInstall(string physicalPath, string refererPath, string requestedDomain, string refererDomain) + { + if (physicalPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) + || physicalPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) + || physicalPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture) + || Globals.Status == Globals.UpgradeStatus.Install + || Globals.Status == Globals.UpgradeStatus.Upgrade) + { + return true; + } - // 727 prevent redirectLoop with do301 in querystring - if (result.Action == ActionType.Redirect301 || - result.Action == ActionType.Redirect302) - { - cleanPath = RedirectTokens.RemoveAnyRedirectTokens( - cleanPath, - request.QueryString); - } + // 954 : DNN 7.0 compatibility + // check for /default.aspx which is default Url launched from the Upgrade/Install wizard page + // 961 : check domain as well as path for the referer + if (physicalPath.EndsWith(Globals.glbDefaultPage, true, CultureInfo.InvariantCulture) == false + && refererPath != null + && string.Compare(requestedDomain, refererDomain, StringComparison.OrdinalIgnoreCase) == 0 + && (refererPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) + || refererPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) + || refererPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture))) + { + return true; + } - // 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); - } + return false; + } - // 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; + private static bool IgnoreRequestForWebServer(string requestedPath) + { + // Should standardize comparison methods + if (requestedPath.IndexOf("synchronizecache.aspx", StringComparison.OrdinalIgnoreCase) > 1 + || requestedPath.EndsWith("keepalive.aspx", StringComparison.OrdinalIgnoreCase)) + { + return true; + } - // should be already set, anyway - result.RewritePath = cleanPath; - } - else - { - // 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; - } - } - } + // Get the root + var rootPath = requestedPath.Substring(0, requestedPath.LastIndexOf("/", StringComparison.Ordinal)); + rootPath = rootPath.Substring(rootPath.IndexOf("://", StringComparison.Ordinal) + 3); - 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) - { - // 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); - } - } + // Check if this is a WebServer and not a portalalias. + // if can auto add portal alias enabled, then return false, alias will add later. + var alias = PortalAliasController.Instance.GetPortalAlias(rootPath); + if (alias != null || CanAutoAddPortalAlias()) + { + return false; + } - break; - } + // Check if this is a WebServer + var server = ServerController.GetEnabledServers().SingleOrDefault(s => s.Url == rootPath); + if (server != null) + { + return true; + } - // 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); - } - } - 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); - } - } - } + return false; + } - finished = true; - } - } + private static bool IgnoreRequestForInstall(HttpRequest request) + { + try + { + string physicalPath = request.PhysicalPath; + string requestedDomain = request.Url.Host; + string refererPath = null, refererDomain = null; + if (request.UrlReferrer != null) + { + refererDomain = request.UrlReferrer.Host; + refererPath = request.UrlReferrer.LocalPath; } + + return IgnoreRequestForInstall(physicalPath, refererPath, requestedDomain, refererDomain); } + catch (PathTooLongException) + { + // catch and handle this exception, caused by an excessively long file path based on the + // mapped virtual url + return false; } - catch (ThreadAbortException) + catch (ArgumentException) { - // 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. + // catch and handle this exception, caused by an invalid character in the file path based on the + // mapped virtual url + return false; } - - return finished; } - private bool CheckForSecureRedirect( - PortalSettings portalSettings, - Uri requestUri, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings) + private static bool IgnoreRequest(UrlAction result, string requestedPath, string ignoreRegex, HttpRequest request) { - bool redirectSecure = false; - string url = requestUri.ToString(); - - // 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) + bool retVal = false; - // no secure redirection for physical resources, only tab-specific requests can be redirected for ssl connections + // check if we are upgrading/installing + // 829 : use result physical path instead of requset physical path + // 875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1 + if (request != null && (IgnoreRequestForInstall(request) || IgnoreRequestForWebServer(requestedPath))) { - if (portalSettings.ActiveTab != null) + // ignore all install requests + retVal = true; + } + else if (request != null && request.Path.EndsWith("imagechallenge.captcha.aspx", StringComparison.InvariantCultureIgnoreCase)) + { + retVal = true; + } + else + { + try { - result.DebugMessages.Add("ActiveTab: " + portalSettings.ActiveTab.TabID.ToString() + "/" + - portalSettings.ActiveTab.TabName + " IsSecure: " + - portalSettings.ActiveTab.IsSecure.ToString()); - - // check ssl enabled - if (portalSettings.SSLEnabled) - { - // 717 : check page is secure, connection is not secure - // 952 : support SSl Offloading in DNN 6.2+ - if (portalSettings.ActiveTab.IsSecure && !result.IsSecureConnection && !result.IsSSLOffloaded) - { - redirectSecure = true; - string stdUrl = portalSettings.STDURL; - 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) + if (ignoreRegex.Length > 0) { - // 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)) + if (Regex.IsMatch(requestedPath, ignoreRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { - // 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; - } + retVal = true; } } } - - if (redirectSecure) + catch (Exception ex) { - // 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; - } + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + result.Ex = ex; } } - return redirectSecure; + return retVal; } - private string ReplaceDomainName(string url, string replaceDomain, string withDomain) + private static void CheckForRewrite( + string fullUrl, + string querystring, + UrlAction result, + bool useFriendlyUrls, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + out bool isPhysicalResource, + Guid parentTraceId) { - if (replaceDomain != string.Empty && withDomain != string.Empty) + bool checkForRewrites; + + // just check to make sure it isn't a physical resource on the server + RewriteController.IdentifyByPhysicalResource( + result.PhysicalPath, + fullUrl, + queryStringCol, + ref result, + useFriendlyUrls, + settings, + out isPhysicalResource, + out checkForRewrites, + parentTraceId); + + if (checkForRewrites && RewriteController.CanRewriteRequest(result, fullUrl, settings)) { - // 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) + bool doSiteUrlProcessing = false; + + // 728 new regex expression to pass values straight onto the siteurls.config file + if (!string.IsNullOrEmpty(settings.UseSiteUrlsRegex)) { - string replaceFind = @"(?<=https?://)" + Regex.Escape(replaceDomain); - url = Regex.Replace(url, replaceFind, withDomain, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + doSiteUrlProcessing = Regex.IsMatch(fullUrl, settings.UseSiteUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } - } - return url; + if (!doSiteUrlProcessing) + + // 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); + if (!doRewrite) + { + doSiteUrlProcessing = true; + } + } + + if (doSiteUrlProcessing) + { + // 728 : compare requests against the siteurls.config file, either if no other match was found, or if we want to skip the rest of the processing + // the standard DNN way of rewriting, using expressions found in the siteurls.config file + RewriteController.IdentifyByRegEx(fullUrl, querystring, result.ApplicationPath, ref result, settings, parentTraceId); + } + } } - protected bool IsPortalAliasIncorrect( - HttpContext context, - HttpRequest request, + private static bool CheckForRedirects( Uri requestUri, - UrlAction result, + string fullUrl, NameValueCollection queryStringCol, + UrlAction result, + string requestType, FriendlyUrlSettings settings, - Guid parentTraceId, - out string httpAlias) + int portalHomeTabId) { - // 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 + bool redirected = false; + if (queryStringCol["error"] == null && queryStringCol["message"] == null && requestType != "POST") { - var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (queryStringCol != null && queryStringCol["forceAlias"] != "true") + // if the / is missing from an extension-less request, then check for a 301 redirect + if (settings.PageExtensionUsageType == PageExtensionUsageType.Never) { - if (portalAliases.Count > 0) + // 575 check on absolutePath instead of absoluteUri : this ignores query strings and fragments like # + // 610 don't always end with '/' - reverses previous setting + // 687 don't double-check 301 redirects. 'CheckFor301' is less concise than 'Redirect301' + // DNN-21906: if the redirect is for splash page, then we should continue the 302 redirect. + if (requestUri.AbsolutePath.EndsWith("/") && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) { - 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); + result.Action = ActionType.CheckFor301; + } + } - if (cpa != null) - { - httpAlias = cpa.HTTPAlias; - continueLoop = false; - } + if (settings.RedirectWrongCase && result.Action == ActionType.Continue) + { + result.Action = ActionType.CheckFor301; + } - 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); + string scheme = requestUri.Scheme + Uri.SchemeDelimiter; + bool queryStringHas301Parm = queryStringCol["do301"] != null; - // 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; - } - } - } - } + // 727 : keep a bool value if there is a do301 request in the querystring + // check for a 301 request in the query string, or an explicit 301 or 302 request + // 2.0 - check for explicit do301=true instead of just do301 key + string do301Val = queryStringCol["do301"]; + if (result.TabId > -1 // valid tab + && (result.Action == ActionType.Redirect301 // specific 301 redirect + || (do301Val != null && do301Val == "true") // or rewrite hint for specific 301 redirect + || result.Action == ActionType.Redirect302)) // or specific 302 redirect + { + // we have ordered a 301 redirect earlier in the code + // get the url for redirection by re-submitting the path into the Friendly Url Provider + string pathOnly = RewriteController.GetRewriteOrRequestedPath(result, requestUri); - // check whether to still go on or not - if (continueLoop) + // 727 prevent redirectLoop with do301 in querystring + if (result.Action == ActionType.Redirect301 || queryStringHas301Parm || result.Action == ActionType.Redirect302) + { + pathOnly = RedirectTokens.RemoveAnyRedirectTokens(pathOnly, queryStringCol); + } + + // check for exclusion by regex for this url + if (result.RedirectAllowed) + { + // get the tab so we know where to go + TabInfo tab; + bool checkRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + + if (checkRedirect) + { + if ((result.Reason == RedirectReason.Deleted_Page || result.Reason == RedirectReason.Disabled_Page) + && portalHomeTabId > 0 + && settings.DeletedTabHandlingType == DeletedTabHandlingType.Do301RedirectToPortalHome) { - // 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) + // redirecting to home page + TabInfo homeTab = TabController.Instance.GetTab(portalHomeTabId, result.PortalId, false); + if (homeTab != null) { - triedWWW = true; // now tried adding/removing www - if (checkAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) - { - checkAlias = checkAlias.Substring(4); - } - else - { - checkAlias = "www." + checkAlias; - } + string homePageUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + homeTab, + pathOnly, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + result.Action = ActionType.Redirect301; + result.FinalUrl = homePageUrl; + result.RewritePath = pathOnly; + redirected = true; } - else + } + else + { + // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider + string cleanPath = RewriteController.GetRewriteOrRequestedPath(result, requestUri); + + // 727 prevent redirectLoop with do301 in querystring + // also check for existing in path of do301 token + if (result.Action == ActionType.Redirect301 || do301Val != null || result.Action == ActionType.Redirect302) { - // 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; + cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, queryStringCol); + } - // 735 : switch to custom method for getting portal - PortalInfo pi = CacheController.GetPortal(result.PortalId, false); - if (pi != null) + // get best friendly url from friendly url provider + string bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + + // get what the friendly Url for this tab should be and stick it in as the redirect + // 727 : using boolean because we wanted to get rid of the do301 before calculating the correct url + if (queryStringHas301Parm) + { + result.Action = ActionType.Redirect301; + if (result.Reason == RedirectReason.Not_Redirected) { - string cultureCode = pi.DefaultLanguage; - if (!string.IsNullOrEmpty(cultureCode)) - { - var primaryPortalAlias = portalAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, cultureCode, settings); - if (primaryPortalAlias != null) - { - httpAlias = primaryPortalAlias.HTTPAlias; - } - } + result.Reason = RedirectReason.Unfriendly_Url_1; } } + + result.FinalUrl = bestFriendlyUrl; + result.RewritePath = pathOnly; + redirected = true; // mark as redirected } } - } - - // 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) + else { - incorrectAlias = true; + // redirect disallowed + // 618: dont' clear if 302 redirect selected + if (result.Action != ActionType.Redirect302Now || result.Action != ActionType.Redirect302) + { + RedirectController.CancelRedirect(ref result, null, settings, "Redirect requested but cancelled because disallowed"); + } } + } } - } + else if (result.TabId > -1 && result.RedirectAllowed && result.Action == ActionType.CheckFor301) + { + // 301 check was requested in earlier processing + // get the tab controller and retrieve the tab the request is for + // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab + if (settings.RedirectUnfriendly) + { + TabInfo tab; + bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + if (allowRedirect && tab != null) + { + // remove the http alias from the url. Do this by putting the url back together from the request and removing the alias + string rewritePathOnly; + if (result.DoRewrite) + { + rewritePathOnly = result.RewritePath; + var pos = rewritePathOnly.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase); + if (pos > Null.NullInteger) + { + rewritePathOnly = rewritePathOnly.Substring(pos); + } + } + else + { + rewritePathOnly = requestUri.Host + requestUri.PathAndQuery; + } - return incorrectAlias; - } + // remove the http alias from the path + var pathAliasEnd = rewritePathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase); + var queryStringIndex = rewritePathOnly.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); + if (pathAliasEnd > Null.NullInteger && (queryStringIndex == Null.NullInteger || pathAliasEnd < queryStringIndex)) + { + rewritePathOnly = rewritePathOnly.Substring(pathAliasEnd + result.PortalAlias.HTTPAlias.Length); + } - /// - /// Redirects an alias if that is allowed by the settings. - /// - /// - /// - /// - /// - private static bool RedirectPortalAlias(string httpAlias, ref UrlAction result, FriendlyUrlSettings settings) - { - bool redirected = false; + // now check to see if need to remove /default.aspx from the end of the requested Url + string requestedUrl = fullUrl; + int requestedUrlAliasEnd = requestedUrl.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) + + (result.PortalAlias.HTTPAlias + "/").Length; + if (requestedUrlAliasEnd > Null.NullInteger) + { + // 818 : when a site root is used for a custom page Url, then check for max length within bounds + if ((requestedUrl.Length - requestedUrlAliasEnd) >= 12 && requestedUrl.Substring(requestedUrlAliasEnd).Equals("default.aspx", StringComparison.InvariantCultureIgnoreCase)) + { + requestedUrl = requestedUrl.Substring(0, requestedUrl.Length - 12); - // 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); - } - } + // 12 = default.aspx length + } + } - return redirected; - } + // what happens here is that the request is reverse-engineered to see if it matches what the friendly Url shoudl have been + // get what the friendly Url for this tab should be + string bestFriendlyUrl; - private static bool ConfigurePortalAliasRedirect( - ref UrlAction result, - string wrongAlias, - string rightAlias, - bool ignoreCustomAliasTabs, - List internalAliases, - FriendlyUrlSettings settings) - { - return ConfigurePortalAliasRedirect( - ref result, - wrongAlias, - rightAlias, - ignoreCustomAliasTabs, - RedirectReason.Wrong_Portal_Alias, - internalAliases, - settings); - } + // 819 : leaving /do301/check in Url because not using cleanPath to remove from + string cleanPath = RedirectTokens.RemoveAnyRedirectTokensAndReasons(rewritePathOnly); - /// - /// Checks to see whether the specified alias is a customTabAlias. - /// - /// - /// - /// - /// - private static bool CheckIfAliasIsCustomTabAlias(ref UrlAction result, string httpAlias, FriendlyUrlSettings settings) - { - List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); - bool isACustomTabAlias = false; - if (customAliasesForTabs != null && customAliasesForTabs.Count > 0) - { - // remove any customAliases that are also primary aliases. - foreach (var cpa in PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId)) + // string cleanPath = rewritePathOnly.Replace("&do301=check","");//remove check parameter if it exists + // cleanPath = cleanPath.Replace("&do301=true", "");//don't pass through internal redirect check parameter + cleanPath = cleanPath.Replace("&_aumdebug=true", string.Empty); // remove debug parameter if it exists + + Match match = RewritePathRx.Match(rewritePathOnly ?? string.Empty); + if (match.Success) + { + // when the pathOnly value ends with '=' it means there is a query string pair with a key and no value + // make the assumption that this was passed in as a page name OTHER than default page + string pageName = match.Groups["parm"].Value; // get the last parameter in the list + + cleanPath = cleanPath.Replace(match.Value, string.Empty); + + // remove the last parameter from the path + + // generate teh friendly URl name with the last parameter as the page name, not a query string parameter + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + pageName + settings.PageExtension, + result.HttpAlias, + false, + settings, + Guid.Empty); + } + else + { + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + cleanPath, + Globals.glbDefaultPage, + result.HttpAlias, + false, + settings, + Guid.Empty); + } + + // if the incoming request doesn't match the 'most friendly' url, a 301 Moved Permanently status is returned, along with the friendly url + // check the bestFriendlyUrl against either the url, or rawUrl (with and without host) + // in each case, the aumdebug parameter will be searched for and replaced + var urlDecode = HttpUtility.UrlDecode(requestedUrl); + if (urlDecode != null) + { + string rawUrlWithHost = StripDebugParameter(urlDecode.ToLowerInvariant()); + + // string rawUrlWithHost = StripDebugParameter(System.Web.HttpUtility.UrlDecode(scheme + requestUri.Host + requestUri.PathAndQuery).ToLowerInvariant()); + string rawUrlWithHostNoScheme = StripDebugParameter(rawUrlWithHost.Replace(scheme, string.Empty)); + string bestFriendlyNoScheme = StripDebugParameter(bestFriendlyUrl.ToLowerInvariant().Replace(scheme, string.Empty)); + string requestedPathNoScheme = StripDebugParameter(requestUri.AbsoluteUri.Replace(scheme, string.Empty).ToLowerInvariant()); + string rawUrlLowerCase = StripDebugParameter(requestUri.AbsoluteUri.ToLowerInvariant()); + + // check to see if just an alias redirect of an internal alias + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + + if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0 && primaryAliases.Count > 0) + { + var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result); + if (cpa != null) + { + string chosenAlias = cpa.HTTPAlias.ToLowerInvariant(); + foreach (InternalAlias ia in settings.InternalAliasList) + { + string internalAlias = ia.HttpAlias.ToLowerInvariant(); + if (requestedPathNoScheme.Contains(internalAlias)) + { + // an internal alias has been used. + // replace this in the comparison charts to do a 'fair' comparison + requestedPathNoScheme = requestedPathNoScheme.Replace(internalAlias, chosenAlias); + rawUrlWithHost = rawUrlWithHost.Replace(scheme + internalAlias, scheme + chosenAlias); + rawUrlWithHostNoScheme = rawUrlWithHostNoScheme.Replace(internalAlias, chosenAlias); + rawUrlLowerCase = rawUrlLowerCase.Replace(internalAlias, chosenAlias); + break; + } + } + } + } + + // DNN-9158: prevent SSL Offloading infinite redirects + if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https")) + { + bestFriendlyNoScheme = $"http://{bestFriendlyNoScheme.Substring(8)}"; + } + + if (!(bestFriendlyNoScheme == requestedPathNoScheme + || bestFriendlyNoScheme == rawUrlWithHost + || bestFriendlyNoScheme == rawUrlWithHostNoScheme + || bestFriendlyNoScheme == HttpUtility.UrlDecode(requestedPathNoScheme) + || HttpUtility.UrlDecode(bestFriendlyNoScheme) == HttpUtility.UrlDecode(requestedPathNoScheme) + || bestFriendlyNoScheme == rawUrlLowerCase)) + { + redirected = true; + result.Action = ActionType.Redirect301; + result.FinalUrl = bestFriendlyUrl; + if (result.Reason != RedirectReason.Custom_Tab_Alias && + result.Reason != RedirectReason.Deleted_Page && + result.Reason != RedirectReason.Disabled_Page) + { + result.Reason = RedirectReason.Unfriendly_Url_2; + } + + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + requestedPathNoScheme + " [requested with no scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHost + " [requested with host and scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHostNoScheme + " [requested with host, no scheme]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + HttpUtility.UrlDecode(requestedPathNoScheme) + " [requested and decoded]"); + result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlLowerCase + " [requested raw Url]"); + } + } + } + } + } + + if (result.RedirectAllowed && settings.RedirectWrongCase) { - if (cpa.IsPrimary == true && customAliasesForTabs.Contains(cpa.HTTPAlias)) + // check for redirects where a redirectToSubDomain is specified, + // redirect for Wrong case is specified, and there is a valid tab and it's not already redirected somewhere else + bool doRedirect = false; + string redirectPath = redirected ? result.FinalUrl : requestUri.AbsoluteUri; + string redirectPathOnly = redirectPath; + if (redirectPathOnly.Contains("?")) { - customAliasesForTabs.Remove(cpa.HTTPAlias); + redirectPathOnly = redirectPathOnly.Substring(0, redirectPathOnly.IndexOf("?", StringComparison.Ordinal)); } - } - isACustomTabAlias = customAliasesForTabs.Contains(httpAlias.ToLowerInvariant()); - } + // Thanks Etienne for the fix for Diacritic Characters Terminal Loop! + // if the url contains url encoded characters, they appear here uppercase -> %C3%83%C2 + // decode the url to get back the original character and do proper casing comparison + string urlDecodedRedirectPath = HttpUtility.UrlDecode(redirectPathOnly); - return isACustomTabAlias; - } + // check for wrong case redirection + if (urlDecodedRedirectPath != null && (settings.RedirectWrongCase && string.CompareOrdinal(urlDecodedRedirectPath, urlDecodedRedirectPath.ToLowerInvariant()) != 0)) + { + TabInfo tab; + bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); - /// - /// Checks to see whether the specified alias is a customTabAlias for the TabId in result - /// - /// - /// - /// - /// - private static bool CheckIfAliasIsCurrentTabCustomTabAlias(ref UrlAction result, FriendlyUrlSettings settings) - { - var customAliasesForTab = TabController.Instance.GetCustomAliases(result.TabId, result.PortalId); - bool isCurrentTabCustomTabAlias = false; - if (customAliasesForTab != null && customAliasesForTab.Count > 0) - { - //see if we have a customAlias for the current CultureCode - if (customAliasesForTab.ContainsKey(result.CultureCode)) - { - //if it is for the current culture, we need to know if it's a primary alias - var tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(customAliasesForTab[result.CultureCode]); - if (tabPortalAlias != null && !tabPortalAlias.IsPrimary) + if (allowRedirect && !string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) + { + // don't allow redirect if excluded from redirecting in the force lower case regex pattern (606) + allowRedirect = !Regex.IsMatch(redirectPath, settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } + + if (allowRedirect) + { + // special case : when IIS automatically places /default.aspx on the end of the string, + // then don't try and redirect to the lower case /default.aspx, just let it through. + // we don't know whether IIS appended /Default.aspx on the end, however, we can guess + // if the redirectDefault.aspx is turned on (511) + if (settings.RedirectDefaultPage == false && redirectPathOnly.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + // ignore this, because it's just a redirect of the /Default.aspx to /default.aspx + } + else + { + redirectPath = redirectPath.Replace(redirectPathOnly, redirectPathOnly.ToLowerInvariant()); + doRedirect = true; + result.Reason = RedirectReason.Not_Lower_Case; + } + } + } + + if (doRedirect) { - // it's not a primary alias, so must be a custom tab alias - isCurrentTabCustomTabAlias = true; + result.Action = ActionType.Redirect301; + result.FinalUrl = CheckForSiteRootRedirect(result.PortalAlias.HTTPAlias, redirectPath); + redirected = true; } } } - // if it's not a custom alias for the current tab, we'll need to change the result - if (!isCurrentTabCustomTabAlias) - { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Wrong_Portal_Alias; - } - return isCurrentTabCustomTabAlias; + + return redirected; } - /// - /// Configures the result object to set the correct Alias redirect - /// parameters and destination URL. - /// - /// - /// - /// - /// - /// - /// - /// - /// - private static bool ConfigurePortalAliasRedirect( - ref UrlAction result, - string wrongAlias, - string rightAlias, - bool ignoreCustomAliasTabs, - RedirectReason redirectReason, - List internalAliases, - FriendlyUrlSettings settings) + + private static string StripDebugParameter(string url) { - // wrong alias for the portal - // check to see if the wrong portal alias could be a custom alias for a tab - bool doRedirect; - if (ignoreCustomAliasTabs == false) // check out custom alias tabs collection + return AumDebugRegex.Replace(url, string.Empty); + } + + private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool checkBaseUrls, out TabInfo tab, FriendlyUrlSettings settings) + { + bool doRedirect = false; + tab = TabController.Instance.GetTab(tabId, portalId, false); + + // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab + if (tab != null && tab.IsSuperTab == false && !tab.DoNotRedirect) { - // if an alias is a custom tab alias for a specific tab, then don't redirect - // if we have the TabId, we'll need to check if the alias is valid for the current tab - if (result.TabId > 0 && CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) - { - doRedirect = false; - } - else if (result.TabId < 0 && CheckIfAliasIsCustomTabAlias(ref result, wrongAlias, settings)) + if (checkBaseUrls) { - doRedirect = false; + // no redirect for friendly url purposes if the tab is in the 'base friendly urls' section + doRedirect = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true); } else { doRedirect = true; } } - else - { - doRedirect = true; // do redirect, ignore custom alias entries for tabs - } - // check to see if it is an internal alias. These are used to block redirects - // to allow for reverse proxy requests, which must change the rewritten alias - // while leaving the requested alias - bool internalAliasFound = false; - if (doRedirect && internalAliases != null && internalAliases.Count > 0) - { - if (internalAliases.Any(ia => string.Compare(ia.HttpAlias, wrongAlias, StringComparison.OrdinalIgnoreCase) == 0)) - { - internalAliasFound = true; - doRedirect = false; - } - } + return doRedirect; + } - // if still need to do redirect, then set the settings that will cause the redirect (redirect not done here) - if (doRedirect) + 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) { - result.Action = ActionType.Redirect301; - result.Reason = redirectReason; - var destUrl = result.OriginalPath; - if (result.OriginalPath.Contains(wrongAlias)) + var urlToMatch = requestUrl; + + // 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) { - destUrl = result.OriginalPath.Replace(wrongAlias, rightAlias); + continue; } - else if (result.OriginalPath.ToLowerInvariant().Contains(wrongAlias)) + else { - destUrl = result.OriginalPath.ToLowerInvariant().Replace(wrongAlias, rightAlias); - } + // 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) + { + // alias is in the query string, go to the next alias + continue; + } - if (redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture || - redirectReason == RedirectReason.Wrong_Portal_Alias_For_Culture_And_Browser) - { - destUrl = destUrl.Replace("/language/" + result.CultureCode, string.Empty); + // we are fine here, lets prepare URL to be validated in regex + urlToMatch = urlToMatch.ReplaceIgnoreCase(alias, "_ALIAS_"); } - destUrl = CheckForSiteRootRedirect(rightAlias, destUrl); - result.FinalUrl = destUrl; - } - else - { - // 838 : don't overwrite the reason if already have checkfor301 - // and don't do a check on the basis that an internal alias was found - if (result.Action != ActionType.CheckFor301 && internalAliasFound == 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) { - // set status to 'check for redirect' - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Custom_Tab_Alias; + // check for mobile browser and matching + var aliasEx = (PortalAliasInfo)portalAliases[alias]; + redirectAlias = aliasEx.Redirect; + if (redirectAlias) + { + wrongAlias = alias; + } + + isPrimaryAlias = aliasEx.IsPrimary; + aliasInfo = aliasEx; + break; } } - return doRedirect; + return aliasInfo; } - private void IdentifyPortalAlias( + private void ProcessRequest( HttpContext context, - HttpRequest request, - Uri requestUri, UrlAction result, - NameValueCollection queryStringCol, + Uri requestUri, + bool useFriendlyUrls, + UrlAction result, FriendlyUrlSettings settings, + bool allowSettingsChange, Guid parentTraceId) { - // get the domain name of the request, if it isn't already supplied - if (request != null && string.IsNullOrEmpty(result.DomainName)) - { - result.DomainName = Globals.GetDomainName(request); // parse the domain name out of the request - } + bool finished = false; + bool showDebug = false; + bool postRequest = false; - // get tabId from querystring ( this is mandatory for maintaining portal context for child portals ) - if (queryStringCol["tabid"] != null) + HttpRequest request = context.Request; + HttpResponse response = context.Response; + string requestType = request.RequestType; + NameValueCollection queryStringCol = request.QueryString; + + try { - string raw = queryStringCol["tabid"]; - int tabId; - if (int.TryParse(raw, out tabId)) - { - result.TabId = tabId; - } - else + string fullUrl, querystring; + + // 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); + + showDebug = CheckForDebug(request, queryStringCol, settings.AllowDebugCode); + string ignoreRegex = settings.IgnoreRegex; + bool ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + bool redirectAlias = false; + if (!ignoreRequest) { - // couldn't parse tab id - // split in two? - string[] tabids = raw.Split(','); - if (tabids.GetUpperBound(0) > 0) + // 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); + + // 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) { - // hmm more than one tabid - if (int.TryParse(tabids[0], out tabId)) + // 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) { - result.TabId = tabId; + settings = new FriendlyUrlSettings(requestedAlias.PortalID); + result.SetRedirectAllowed(result.OriginalPath, settings); + } - // but we want to warn against this! - var ex = - new Exception( - "Illegal request exception : Two TabId parameters provided in a single request: " + - requestUri); - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + result.PortalAlias = requestedAlias; + result.PrimaryAlias = requestedAlias; // this is the primary alias + result.PortalId = requestedAlias.PortalID; + result.CultureCode = requestedAlias.CultureCode; - result.Ex = ex; + // 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 { - // yeah, nothing, divert to 404 - result.Action = ActionType.Output404; - var ex = - new Exception( - "Illegal request exception : TabId parameters in query string, but invalid TabId requested : " + - requestUri); - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - result.Ex = ex; + // 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; + } + } } } } - } - // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) - if (queryStringCol["portalid"] != null) - { - string raw = queryStringCol["portalid"]; - int portalId; - if (int.TryParse(raw, out portalId)) + ignoreRegex = settings.IgnoreRegex; + ignoreRequest = IgnoreRequest(result, fullUrl, ignoreRegex, request); + if (!ignoreRequest) { - // 848 : if portal already found is different to portal id in querystring, then load up different alias - // this is so the portal settings will be loaded correctly. - if (result.PortalId != portalId) + // check to see if a post request + if (request.RequestType == "POST") { - // portal id different to what we expected - result.PortalId = portalId; + postRequest = true; + } - // check the loaded portal alias, because it might be wrong - if (result.PortalAlias != null && result.PortalAlias.PortalID != portalId) + // 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) { - // yes, the identified portal alias is wrong. Find the correct alias for this portal - PortalAliasInfo pa = TabIndexController.GetPortalAliasByPortal(portalId, result.DomainName); - if (pa != null) - { - // note: sets portal id and portal alias - result.PortalAlias = pa; - } + result.PrimaryAlias = primaryAlias; } + + // try and redirect the alias if the settings allow it + redirectAlias = RedirectPortalAlias(primaryHttpAlias, ref result, settings); } - } - } - else - { - // check for a portal alias if there's no portal Id in the query string - // check for absence of captcha value, because the captcha string re-uses the alias querystring value - if (queryStringCol["alias"] != null && queryStringCol["captcha"] == null) - { - string alias = queryStringCol["alias"]; - PortalAliasInfo portalAlias = PortalAliasController.Instance.GetPortalAlias(alias); - if (portalAlias != null) + + if (redirectAlias) { - // ok the portal alias was found by the alias name - // check if the alias contains the domain name - if (alias.Contains(result.DomainName) == false) - { - // replaced to the domain defined in the alias - if (request != null) - { - string redirectDomain = Globals.GetPortalDomainName(alias, request, 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; + } - // retVal.Url = redirectDomain; - result.FinalUrl = redirectDomain; - result.Action = ActionType.Redirect302Now; - result.Reason = RedirectReason.Alias_In_Url; - } + if (!finished) + { + // 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 { - // the alias is the same as the current domain - result.HttpAlias = portalAlias.HTTPAlias; - result.PortalAlias = portalAlias; - result.PortalId = portalAlias.PortalID; + bool isPhysicalResource; + CheckForRewrite(fullUrl, querystring, result, useFriendlyUrls, queryStringCol, settings, out isPhysicalResource, parentTraceId); + } - // don't use this crap though - we don't want ?alias=portalAlias in our Url - if (result.RedirectAllowed) - { - string redirect = requestUri.Scheme + Uri.SchemeDelimiter + result.PortalAlias.HTTPAlias + - "/"; - result.Action = ActionType.Redirect301; - result.FinalUrl = redirect; - result.Reason = RedirectReason.Unfriendly_Url_Child_Portal; - } + // return 404 if there is no portal alias for a rewritten request + if (result.DoRewrite && result.PortalAlias == null) + { + // 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; + + Handle404OrException(settings, context, null, result, false, showDebug); + finished = true; // cannot fulfil request unless correct portal alias specified } } - } - } - // first try and identify the portal using the tabId, but only if we identified this tab by looking up the tabid - // from the original url - // 668 : error in child portal redirects to child portal home page because of mismatch in tab/domain name - if (result.TabId != -1 && result.FriendlyRewrite == false) - { - // get the alias from the tabid, but only if it is for a tab in that domain - // 2.0 : change to compare retrieved alias to the already-set httpAlias - string httpAliasFromTab = PortalAliasController.GetPortalAliasByTab(result.TabId, result.DomainName); - if (httpAliasFromTab != null) - { - // 882 : account for situation when portalAlias is null. - if ((result.PortalAlias != null && string.Compare(result.PortalAlias.HTTPAlias, httpAliasFromTab, StringComparison.OrdinalIgnoreCase) != 0) - || result.PortalAlias == null) + // now we may know the TabId. If the current alias is not the same as the primary alias, + // we should check if the current alias is indeed a valid custom alias for the current tab. + if (result.TabId > 0 && result.HttpAlias != result.PrimaryAlias.HTTPAlias && !CheckIfAliasIsCurrentTabCustomTabAlias(ref result, settings)) { - // 691 : change logic to force change in portal alias context rather than force back. - // This is because the tabid in the query string should take precedence over the portal alias - // to handle parent.com/default.aspx?tabid=xx where xx lives in parent.com/child/ - var tab = TabController.Instance.GetTab(result.TabId, Null.NullInteger, false); - - // when result alias is null or result alias is different from tab-identified portalAlias - if (tab != null && (result.PortalAlias == null || tab.PortalID != result.PortalAlias.PortalID)) + //it was an incorrect alias + //try and redirect the alias if the settings allow it + if( RedirectPortalAlias(result.PrimaryAlias.HTTPAlias, ref result, settings)) { - // the tabid is different to the identified portalid from the original alias identified - // so get a new alias - PortalAliasInfo tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(httpAliasFromTab, tab.PortalID); - if (tabPortalAlias != null) - { - result.PortalId = tabPortalAlias.PortalID; - result.PortalAlias = tabPortalAlias; - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Wrong_Portal; - } + //not correct alias for tab : 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 no alias, try and set by using the identified http alias or domain name - if (result.PortalAlias == null) - { - if (!string.IsNullOrEmpty(result.HttpAlias)) - { - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias); - } - else - { - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); - if (result.PortalAlias == null && result.DomainName.EndsWith("/")) + if (!finished && result.DoRewrite) { - result.DomainName = result.DomainName.TrimEnd('/'); - result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); - } - } - } + // 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) - { - if (!requestUri.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - // allows requests for aspx pages in custom folder locations to be processed - return; - } + 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); - // the domain name was not found so try using the host portal's first alias - if (Host.HostPortalID != -1) - { - result.PortalId = Host.HostPortalID; + // 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; + } - // use the host portal, but replaced to the host portal home page - var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (aliases.Count > 0) - { - string alias = null; + // 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); + } + } + } - // get the alias as the chosen portal alias for the host portal based on the result culture code - var cpa = aliases.GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, settings); - if (cpa != null) + if (!finished && result.DoRewrite) + { + // if so, do the rewrite + if (result.RewritePath.StartsWith(result.Scheme) || result.RewritePath.StartsWith(Globals.glbDefaultPage) == false) { - alias = cpa.HTTPAlias; + 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); + } + } + } + else + { + RewriterUtils.RewriteUrl(context, "~/" + result.RewritePath); } + } - if (alias != null) + // confirm which portal the request is for + if (!finished) + { + this.IdentifyPortalAlias(context, request, requestUri, result, queryStringCol, settings, parentTraceId); + if (result.Action == ActionType.Redirect302Now) { - result.Action = ActionType.Redirect301; - result.Reason = RedirectReason.Host_Portal_Used; - string destUrl = MakeUrlWithAlias(requestUri, alias); - destUrl = CheckForSiteRootRedirect(alias, destUrl); - result.FinalUrl = destUrl; + // performs a 302 redirect if requested + response.AppendHeader("X-Redirect-Reason", result.Reason.ToString().Replace("_", " ") + " Requested"); + response.Redirect(result.FinalUrl, false); + finished = true; } else { - // Get the first Alias for the host portal - result.PortalAlias = aliases[result.PortalId]; - string url = MakeUrlWithAlias(requestUri, result.PortalAlias); - if (result.TabId != -1) + if (result.Action == ActionType.Redirect301 && !string.IsNullOrEmpty(result.FinalUrl)) { - url += requestUri.Query; - } + finished = true; - result.FinalUrl = url; - result.Reason = RedirectReason.Host_Portal_Used; - result.Action = ActionType.Redirect302Now; + // 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); + } } } - } - } - - // double check to make sure we still have the correct alias now that all other information is known (ie tab, portal, culture) - // 770 : redirect alias based on tab id when custom alias used - if (result.TabId == -1 && result.Action == ActionType.CheckFor301 && - result.Reason == RedirectReason.Custom_Tab_Alias) - { - // here because the portal alias matched, but no tab was found, and because there are custom tab aliases used for this portal - // need to redirect back to the chosen portal alias and keep the current path. - string wrongAlias = result.HttpAlias; // it's a valid alias, but only for certain tabs - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - if (primaryAliases != null && result.PortalId > -1) - { - // going to look for the correct alias based on the culture of the request - string requestCultureCode = result.CultureCode; - // if that didn't work use the default language of the portal - if (requestCultureCode == null) + if (!finished) { - // this might end up in a double redirect if the path of the Url is for a specific language as opposed - // to a path belonging to the default language domain - PortalInfo portal = PortalController.Instance.GetPortal(result.PortalId); - if (portal != null) - { - requestCultureCode = portal.DefaultLanguage; - } + // check to see if this tab has an external url that should be forwared or not + finished = CheckForTabExternalForwardOrRedirect(context, ref result, response, settings, parentTraceId); } - // now that the culture code is known, look up the correct portal alias for this portalid/culture code - var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, requestCultureCode, settings); - if (cpa != null) + // 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))) { - // if an alias was found that matches the request and the culture code, then run with that - string rightAlias = cpa.HTTPAlias; + // 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; + } + } - // will cause a redirect to the primary portal alias - we know now that there was no custom alias tab - // found, so it's just a plain wrong alias - ConfigurePortalAliasRedirect(ref result, wrongAlias, rightAlias, true, - settings.InternalAliasList, settings); + finished = true; } - } - } - else - { - // then check to make sure it's the chosen portal alias for this portal - // 627 : don't do it if we're redirecting to the host portal - if (result.RedirectAllowed && result.Reason != RedirectReason.Host_Portal_Used) - { - string primaryAlias; - // checking again in case the rewriting operation changed the values for the valid portal alias - bool incorrectAlias = this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryAlias); - if (incorrectAlias) + // 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) { - RedirectPortalAlias(primaryAlias, ref result, settings); - } - } - } + 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 + { + finished = true; + response.AppendHeader("X-Result-Reason", result.Reason.ToString().Replace("_", " ")); - // check to see if we have to avoid the core 302 redirect for the portal alias that is in the /defualt.aspx - // for child portals - // exception to that is when a custom alias is used but no rewrite has taken place - if (result.DoRewrite == false && (result.Action == ActionType.Continue - || - (result.Action == ActionType.CheckFor301 && - result.Reason == RedirectReason.Custom_Tab_Alias))) - { - string aliasQuerystring; - bool isChildAliasRootUrl = CheckForChildPortalRootUrl(requestUri.AbsoluteUri, result, out aliasQuerystring); - if (isChildAliasRootUrl) - { - RewriteAsChildAliasRoot(context, result, aliasQuerystring, settings); - } - } - } + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, null); + } - internal static void RewriteAsChildAliasRoot( - HttpContext context, - UrlAction result, - string aliasQueryString, - FriendlyUrlSettings settings) - { - string culture = null; + // show the 404 page if configured + result.Reason = RedirectReason.Requested_404; + Handle404OrException(settings, context, null, result, true, showDebug); + } + } - // 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 (!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) + { + finished = true; - if (string.IsNullOrEmpty(culture)) + if (showDebug) + { + ShowDebugData(context, requestUri.AbsoluteUri, result, null); + } - // 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; - } - } + // 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 + { + Globals.SetApplicationName(result.PortalId); - if (!string.IsNullOrEmpty(culture)) // a culture was identified for the alias root - { - if (RewriteController.AddLanguageCodeToRewritePath(ref aliasQueryString, culture)) - { - result.CultureCode = culture; - } + // load the PortalSettings into current context + var portalSettings = new PortalSettings(result.TabId, result.PortalAlias); - result.DoRewrite = true; - result.RewritePath = "~/" + Globals.glbDefaultPage + aliasQueryString; + // set the primary alias if one was specified + if (result.PrimaryAlias != null) + { + portalSettings.PrimaryAlias = result.PrimaryAlias; + } - // 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); - } - } - } + 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; + } - internal static bool CheckForChildPortalRootUrl(string requestUrl, UrlAction result, out string aliasQueryString) - { - bool isChildPortalRootUrl = false; + int portalHomeTabId = portalSettings.HomeTabId; + if (context != null && portalSettings != null && !context.Items.Contains("PortalSettings")) + { + context.Items.Add("PortalSettings", portalSettings); - // 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 + // 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()); + } - // 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; - } + // 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); + } - 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; + 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(); - // 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; - } - - private static string MakeUrlWithAlias(Uri requestUri, string httpAlias) - { - return requestUri.AbsoluteUri.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) - ? "https://" + httpAlias.Replace("*.", string.Empty) + "/" - : "http://" + httpAlias.Replace("*.", string.Empty) + "/"; - } - - private static string MakeUrlWithAlias(Uri requestUri, PortalAliasInfo alias) - { - return MakeUrlWithAlias(requestUri, alias.HTTPAlias); - } - - /// - /// Determines if this is a request from an install / upgrade url. - /// - /// - /// - /// - /// - /// - /// - /// //875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1. - /// - private static bool IgnoreRequestForInstall(string physicalPath, string refererPath, string requestedDomain, string refererDomain) - { - if (physicalPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) - || physicalPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) - || physicalPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture) - || Globals.Status == Globals.UpgradeStatus.Install - || Globals.Status == Globals.UpgradeStatus.Upgrade) - { - return true; - } - - // 954 : DNN 7.0 compatibility - // check for /default.aspx which is default Url launched from the Upgrade/Install wizard page - // 961 : check domain as well as path for the referer - if (physicalPath.EndsWith(Globals.glbDefaultPage, true, CultureInfo.InvariantCulture) == false - && refererPath != null - && string.Compare(requestedDomain, refererDomain, StringComparison.OrdinalIgnoreCase) == 0 - && (refererPath.EndsWith("install.aspx", true, CultureInfo.InvariantCulture) - || refererPath.EndsWith("installwizard.aspx", true, CultureInfo.InvariantCulture) - || refererPath.EndsWith("upgradewizard.aspx", true, CultureInfo.InvariantCulture))) - { - return true; - } - - return false; - } - - private static bool IgnoreRequestForWebServer(string requestedPath) - { - // Should standardize comparison methods - if (requestedPath.IndexOf("synchronizecache.aspx", StringComparison.OrdinalIgnoreCase) > 1 - || requestedPath.EndsWith("keepalive.aspx", StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - // Get the root - var rootPath = requestedPath.Substring(0, requestedPath.LastIndexOf("/", StringComparison.Ordinal)); - rootPath = rootPath.Substring(rootPath.IndexOf("://", StringComparison.Ordinal) + 3); - - // Check if this is a WebServer and not a portalalias. - // if can auto add portal alias enabled, then return false, alias will add later. - var alias = PortalAliasController.Instance.GetPortalAlias(rootPath); - if (alias != null || CanAutoAddPortalAlias()) - { - return false; - } - - // Check if this is a WebServer - var server = ServerController.GetEnabledServers().SingleOrDefault(s => s.Url == rootPath); - if (server != null) - { - return true; - } + // add a refresh header to the response + response.AddHeader("Refresh", "0;URL=" + result.FinalUrl); - return false; - } + // 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); + } - private static bool IgnoreRequestForInstall(HttpRequest request) - { - try - { - string physicalPath = request.PhysicalPath; - string requestedDomain = request.Url.Host; - string refererPath = null, refererDomain = null; - if (request.UrlReferrer != null) - { - refererDomain = request.UrlReferrer.Host; - refererPath = request.UrlReferrer.LocalPath; - } + // 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; + } + } + } + } + } + else + { + // 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; + } + } + } + } + } + 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 (showDebug) + { + ShowDebugData(context, fullUrl, result, null); + } - return IgnoreRequestForInstall(physicalPath, refererPath, requestedDomain, refererDomain); - } - catch (PathTooLongException) - { - // catch and handle this exception, caused by an excessively long file path based on the - // mapped virtual url - return false; - } - catch (ArgumentException) - { - // catch and handle this exception, caused by an invalid character in the file path based on the - // mapped virtual url - return false; - } - } + result.Reason = RedirectReason.Requested_404; - private static bool IgnoreRequest(UrlAction result, string requestedPath, string ignoreRegex, HttpRequest request) - { - bool retVal = false; + // 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; + } + } + } - // check if we are upgrading/installing - // 829 : use result physical path instead of requset physical path - // 875 : cater for the upgradewizard.aspx Url that is new to DNN 6.1 - if (request != null && (IgnoreRequestForInstall(request) || IgnoreRequestForWebServer(requestedPath))) - { - // ignore all install requests - retVal = true; - } - else if (request != null && request.Path.EndsWith("imagechallenge.captcha.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - retVal = true; - } - else - { - try - { - if (ignoreRegex.Length > 0) + // 404 page ?? + if (settings.TabId404 > 0 && settings.TabId404 == result.TabId) { - if (Regex.IsMatch(requestedPath, ignoreRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + string status = queryStringCol["status"]; + if (status == "404") { - retVal = true; + // respond with a 404 error + result.Action = ActionType.Output404; + result.Reason = RedirectReason.Requested_404_In_Url; + Handle404OrException(settings, context, null, result, true, showDebug); } } - } - catch (Exception ex) - { - UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - result.Ex = ex; - } - } - - return retVal; - } + else + { + if (result.DoRewrite == false && result.CanRewrite != StateBoolean.False && !finished && + result.Action == ActionType.Continue) + { + // 739 : catch no-extension 404 errors + string pathWithNoQs = result.OriginalPath; + if (pathWithNoQs.Contains("?")) + { + pathWithNoQs = pathWithNoQs.Substring(0, pathWithNoQs.IndexOf("?", StringComparison.Ordinal)); + } - private static void CheckForRewrite( - string fullUrl, - string querystring, - UrlAction result, - bool useFriendlyUrls, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - out bool isPhysicalResource, - Guid parentTraceId) - { - bool checkForRewrites; + if (!pathWithNoQs.Substring(pathWithNoQs.Length - 5, 5).Contains(".")) + { + // 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; - // just check to make sure it isn't a physical resource on the server - RewriteController.IdentifyByPhysicalResource( - result.PhysicalPath, - fullUrl, - queryStringCol, - ref result, - useFriendlyUrls, - settings, - out isPhysicalResource, - out checkForRewrites, - parentTraceId); + // 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 (checkForRewrites && RewriteController.CanRewriteRequest(result, fullUrl, settings)) + // show debug messages after extensionless-url special 404 handling + if (showDebug) + { + 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) { - bool doSiteUrlProcessing = false; - - // 728 new regex expression to pass values straight onto the siteurls.config file - if (!string.IsNullOrEmpty(settings.UseSiteUrlsRegex)) + if (showDebug) { - doSiteUrlProcessing = Regex.IsMatch(fullUrl, settings.UseSiteUrlsRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + Services.Exceptions.Exceptions.LogException(ex); } - if (!doSiteUrlProcessing) - - // if a virtual request, and not starting with the siteUrls.config file, go on to find the rewritten path + if (response != null) { - // looks up the page index to find the correct Url - bool doRewrite = RewriteController.IdentifyByTabPathEx(fullUrl, querystring, result, queryStringCol, settings, parentTraceId); - if (!doRewrite) + if (showDebug) { - doSiteUrlProcessing = true; + ShowDebugData(context, requestUri.AbsoluteUri, result, ex); } - } - if (doSiteUrlProcessing) + if (result != null) + { + result.Ex = ex; + result.Reason = RedirectReason.Exception; + } + + Handle404OrException(settings, context, ex, result, false, showDebug); + } + else { - // 728 : compare requests against the siteurls.config file, either if no other match was found, or if we want to skip the rest of the processing - // the standard DNN way of rewriting, using expressions found in the siteurls.config file - RewriteController.IdentifyByRegEx(fullUrl, querystring, result.ApplicationPath, ref result, settings, parentTraceId); + if (result != null && result.DebugMessages != null) + { + result.DebugMessages.Add("Exception: " + ex.Message); + result.DebugMessages.Add("Stack Trace: " + ex.StackTrace); + } + + throw; } } - } - - 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) + finally { - throw new HttpException(404, "Not Found"); + // 809 : add in new code copied from urlRewrite class in standard Url Rewrite module + if (context != null && context.Items["FirstRequest"] != null) + { + context.Items.Remove("FirstRequest"); + + // process any messages in the eventQueue for the Application_Start_FIrstRequest event + EventQueueController.ProcessMessages("Application_Start_FirstRequest"); + } } } - private static bool CheckForRedirects( + private bool CheckForSecureRedirect( + PortalSettings portalSettings, Uri requestUri, - string fullUrl, - NameValueCollection queryStringCol, UrlAction result, - string requestType, - FriendlyUrlSettings settings, - int portalHomeTabId) + NameValueCollection queryStringCol, + FriendlyUrlSettings settings) { - bool redirected = false; - if (queryStringCol["error"] == null && queryStringCol["message"] == null && requestType != "POST") + bool redirectSecure = false; + string url = requestUri.ToString(); + + // 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 { - // if the / is missing from an extension-less request, then check for a 301 redirect - if (settings.PageExtensionUsageType == PageExtensionUsageType.Never) + if (portalSettings.ActiveTab != null) { - // 575 check on absolutePath instead of absoluteUri : this ignores query strings and fragments like # - // 610 don't always end with '/' - reverses previous setting - // 687 don't double-check 301 redirects. 'CheckFor301' is less concise than 'Redirect301' - // DNN-21906: if the redirect is for splash page, then we should continue the 302 redirect. - if (requestUri.AbsolutePath.EndsWith("/") && result.Action != ActionType.Redirect301 && result.Reason != RedirectReason.Requested_SplashPage) + result.DebugMessages.Add("ActiveTab: " + portalSettings.ActiveTab.TabID.ToString() + "/" + + portalSettings.ActiveTab.TabName + " IsSecure: " + + portalSettings.ActiveTab.IsSecure.ToString()); + + // check ssl enabled + if (portalSettings.SSLEnabled) { - result.Action = ActionType.CheckFor301; + // 717 : check page is secure, connection is not secure + // 952 : support SSl Offloading in DNN 6.2+ + if (portalSettings.ActiveTab.IsSecure && !result.IsSecureConnection && !result.IsSSLOffloaded) + { + redirectSecure = true; + string stdUrl = portalSettings.STDURL; + string sslUrl = portalSettings.SSLURL; + if (string.IsNullOrEmpty(result.HttpAlias) == false) + { + stdUrl = result.HttpAlias; + } + + url = url.Replace("http://", "https://"); + url = this.ReplaceDomainName(url, stdUrl, sslUrl); + } } - } - if (settings.RedirectWrongCase && result.Action == ActionType.Continue) - { - result.Action = ActionType.CheckFor301; + // 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; + } + } + } } - string scheme = requestUri.Scheme + Uri.SchemeDelimiter; - bool queryStringHas301Parm = queryStringCol["do301"] != null; - - // 727 : keep a bool value if there is a do301 request in the querystring - // check for a 301 request in the query string, or an explicit 301 or 302 request - // 2.0 - check for explicit do301=true instead of just do301 key - string do301Val = queryStringCol["do301"]; - if (result.TabId > -1 // valid tab - && (result.Action == ActionType.Redirect301 // specific 301 redirect - || (do301Val != null && do301Val == "true") // or rewrite hint for specific 301 redirect - || result.Action == ActionType.Redirect302)) // or specific 302 redirect + if (redirectSecure) { - // we have ordered a 301 redirect earlier in the code - // get the url for redirection by re-submitting the path into the Friendly Url Provider - string pathOnly = RewriteController.GetRewriteOrRequestedPath(result, requestUri); - - // 727 prevent redirectLoop with do301 in querystring - if (result.Action == ActionType.Redirect301 || queryStringHas301Parm || result.Action == ActionType.Redirect302) + // 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)) { - pathOnly = RedirectTokens.RemoveAnyRedirectTokens(pathOnly, queryStringCol); + // match the raw url + exclude = Regex.IsMatch(result.RawUrl, doNotRedirectSecureRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } - // check for exclusion by regex for this url - if (result.RedirectAllowed) + if (!exclude) { - // get the tab so we know where to go - TabInfo tab; - bool checkRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + result.Action = ActionType.Redirect302Now; + result.Reason = RedirectReason.Secure_Page_Requested; - if (checkRedirect) + // 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) { - if ((result.Reason == RedirectReason.Deleted_Page || result.Reason == RedirectReason.Disabled_Page) - && portalHomeTabId > 0 - && settings.DeletedTabHandlingType == DeletedTabHandlingType.Do301RedirectToPortalHome) - { - // redirecting to home page - TabInfo homeTab = TabController.Instance.GetTab(portalHomeTabId, result.PortalId, false); - if (homeTab != null) - { - string homePageUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( - homeTab, - pathOnly, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); - result.Action = ActionType.Redirect301; - result.FinalUrl = homePageUrl; - result.RewritePath = pathOnly; - redirected = true; - } - } - else - { - // get the rewrite or requested path in a clean format, suitable for input to the friendly url provider - string cleanPath = RewriteController.GetRewriteOrRequestedPath(result, requestUri); + // replace the /default.aspx in the Url if it was found + url = DefaultPageRegex.Replace(url, "/"); + } - // 727 prevent redirectLoop with do301 in querystring - // also check for existing in path of do301 token - if (result.Action == ActionType.Redirect301 || do301Val != null || result.Action == ActionType.Redirect302) - { - cleanPath = RedirectTokens.RemoveAnyRedirectTokens(cleanPath, queryStringCol); - } + 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; + } + + private void IdentifyPortalAlias( + HttpContext context, + HttpRequest request, + Uri requestUri, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + // get the domain name of the request, if it isn't already supplied + if (request != null && string.IsNullOrEmpty(result.DomainName)) + { + result.DomainName = Globals.GetDomainName(request); // parse the domain name out of the request + } - // get best friendly url from friendly url provider - string bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( - tab, - cleanPath, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); + // get tabId from querystring ( this is mandatory for maintaining portal context for child portals ) + if (queryStringCol["tabid"] != null) + { + string raw = queryStringCol["tabid"]; + int tabId; + if (int.TryParse(raw, out tabId)) + { + result.TabId = tabId; + } + else + { + // couldn't parse tab id + // split in two? + string[] tabids = raw.Split(','); + if (tabids.GetUpperBound(0) > 0) + { + // hmm more than one tabid + if (int.TryParse(tabids[0], out tabId)) + { + result.TabId = tabId; - // get what the friendly Url for this tab should be and stick it in as the redirect - // 727 : using boolean because we wanted to get rid of the do301 before calculating the correct url - if (queryStringHas301Parm) - { - result.Action = ActionType.Redirect301; - if (result.Reason == RedirectReason.Not_Redirected) - { - result.Reason = RedirectReason.Unfriendly_Url_1; - } - } + // but we want to warn against this! + var ex = + new Exception( + "Illegal request exception : Two TabId parameters provided in a single request: " + + requestUri); + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); - result.FinalUrl = bestFriendlyUrl; - result.RewritePath = pathOnly; - redirected = true; // mark as redirected - } + result.Ex = ex; } else { - // redirect disallowed - // 618: dont' clear if 302 redirect selected - if (result.Action != ActionType.Redirect302Now || result.Action != ActionType.Redirect302) - { - RedirectController.CancelRedirect(ref result, null, settings, "Redirect requested but cancelled because disallowed"); - } + // yeah, nothing, divert to 404 + result.Action = ActionType.Output404; + var ex = + new Exception( + "Illegal request exception : TabId parameters in query string, but invalid TabId requested : " + + requestUri); + UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", result); + result.Ex = ex; } } } - else if (result.TabId > -1 && result.RedirectAllowed && result.Action == ActionType.CheckFor301) + } + + // get PortalId from querystring ( this is used for host menu options as well as child portal navigation ) + if (queryStringCol["portalid"] != null) + { + string raw = queryStringCol["portalid"]; + int portalId; + if (int.TryParse(raw, out portalId)) { - // 301 check was requested in earlier processing - // get the tab controller and retrieve the tab the request is for - // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab - if (settings.RedirectUnfriendly) + // 848 : if portal already found is different to portal id in querystring, then load up different alias + // this is so the portal settings will be loaded correctly. + if (result.PortalId != portalId) { - TabInfo tab; - bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); - if (allowRedirect && tab != null) - { - // remove the http alias from the url. Do this by putting the url back together from the request and removing the alias - string rewritePathOnly; - if (result.DoRewrite) - { - rewritePathOnly = result.RewritePath; - var pos = rewritePathOnly.IndexOf("default.aspx", StringComparison.OrdinalIgnoreCase); - if (pos > Null.NullInteger) - { - rewritePathOnly = rewritePathOnly.Substring(pos); - } - } - else - { - rewritePathOnly = requestUri.Host + requestUri.PathAndQuery; - } + // portal id different to what we expected + result.PortalId = portalId; - // remove the http alias from the path - var pathAliasEnd = rewritePathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase); - var queryStringIndex = rewritePathOnly.IndexOf("?", StringComparison.InvariantCultureIgnoreCase); - if (pathAliasEnd > Null.NullInteger && (queryStringIndex == Null.NullInteger || pathAliasEnd < queryStringIndex)) + // check the loaded portal alias, because it might be wrong + if (result.PortalAlias != null && result.PortalAlias.PortalID != portalId) + { + // yes, the identified portal alias is wrong. Find the correct alias for this portal + PortalAliasInfo pa = TabIndexController.GetPortalAliasByPortal(portalId, result.DomainName); + if (pa != null) { - rewritePathOnly = rewritePathOnly.Substring(pathAliasEnd + result.PortalAlias.HTTPAlias.Length); + // note: sets portal id and portal alias + result.PortalAlias = pa; } - - // now check to see if need to remove /default.aspx from the end of the requested Url - string requestedUrl = fullUrl; - int requestedUrlAliasEnd = requestedUrl.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) - + (result.PortalAlias.HTTPAlias + "/").Length; - if (requestedUrlAliasEnd > Null.NullInteger) + } + } + } + } + else + { + // check for a portal alias if there's no portal Id in the query string + // check for absence of captcha value, because the captcha string re-uses the alias querystring value + if (queryStringCol["alias"] != null && queryStringCol["captcha"] == null) + { + string alias = queryStringCol["alias"]; + PortalAliasInfo portalAlias = PortalAliasController.Instance.GetPortalAlias(alias); + if (portalAlias != null) + { + // ok the portal alias was found by the alias name + // check if the alias contains the domain name + if (alias.Contains(result.DomainName) == false) + { + // replaced to the domain defined in the alias + if (request != null) { - // 818 : when a site root is used for a custom page Url, then check for max length within bounds - if ((requestedUrl.Length - requestedUrlAliasEnd) >= 12 && requestedUrl.Substring(requestedUrlAliasEnd).Equals("default.aspx", StringComparison.InvariantCultureIgnoreCase)) - { - requestedUrl = requestedUrl.Substring(0, requestedUrl.Length - 12); + string redirectDomain = Globals.GetPortalDomainName(alias, request, true); - // 12 = default.aspx length - } + // retVal.Url = redirectDomain; + result.FinalUrl = redirectDomain; + result.Action = ActionType.Redirect302Now; + result.Reason = RedirectReason.Alias_In_Url; } + } + else + { + // the alias is the same as the current domain + result.HttpAlias = portalAlias.HTTPAlias; + result.PortalAlias = portalAlias; + result.PortalId = portalAlias.PortalID; - // what happens here is that the request is reverse-engineered to see if it matches what the friendly Url shoudl have been - // get what the friendly Url for this tab should be - string bestFriendlyUrl; - - // 819 : leaving /do301/check in Url because not using cleanPath to remove from - string cleanPath = RedirectTokens.RemoveAnyRedirectTokensAndReasons(rewritePathOnly); - - // string cleanPath = rewritePathOnly.Replace("&do301=check","");//remove check parameter if it exists - // cleanPath = cleanPath.Replace("&do301=true", "");//don't pass through internal redirect check parameter - cleanPath = cleanPath.Replace("&_aumdebug=true", string.Empty); // remove debug parameter if it exists - - Match match = RewritePathRx.Match(rewritePathOnly ?? string.Empty); - if (match.Success) - { - // when the pathOnly value ends with '=' it means there is a query string pair with a key and no value - // make the assumption that this was passed in as a page name OTHER than default page - string pageName = match.Groups["parm"].Value; // get the last parameter in the list - - cleanPath = cleanPath.Replace(match.Value, string.Empty); - - // remove the last parameter from the path - - // generate teh friendly URl name with the last parameter as the page name, not a query string parameter - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( - tab, - cleanPath, - pageName + settings.PageExtension, - result.HttpAlias, - false, - settings, - Guid.Empty); - } - else + // don't use this crap though - we don't want ?alias=portalAlias in our Url + if (result.RedirectAllowed) { - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( - tab, - cleanPath, - Globals.glbDefaultPage, - result.HttpAlias, - false, - settings, - Guid.Empty); + string redirect = requestUri.Scheme + Uri.SchemeDelimiter + result.PortalAlias.HTTPAlias + + "/"; + result.Action = ActionType.Redirect301; + result.FinalUrl = redirect; + result.Reason = RedirectReason.Unfriendly_Url_Child_Portal; } + } + } + } + } - // if the incoming request doesn't match the 'most friendly' url, a 301 Moved Permanently status is returned, along with the friendly url - // check the bestFriendlyUrl against either the url, or rawUrl (with and without host) - // in each case, the aumdebug parameter will be searched for and replaced - var urlDecode = HttpUtility.UrlDecode(requestedUrl); - if (urlDecode != null) - { - string rawUrlWithHost = StripDebugParameter(urlDecode.ToLowerInvariant()); - - // string rawUrlWithHost = StripDebugParameter(System.Web.HttpUtility.UrlDecode(scheme + requestUri.Host + requestUri.PathAndQuery).ToLowerInvariant()); - string rawUrlWithHostNoScheme = StripDebugParameter(rawUrlWithHost.Replace(scheme, string.Empty)); - string bestFriendlyNoScheme = StripDebugParameter(bestFriendlyUrl.ToLowerInvariant().Replace(scheme, string.Empty)); - string requestedPathNoScheme = StripDebugParameter(requestUri.AbsoluteUri.Replace(scheme, string.Empty).ToLowerInvariant()); - string rawUrlLowerCase = StripDebugParameter(requestUri.AbsoluteUri.ToLowerInvariant()); - - // check to see if just an alias redirect of an internal alias - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); - - if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0 && primaryAliases.Count > 0) - { - var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result); - if (cpa != null) - { - string chosenAlias = cpa.HTTPAlias.ToLowerInvariant(); - foreach (InternalAlias ia in settings.InternalAliasList) - { - string internalAlias = ia.HttpAlias.ToLowerInvariant(); - if (requestedPathNoScheme.Contains(internalAlias)) - { - // an internal alias has been used. - // replace this in the comparison charts to do a 'fair' comparison - requestedPathNoScheme = requestedPathNoScheme.Replace(internalAlias, chosenAlias); - rawUrlWithHost = rawUrlWithHost.Replace(scheme + internalAlias, scheme + chosenAlias); - rawUrlWithHostNoScheme = rawUrlWithHostNoScheme.Replace(internalAlias, chosenAlias); - rawUrlLowerCase = rawUrlLowerCase.Replace(internalAlias, chosenAlias); - break; - } - } - } - } - - // DNN-9158: prevent SSL Offloading infinite redirects - if (!result.IsSecureConnection && result.IsSSLOffloaded && bestFriendlyNoScheme.StartsWith("https")) - { - bestFriendlyNoScheme = $"http://{bestFriendlyNoScheme.Substring(8)}"; - } - - if (!(bestFriendlyNoScheme == requestedPathNoScheme - || bestFriendlyNoScheme == rawUrlWithHost - || bestFriendlyNoScheme == rawUrlWithHostNoScheme - || bestFriendlyNoScheme == HttpUtility.UrlDecode(requestedPathNoScheme) - || HttpUtility.UrlDecode(bestFriendlyNoScheme) == HttpUtility.UrlDecode(requestedPathNoScheme) - || bestFriendlyNoScheme == rawUrlLowerCase)) - { - redirected = true; - result.Action = ActionType.Redirect301; - result.FinalUrl = bestFriendlyUrl; - if (result.Reason != RedirectReason.Custom_Tab_Alias && - result.Reason != RedirectReason.Deleted_Page && - result.Reason != RedirectReason.Disabled_Page) - { - result.Reason = RedirectReason.Unfriendly_Url_2; - } + // first try and identify the portal using the tabId, but only if we identified this tab by looking up the tabid + // from the original url + // 668 : error in child portal redirects to child portal home page because of mismatch in tab/domain name + if (result.TabId != -1 && result.FriendlyRewrite == false) + { + // get the alias from the tabid, but only if it is for a tab in that domain + // 2.0 : change to compare retrieved alias to the already-set httpAlias + string httpAliasFromTab = PortalAliasController.GetPortalAliasByTab(result.TabId, result.DomainName); + if (httpAliasFromTab != null) + { + // 882 : account for situation when portalAlias is null. + if ((result.PortalAlias != null && string.Compare(result.PortalAlias.HTTPAlias, httpAliasFromTab, StringComparison.OrdinalIgnoreCase) != 0) + || result.PortalAlias == null) + { + // 691 : change logic to force change in portal alias context rather than force back. + // This is because the tabid in the query string should take precedence over the portal alias + // to handle parent.com/default.aspx?tabid=xx where xx lives in parent.com/child/ + var tab = TabController.Instance.GetTab(result.TabId, Null.NullInteger, false); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + requestedPathNoScheme + " [requested with no scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHost + " [requested with host and scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlWithHostNoScheme + " [requested with host, no scheme]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + HttpUtility.UrlDecode(requestedPathNoScheme) + " [requested and decoded]"); - result.DebugMessages.Add("Compared :" + bestFriendlyNoScheme + " [generated] -> " + rawUrlLowerCase + " [requested raw Url]"); - } + // when result alias is null or result alias is different from tab-identified portalAlias + if (tab != null && (result.PortalAlias == null || tab.PortalID != result.PortalAlias.PortalID)) + { + // the tabid is different to the identified portalid from the original alias identified + // so get a new alias + PortalAliasInfo tabPortalAlias = PortalAliasController.Instance.GetPortalAlias(httpAliasFromTab, tab.PortalID); + if (tabPortalAlias != null) + { + result.PortalId = tabPortalAlias.PortalID; + result.PortalAlias = tabPortalAlias; + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Wrong_Portal; } } } } + } - if (result.RedirectAllowed && settings.RedirectWrongCase) + // if no alias, try and set by using the identified http alias or domain name + if (result.PortalAlias == null) + { + if (!string.IsNullOrEmpty(result.HttpAlias)) { - // check for redirects where a redirectToSubDomain is specified, - // redirect for Wrong case is specified, and there is a valid tab and it's not already redirected somewhere else - bool doRedirect = false; - string redirectPath = redirected ? result.FinalUrl : requestUri.AbsoluteUri; - string redirectPathOnly = redirectPath; - if (redirectPathOnly.Contains("?")) + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.HttpAlias); + } + else + { + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); + if (result.PortalAlias == null && result.DomainName.EndsWith("/")) { - redirectPathOnly = redirectPathOnly.Substring(0, redirectPathOnly.IndexOf("?", StringComparison.Ordinal)); + result.DomainName = result.DomainName.TrimEnd('/'); + result.PortalAlias = PortalAliasController.Instance.GetPortalAlias(result.DomainName); } + } + } - // Thanks Etienne for the fix for Diacritic Characters Terminal Loop! - // if the url contains url encoded characters, they appear here uppercase -> %C3%83%C2 - // decode the url to get back the original character and do proper casing comparison - string urlDecodedRedirectPath = HttpUtility.UrlDecode(redirectPathOnly); + if (result.PortalId == -1) + { + if (!requestUri.LocalPath.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + // allows requests for aspx pages in custom folder locations to be processed + return; + } - // check for wrong case redirection - if (urlDecodedRedirectPath != null && (settings.RedirectWrongCase && string.CompareOrdinal(urlDecodedRedirectPath, urlDecodedRedirectPath.ToLowerInvariant()) != 0)) + // the domain name was not found so try using the host portal's first alias + if (Host.HostPortalID != -1) + { + result.PortalId = Host.HostPortalID; + + // use the host portal, but replaced to the host portal home page + var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (aliases.Count > 0) { - TabInfo tab; - bool allowRedirect = CheckFor301RedirectExclusion(result.TabId, result.PortalId, true, out tab, settings); + string alias = null; - if (allowRedirect && !string.IsNullOrEmpty(settings.ForceLowerCaseRegex)) + // get the alias as the chosen portal alias for the host portal based on the result culture code + var cpa = aliases.GetAliasByPortalIdAndSettings(result.PortalId, result, result.CultureCode, settings); + if (cpa != null) { - // don't allow redirect if excluded from redirecting in the force lower case regex pattern (606) - allowRedirect = !Regex.IsMatch(redirectPath, settings.ForceLowerCaseRegex, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + alias = cpa.HTTPAlias; } - if (allowRedirect) + if (alias != null) { - // special case : when IIS automatically places /default.aspx on the end of the string, - // then don't try and redirect to the lower case /default.aspx, just let it through. - // we don't know whether IIS appended /Default.aspx on the end, however, we can guess - // if the redirectDefault.aspx is turned on (511) - if (settings.RedirectDefaultPage == false && redirectPathOnly.EndsWith(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - // ignore this, because it's just a redirect of the /Default.aspx to /default.aspx - } - else + result.Action = ActionType.Redirect301; + result.Reason = RedirectReason.Host_Portal_Used; + string destUrl = MakeUrlWithAlias(requestUri, alias); + destUrl = CheckForSiteRootRedirect(alias, destUrl); + result.FinalUrl = destUrl; + } + else + { + // Get the first Alias for the host portal + result.PortalAlias = aliases[result.PortalId]; + string url = MakeUrlWithAlias(requestUri, result.PortalAlias); + if (result.TabId != -1) { - redirectPath = redirectPath.Replace(redirectPathOnly, redirectPathOnly.ToLowerInvariant()); - doRedirect = true; - result.Reason = RedirectReason.Not_Lower_Case; + url += requestUri.Query; } - } - } - if (doRedirect) - { - result.Action = ActionType.Redirect301; - result.FinalUrl = CheckForSiteRootRedirect(result.PortalAlias.HTTPAlias, redirectPath); - redirected = true; + result.FinalUrl = url; + result.Reason = RedirectReason.Host_Portal_Used; + result.Action = ActionType.Redirect302Now; + } } } } - return redirected; - } + // double check to make sure we still have the correct alias now that all other information is known (ie tab, portal, culture) + // 770 : redirect alias based on tab id when custom alias used + if (result.TabId == -1 && result.Action == ActionType.CheckFor301 && + result.Reason == RedirectReason.Custom_Tab_Alias) + { + // here because the portal alias matched, but no tab was found, and because there are custom tab aliases used for this portal + // need to redirect back to the chosen portal alias and keep the current path. + string wrongAlias = result.HttpAlias; // it's a valid alias, but only for certain tabs + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(result.PortalId).ToList(); + if (primaryAliases != null && result.PortalId > -1) + { + // going to look for the correct alias based on the culture of the request + string requestCultureCode = result.CultureCode; - private static string StripDebugParameter(string url) - { - return AumDebugRegex.Replace(url, string.Empty); - } + // if that didn't work use the default language of the portal + if (requestCultureCode == null) + { + // this might end up in a double redirect if the path of the Url is for a specific language as opposed + // to a path belonging to the default language domain + PortalInfo portal = PortalController.Instance.GetPortal(result.PortalId); + if (portal != null) + { + requestCultureCode = portal.DefaultLanguage; + } + } - private static bool CheckFor301RedirectExclusion(int tabId, int portalId, bool checkBaseUrls, out TabInfo tab, FriendlyUrlSettings settings) - { - bool doRedirect = false; - tab = TabController.Instance.GetTab(tabId, portalId, false); + // now that the culture code is known, look up the correct portal alias for this portalid/culture code + var cpa = primaryAliases.GetAliasByPortalIdAndSettings(result.PortalId, result, requestCultureCode, settings); + if (cpa != null) + { + // if an alias was found that matches the request and the culture code, then run with that + string rightAlias = cpa.HTTPAlias; - // don't redirect unless allowed, the tab is valid, and it's not an admin or super tab - if (tab != null && tab.IsSuperTab == false && !tab.DoNotRedirect) + // will cause a redirect to the primary portal alias - we know now that there was no custom alias tab + // found, so it's just a plain wrong alias + ConfigurePortalAliasRedirect(ref result, wrongAlias, rightAlias, true, + settings.InternalAliasList, settings); + } + } + } + else { - if (checkBaseUrls) + // then check to make sure it's the chosen portal alias for this portal + // 627 : don't do it if we're redirecting to the host portal + if (result.RedirectAllowed && result.Reason != RedirectReason.Host_Portal_Used) { - // no redirect for friendly url purposes if the tab is in the 'base friendly urls' section - doRedirect = !RewriteController.IsExcludedFromFriendlyUrls(tab, settings, true); + string primaryAlias; + + // checking again in case the rewriting operation changed the values for the valid portal alias + bool incorrectAlias = this.IsPortalAliasIncorrect(context, request, requestUri, result, queryStringCol, settings, parentTraceId, out primaryAlias); + if (incorrectAlias) + { + RedirectPortalAlias(primaryAlias, ref result, settings); + } } - else + } + + // check to see if we have to avoid the core 302 redirect for the portal alias that is in the /defualt.aspx + // for child portals + // exception to that is when a custom alias is used but no rewrite has taken place + if (result.DoRewrite == false && (result.Action == ActionType.Continue + || + (result.Action == ActionType.CheckFor301 && + result.Reason == RedirectReason.Custom_Tab_Alias))) + { + string aliasQuerystring; + bool isChildAliasRootUrl = CheckForChildPortalRootUrl(requestUri.AbsoluteUri, result, out aliasQuerystring); + if (isChildAliasRootUrl) { - doRedirect = true; + RewriteAsChildAliasRoot(context, result, aliasQuerystring, settings); } } - - 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) + private void SecurityCheck(HttpApplication app) { - // 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 + "/"; + HttpRequest request = app.Request; + HttpServerUtility server = app.Server; - // get everything up to the end of the portal alias - destUrl = destUrl.Substring(0, destUrl.IndexOf(aliasPlusSlash, StringComparison.Ordinal) + aliasPlusSlash.Length); + // 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"); } - - return destUrl; } } } diff --git a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs index 688693413a4..50b89f60d34 100644 --- a/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs +++ b/DNN Platform/Library/Entities/Urls/BasicFriendlyUrlProvider.cs @@ -60,6 +60,16 @@ internal override string FriendlyUrl(TabInfo tab, string path, string pageName) 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); + } + + internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) + { + return this.FriendlyUrl(tab, path, pageName, portalAlias, null); + } + /// ----------------------------------------------------------------------------- /// /// AddPage adds the page to the friendly url. @@ -304,16 +314,6 @@ private Dictionary GetQueryStringDictionary(string path) return results; } - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings) - { - return this.FriendlyUrl(tab, path, pageName, ((PortalSettings)settings)?.PortalAlias.HTTPAlias, settings); - } - - internal override string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias) - { - return this.FriendlyUrl(tab, path, pageName, portalAlias, null); - } - private string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias, IPortalSettings portalSettings) { string friendlyPath = path; diff --git a/DNN Platform/Library/Entities/Urls/CacheController.cs b/DNN Platform/Library/Entities/Urls/CacheController.cs index b961049b907..313e87b0052 100644 --- a/DNN Platform/Library/Entities/Urls/CacheController.cs +++ b/DNN Platform/Library/Entities/Urls/CacheController.cs @@ -22,13 +22,10 @@ namespace DotNetNuke.Entities.Urls public class CacheController { - internal const string VanityUrlLookupKey = "url_VanityUrlLookup_{0}"; - + 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 UrlDictKey = "url_UrlDict"; private const string UrlPortalsKey = "url_UrlPortals"; private const string CustomAliasTabsKey = "url_CustomAliasTabsKey"; @@ -46,7 +43,10 @@ public class CacheController private const string AlwaysCallProviderTabsKey = "url_AlwaysCallProviderTabs_{0}"; private const string HomePageSkinsKey = "url_HomePageSkins_{0}"; private const string TabPathsKey = "url_TabPathsKey_{0}"; - + private static CacheItemRemovedReason cacheItemRemovedReason; + private static bool LogRemovedReason; + private CacheItemRemovedCallback onRemovePageIndex; + public static void FlushFriendlyUrlSettingsFromCache() { DataCache.RemoveCache(FriendlyUrlSettingsKey); @@ -63,7 +63,181 @@ public static void FlushPageIndexFromCache() DataCache.RemoveCache(PortalAliasesKey); DataCache.RemoveCache(TabPathsKey); } - + + /// + /// Returns a portal info object for the portal. + /// + /// + /// + /// This method wraps the PortalController.GetPortal method, and adds a check if the reuslt is null.. + /// + public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) + { + PortalInfo pi = null; + + // 775 : change to use threadsafe dictionary + SharedDictionary portals = (SharedDictionary)DataCache.GetCache(PortalsKey) ?? + new SharedDictionary(); + + using (portals.GetWriteLock()) + { + if (portals.ContainsKey(portalId)) + { + // portal found, return + pi = portals[portalId]; + } + else + { + try + { + // if not found, get from database + pi = PortalController.Instance.GetPortal(portalId); + + if (pi == null) + { + // Home page redirect loop when using default language not en-US and first request with secondary language + // calls get portal using culture code to support + string cultureCode = PortalController.GetActivePortalLanguage(portalId); + pi = PortalController.Instance.GetPortal(portalId, cultureCode); + } + + if (pi != null) + { + // Home page redirect loop when using default language not en-US and first request with secondary language + // check for correct, default language code in portal object + string portalCultureCode = pi.CultureCode; + if (portalCultureCode != null && + string.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0) + { + // portal culture code and default culture code are not the same. + // this means we will get the incorrect home page tab id + // call back and get the correct one as per the default language + PortalInfo defaultLangPortal = PortalController.Instance.GetPortal(portalId, pi.DefaultLanguage); + if (defaultLangPortal != null) + { + pi = defaultLangPortal; + } + } + } + + if (pi != null) + { + // add to dictionary and re-store in cache + portals.Add(pi.PortalID, pi); + DataCache.SetCache(PortalsKey, portals); // store back in dictionary + } + } + + // ReSharper disable EmptyGeneralCatchClause + catch + + // ReSharper restore EmptyGeneralCatchClause + { + // 912: capture as fall back any exception resulting from doing a portal lookup in 6.x + // this happens when portalId = -1 + // no long, no handling, just passonwards with null portal + } + } + } + + if (exceptionOnNull && pi == null) + { + throw new NullReferenceException("No Portal Found for portalid : " + portalId.ToString()); + } + + return pi; + } + + public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason r) + { + cacheItemRemovedReason = r; +#if DEBUG + if (LogRemovedReason) + { + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + + string itemName; + string count; + List portalCounts = null; + switch (k) + { + case "DNN_" + PageIndexKey: + itemName = "Page Index"; + + // user profile actions + try + { + DataCache.RemoveCache(UserProfileActionsKey); + } + catch (ConfigurationErrorsException) + { + // do nothing, this means the web.config file was overwritten, and thus the cache + // was cleared. + } + + if (v != null && v.GetType() == typeof(SharedDictionary)) + { + count = "Item Count: " + ((SharedDictionary)v).Values.Count.ToString(); + } + else + { + count = "N/a"; + } + + break; + case "DNN_" + UrlDictKey: + itemName = "Friendly Url List"; + if (v != null && + v.GetType() == typeof(SharedDictionary>)) + { + var friendlyUrls = (SharedDictionary>)v; + portalCounts = new List(); + using (friendlyUrls.GetReadLock()) + { + count = "Portal Count: " + friendlyUrls.Count.ToString(); + foreach (int key in friendlyUrls.Keys) + { + SharedDictionary portalUrls = friendlyUrls[key]; + using (portalUrls.GetReadLock()) + { + portalCounts.Add("Portal " + key.ToString() + " Item Count :" + portalUrls.Count.ToString()); + } + } + } + } + else + { + count = "N/a"; + } + + break; + default: + itemName = "Url Rewriter Cache Item"; + count = string.Empty; + break; + } + + // add log values + log.AddProperty("Url Rewriting Caching Message", itemName + " Cache item Removed."); + log.AddProperty("Reason", cacheItemRemovedReason.ToString()); + log.AddProperty("Cache Item Key", k); + log.AddProperty("Item Count", count); + if (portalCounts != null) + { + int i = 0; + foreach (string item in portalCounts) + { + log.AddProperty("Item " + i.ToString(), item); + i++; + } + } + + // System.Diagnostics.Trace.Assert(k != null, "k == " + k); + LogController.Instance.AddLog(log); + } +#endif + } + /// /// Finds the best match friendlyurlparms.config file path. /// @@ -93,7 +267,7 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool { filePath = rootPath + fileName; // just the pathname } - + if (File.Exists(filePath)) { result = filePath; @@ -120,7 +294,7 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool } } } - + if (string.IsNullOrEmpty(result)) { // nothing matching found : now just looking for the root path @@ -132,7 +306,7 @@ internal static string FindFriendlyUrlParmsConfigFilePath(int portalId, out bool } } } - + return result; } @@ -145,167 +319,57 @@ internal static List GetAlwaysCallProviderTabs(int portalId) { result = new List(tabIdsToAlwaysCall); } - + return result; } - - private static CacheDependency GetPortalsCacheDependency() + + // 770 : customised portal alias per-tab + internal static List GetCustomAliasesFromCache() { - var keys = new List { "DNN_PortalDictionary" }; - var portalsDepedency = new CacheDependency(null, keys.ToArray()); - return portalsDepedency; + object raw = DataCache.GetCache(CustomPortalAliasesKey); + return (raw != null) ? (List)raw : null; } - private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) + internal static void ClearCustomAliasesCache() { - SetPageCache(key, value, null, settings, null); + DataCache.ClearCache(CustomPortalAliasesKey); } - private static void SetPageCache(string key, object value, DNNCacheDependency dependency, FriendlyUrlSettings settings, CacheItemRemovedCallback callback) + internal static Hashtable GetHomePageSkinsFromCache(int portalId) { - DateTime absoluteExpiration = DateTime.Now.Add(settings.CacheTime); - DataCache.SetCache( - key, - value, - dependency, - absoluteExpiration, - Cache.NoSlidingExpiration, - CacheItemPriority.AboveNormal, - callback); + string key = string.Format(HomePageSkinsKey, portalId); + var result = (Hashtable)DataCache.GetCache(key); + return result; } - private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) + internal static List GetListOfTabsWithProviders(int portalId, FriendlyUrlSettings settings) { - 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) + List result = null; + string key = string.Format(PortalModuleProviderTabsKey, portalId); + var tabIdsForPortal = (int[])DataCache.GetCache(key); + if (tabIdsForPortal != null) { - keys.AddRange(portalKeys); + result = new List(tabIdsForPortal); } - - var tabsDependency = new CacheDependency(null, keys.ToArray()); - return tabsDependency; + + return result; } - private static void SetPortalCache(string key, object value, FriendlyUrlSettings settings) + internal static Dictionary> GetParameterRedirects(FriendlyUrlSettings settings, int portalId, ref List messages) { - var absoluteExpiration = DateTime.Now.Add(new TimeSpan(24, 0, 0)); - if (settings != null) + string redirectActionKey = string.Format(RedirectActionsKey, portalId); // cached one portal at a time + if (messages == null) { - absoluteExpiration = DateTime.Now.Add(settings.CacheTime); + messages = new List(); } - - // 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() - { - object raw = DataCache.GetCache(CustomPortalAliasesKey); - return (raw != null) ? (List)raw : null; - } - - 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. - /// - /// - /// - /// - /// - /// - internal void GetFriendlyUrlIndexFromCache( - out SharedDictionary> urlDict, - out ConcurrentBag urlPortals, - out SharedDictionary customAliasTabs) - { - urlDict = null; - urlPortals = null; - customAliasTabs = null; - object rawDict = DataCache.GetCache(UrlDictKey); // contains a dictionary of tabs for all portals - object rawPortals = DataCache.GetCache(UrlPortalsKey); - - // contains a list of portals for which we have retrieved the tabs - object rawCustomAliasTabs = DataCache.GetCache(CustomAliasTabsKey); - - // contains a dictionary of tabs with custom aliases, for all portals - if (rawDict != null) - { - urlDict = (SharedDictionary>)rawDict; - } - - if (rawPortals != null) - { - urlPortals = (ConcurrentBag)rawPortals; - } - - if (rawCustomAliasTabs != null) - { - customAliasTabs = (SharedDictionary)rawCustomAliasTabs; - } - } - - internal static Dictionary> GetParameterRedirects(FriendlyUrlSettings settings, int portalId, ref List messages) - { - string redirectActionKey = string.Format(RedirectActionsKey, portalId); // cached one portal at a time - if (messages == null) - { - messages = new List(); - } - - var redirectActions = (Dictionary>)DataCache.GetCache(redirectActionKey); - if (redirectActions == null) + + var redirectActions = (Dictionary>)DataCache.GetCache(redirectActionKey); + if (redirectActions == null) { try { redirectActions = new Dictionary>(); - + // 807 : look for portal specific files bool portalSpecific; string fileName = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); @@ -313,7 +377,7 @@ internal static Dictionary> GetParameterRedir { redirectActions.LoadFromXmlFile(fileName, portalId, portalSpecific, ref messages); } - + CacheDependency fileDependency = null; if (File.Exists(fileName)) { @@ -337,7 +401,7 @@ internal static Dictionary> GetParameterRedir messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } - + return redirectActions; } @@ -349,7 +413,7 @@ internal static Dictionary> GetParameterReplac { messages = new List(); } - + if (replaceActions == null) { replaceActions = new Dictionary>(); @@ -361,7 +425,7 @@ internal static Dictionary> GetParameterReplac { replaceActions.LoadFromXmlFile(fileName, portalId, portalSpecific, ref messages); } - + CacheDependency cacheDependency = null; if (replaceActions.Count > 0) { @@ -378,27 +442,8 @@ internal static Dictionary> GetParameterReplac messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } - - 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; - } + return replaceActions; } internal static Dictionary> GetParameterRewrites(int portalId, ref List messages, Guid parentTraceId) @@ -408,7 +453,7 @@ internal static Dictionary> GetParameter { messages = new List(); } - + var rewriteActions = (Dictionary>)DataCache.GetCache(rewriteActionKey); if (rewriteActions == null) { @@ -416,14 +461,14 @@ internal static Dictionary> GetParameter { rewriteActions = new Dictionary>(); bool portalSpecific; - + // 807 : new change to look for portal rule files in portal specific locations string filename = FindFriendlyUrlParmsConfigFilePath(portalId, out portalSpecific); if (!string.IsNullOrEmpty(filename)) { rewriteActions.LoadFromXmlFile(filename, portalId, portalSpecific, ref messages); } - + CacheDependency fileDependency = null; if (File.Exists(filename)) { @@ -438,7 +483,7 @@ internal static Dictionary> GetParameter messages.Add("Exception: " + ex.Message + "\n" + ex.StackTrace); } } - + return rewriteActions; } @@ -448,7 +493,7 @@ internal static OrderedDictionary GetPortalAliasesFromCache() return (raw != null) ? (OrderedDictionary)raw : null; } - internal static List GetProvidersForTabAndPortal( + internal static List GetProvidersForTabAndPortal( int tabId, int portalId, FriendlyUrlSettings settings, @@ -496,11 +541,11 @@ internal static List GetProvidersForTabAndPortal( { allCachedProviders = new List(); } - + allCachedProviders.AddRange(cachedTabProviders); } } - + return allCachedProviders; } @@ -561,7 +606,7 @@ internal static void StoreListOfTabsWithProviders(List pro providersWithTabsStr.Add("AllTabs"); } } - + if (provider.AlwaysUsesDnnPagePath(portalId) == false) { if (providersWithTabs.Contains(RewriteController.SiteRootRewrite) == false) @@ -570,7 +615,7 @@ internal static void StoreListOfTabsWithProviders(List pro providersWithTabsStr.Add("NoPath"); } } - + foreach (int providerTabId in provider.ProviderConfig.TabIds) { if (providersWithTabs.Contains(providerTabId) == false) @@ -596,68 +641,14 @@ 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 string allTabsKey = string.Format(PortalModuleProvidersAllTabsKey, portalId); - + // get the providers that are on all tabs var allTabsProviders = new List(); - + // holds all providers, indexed by tabId var tabsProviders = new Dictionary>(); var tabIdStr = new List(); @@ -686,24 +677,24 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett tabIdStr.Add(tabId.ToString()); } } - + providerCount++; } - + // store the list of providers where the provider might be called with no valid TabId, because // the provider allows for Urls with no DNN Page path, which means the TabId can't be identified // by the Url Rewriter. This identifies the Provider as using a 'siteRootRewrite' if (provider.AlwaysUsesDnnPagePath(portalId) == false) { List noPathProviders; - + // add this one if (tabsProviders.ContainsKey(RewriteController.SiteRootRewrite)) { noPathProviders = tabsProviders[RewriteController.SiteRootRewrite]; noPathProviders.Add(provider); tabsProviders[RewriteController.SiteRootRewrite] = noPathProviders; - + // assign back to position in tabs } else @@ -714,13 +705,13 @@ internal static void StoreModuleProvidersForPortal(int portalId, FriendlyUrlSett } } } - + // now add the two collections to the cache if (allTabsProviders.Count > 0) { SetPageCache(allTabsKey, allTabsProviders, settings); } - + if (tabsProviders.Count > 0) { foreach (int tabId in tabsProviders.Keys) @@ -750,41 +741,153 @@ internal static void StorePortalAliasesInCache(OrderedDictionary aliasList, Frie { SetPortalCache(PortalAliasesKey, aliasList, settings); } - - internal void StorePageIndexInCache( - SharedDictionary tabDictionary, - SharedDictionary portalDepthInfo, - FriendlyUrlSettings settings, - string reason) + + /// + /// Retrieve the Url Dictionary for the installation. + /// + /// + /// + /// + /// + /// + internal void GetFriendlyUrlIndexFromCache( + out SharedDictionary> urlDict, + out ConcurrentBag urlPortals, + out SharedDictionary customAliasTabs) { - this.onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback)this.RemovedPageIndexCallBack : null; + urlDict = null; + urlPortals = null; + customAliasTabs = null; + object rawDict = DataCache.GetCache(UrlDictKey); // contains a dictionary of tabs for all portals + object rawPortals = DataCache.GetCache(UrlPortalsKey); - // get list of portal ids for the portals we are storing in the page index - var portalIds = new List(); - using (portalDepthInfo.GetReadLock()) + // contains a list of portals for which we have retrieved the tabs + object rawCustomAliasTabs = DataCache.GetCache(CustomAliasTabsKey); + + // contains a dictionary of tabs with custom aliases, for all portals + if (rawDict != null) { - portalIds.AddRange(portalDepthInfo.Keys); + urlDict = (SharedDictionary>)rawDict; } - // 783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex. - SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(this.GetTabsCacheDependency(portalIds)), settings, this.onRemovePageIndex); - - SetPageCache(PageIndexDepthKey, portalDepthInfo, settings); - - LogRemovedReason = settings.LogCacheMessages; + if (rawPortals != null) + { + urlPortals = (ConcurrentBag)rawPortals; + } - if (settings.LogCacheMessages) + if (rawCustomAliasTabs != null) { - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + customAliasTabs = (SharedDictionary)rawCustomAliasTabs; + } + } - log.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache"); + 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; + } + } + + /// + /// 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 void StorePageIndexInCache( + SharedDictionary tabDictionary, + SharedDictionary portalDepthInfo, + FriendlyUrlSettings settings, + string reason) + { + this.onRemovePageIndex = settings.LogCacheMessages ? (CacheItemRemovedCallback)this.RemovedPageIndexCallBack : null; + + // get list of portal ids for the portals we are storing in the page index + var portalIds = new List(); + using (portalDepthInfo.GetReadLock()) + { + portalIds.AddRange(portalDepthInfo.Keys); + } + + // 783 : use cache dependency to manage page index instead of triggerDictionaryRebuild regex. + SetPageCache(PageIndexKey, tabDictionary, new DNNCacheDependency(this.GetTabsCacheDependency(portalIds)), settings, this.onRemovePageIndex); + + SetPageCache(PageIndexDepthKey, portalDepthInfo, settings); + + LogRemovedReason = settings.LogCacheMessages; + + if (settings.LogCacheMessages) + { + var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; + + log.AddProperty("Url Rewriting Caching Message", "Page Index built and Stored in Cache"); log.AddProperty("Reason", reason); log.AddProperty("Cache Item Key", PageIndexKey); using (tabDictionary.GetReadLock()) { log.AddProperty("Item Count", tabDictionary.Count.ToString()); } - + log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); LogController.Instance.AddLog(log); } @@ -792,186 +895,83 @@ internal void StorePageIndexInCache( internal void StoreTabPathsInCache(int portalId, SharedDictionary tabPathDictionary, FriendlyUrlSettings settings) { - SetPageCache( + SetPageCache( string.Format(TabPathsKey, portalId), tabPathDictionary, new DNNCacheDependency(this.GetTabsCacheDependency(new List { portalId })), settings, null); - } + } - /// - /// Returns a portal info object for the portal. - /// - /// - /// - /// This method wraps the PortalController.GetPortal method, and adds a check if the reuslt is null.. - /// - public static PortalInfo GetPortal(int portalId, bool exceptionOnNull) + private static CacheDependency GetPortalsCacheDependency() { - PortalInfo pi = null; - - // 775 : change to use threadsafe dictionary - SharedDictionary portals = (SharedDictionary)DataCache.GetCache(PortalsKey) ?? - new SharedDictionary(); + var keys = new List { "DNN_PortalDictionary" }; + var portalsDepedency = new CacheDependency(null, keys.ToArray()); + return portalsDepedency; + } - using (portals.GetWriteLock()) - { - if (portals.ContainsKey(portalId)) - { - // portal found, return - pi = portals[portalId]; - } - else - { - try - { - // if not found, get from database - pi = PortalController.Instance.GetPortal(portalId); + private static void SetPageCache(string key, object value, FriendlyUrlSettings settings) + { + SetPageCache(key, value, null, settings, null); + } - if (pi == null) - { - // Home page redirect loop when using default language not en-US and first request with secondary language - // calls get portal using culture code to support - string cultureCode = PortalController.GetActivePortalLanguage(portalId); - pi = PortalController.Instance.GetPortal(portalId, cultureCode); - } - - if (pi != null) - { - // Home page redirect loop when using default language not en-US and first request with secondary language - // check for correct, default language code in portal object - string portalCultureCode = pi.CultureCode; - if (portalCultureCode != null && - string.CompareOrdinal(portalCultureCode, pi.DefaultLanguage) != 0) - { - // portal culture code and default culture code are not the same. - // this means we will get the incorrect home page tab id - // call back and get the correct one as per the default language - PortalInfo defaultLangPortal = PortalController.Instance.GetPortal(portalId, pi.DefaultLanguage); - if (defaultLangPortal != null) - { - pi = defaultLangPortal; - } - } - } - - if (pi != null) - { - // add to dictionary and re-store in cache - portals.Add(pi.PortalID, pi); - DataCache.SetCache(PortalsKey, portals); // store back in dictionary - } - } - - // ReSharper disable EmptyGeneralCatchClause - catch - - // ReSharper restore EmptyGeneralCatchClause - { - // 912: capture as fall back any exception resulting from doing a portal lookup in 6.x - // this happens when portalId = -1 - // no long, no handling, just passonwards with null portal - } - } + 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 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); } - if (exceptionOnNull && pi == null) + // 857 : use cache dependency for portal alias cache + if (settings != null) { - throw new NullReferenceException("No Portal Found for portalid : " + portalId.ToString()); + DataCache.SetCache( + key, + value, + new DNNCacheDependency(GetPortalsCacheDependency()), + absoluteExpiration, + Cache.NoSlidingExpiration); + } + else + { + DataCache.SetCache(key, value, absoluteExpiration); } - - return pi; } - public void RemovedPageIndexCallBack(string k, object v, CacheItemRemovedReason r) + private CacheDependency GetTabsCacheDependency(IEnumerable portalIds) { - cacheItemRemovedReason = r; -#if DEBUG - if (LogRemovedReason) + var keys = new List(); + foreach (int portalId in portalIds) { - var log = new LogInfo { LogTypeKey = "HOST_ALERT" }; - - string itemName; - string count; - List portalCounts = null; - switch (k) - { - case "DNN_" + PageIndexKey: - itemName = "Page Index"; - - // user profile actions - try - { - DataCache.RemoveCache(UserProfileActionsKey); - } - catch (ConfigurationErrorsException) - { - // do nothing, this means the web.config file was overwritten, and thus the cache - // was cleared. - } - - if (v != null && v.GetType() == typeof(SharedDictionary)) - { - count = "Item Count: " + ((SharedDictionary)v).Values.Count.ToString(); - } - else - { - count = "N/a"; - } + const string cacheKey = DataCache.TabCacheKey; + string key = string.Format(cacheKey, portalId); + key = "DNN_" + key; // add on the DNN_ prefix + keys.Add(key); + } - break; - case "DNN_" + UrlDictKey: - itemName = "Friendly Url List"; - if (v != null && - v.GetType() == typeof(SharedDictionary>)) - { - var friendlyUrls = (SharedDictionary>)v; - portalCounts = new List(); - using (friendlyUrls.GetReadLock()) - { - count = "Portal Count: " + friendlyUrls.Count.ToString(); - foreach (int key in friendlyUrls.Keys) - { - SharedDictionary portalUrls = friendlyUrls[key]; - using (portalUrls.GetReadLock()) - { - portalCounts.Add("Portal " + key.ToString() + " Item Count :" + portalUrls.Count.ToString()); - } - } - } - } - else - { - count = "N/a"; - } - - break; - default: - itemName = "Url Rewriter Cache Item"; - count = string.Empty; - break; - } - - // add log values - log.AddProperty("Url Rewriting Caching Message", itemName + " Cache item Removed."); - log.AddProperty("Reason", cacheItemRemovedReason.ToString()); - log.AddProperty("Cache Item Key", k); - log.AddProperty("Item Count", count); - if (portalCounts != null) - { - int i = 0; - foreach (string item in portalCounts) - { - log.AddProperty("Item " + i.ToString(), item); - i++; - } - } - - // System.Diagnostics.Trace.Assert(k != null, "k == " + k); - LogController.Instance.AddLog(log); + // get the portals list dependency + var portalKeys = new List(); + if (portalKeys.Count > 0) + { + keys.AddRange(portalKeys); } -#endif - } + + var tabsDependency = new CacheDependency(null, keys.ToArray()); + return tabsDependency; + } } } diff --git a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs index ad8f266b654..342f5157ee3 100644 --- a/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs +++ b/DNN Platform/Library/Entities/Urls/CollectionExtensions.cs @@ -19,7 +19,7 @@ public static void LoadFromXmlFile(this Dictionary(); if (File.Exists(fileName)) { @@ -42,7 +42,7 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } - + tabActionCol.Add(action); actionCount++; @@ -85,14 +85,14 @@ public static void LoadFromXmlFile(this Dictionary(); } - + if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName) @@ -133,22 +133,22 @@ public static void LoadFromXmlFile(this Dictionary(); int actionCount = 0; - + // now set up the action string portalIdRaw = rdr.GetAttribute("rulePortalId"); if (string.IsNullOrEmpty(portalIdRaw)) { portalIdRaw = rdr.GetAttribute("portalId"); } - + int rulePortalId = -1; if (portalIdRaw != null) { int.TryParse(portalIdRaw, out rulePortalId); } - + if (rulePortalId == portalId || rulePortalId == -1 || portalSpecific) - + // if portal specific, all rules are assumed to belong to the portal { string tabIdRaw = rdr.GetAttribute("tabIds"); @@ -188,12 +188,12 @@ public static void LoadFromXmlFile(this Dictionary tabActionCol; if (actions.ContainsKey(action.TabId)) { @@ -204,27 +204,27 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } - + tabActionCol.Add(action); actionCount++; } - + messages.Add(name + " redirect actions added:" + actionCount.ToString()); } - + if (tabMessages.Count > 0) { messages.AddRange(tabMessages); } } - + break; case XmlNodeType.EndElement: break; } } - + rdr.Close(); } } @@ -235,7 +235,7 @@ public static void LoadFromXmlFile(this Dictionary(); } - + if (File.Exists(fileName)) { var rdr = new XmlTextReader(fileName) @@ -257,7 +257,7 @@ public static void LoadFromXmlFile(this Dictionary(); actions.Add(action.TabId, tabActionCol); } - + tabActionCol.Add(action); actionCount++; } - + messages.Add(name + " rewrite actions added:" + actionCount.ToString()); } } - + break; case XmlNodeType.EndElement: break; } } - + rdr.Close(); } else diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs index c0d73733e95..9d3d94c21a2 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterConfiguration.cs @@ -28,7 +28,7 @@ public RewriterRuleCollection Rules { return this._rules; } - + set { this._rules = value; @@ -58,14 +58,14 @@ 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); } - + if (File.Exists(filePath)) { // Set back into Cache @@ -93,7 +93,7 @@ public static RewriterConfiguration GetConfig() fileReader.Close(); } } - + return config; } @@ -113,7 +113,7 @@ public static void SaveConfig(RewriterRuleCollection rules) // make sure file is not read-only File.SetAttributes(filePath, FileAttributes.Normal); } - + using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var writer = new StreamWriter(fileWriter)) { diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs index f303f84c881..6944ab7ac8c 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterRule.cs @@ -10,20 +10,20 @@ namespace DotNetNuke.Entities.Urls.Config [Serializable] public class RewriterRule - { - [NonSerialized] - private Regex _matchRx; - - private string _lookFor; - private string _sendTo; - + { + [NonSerialized] + private Regex _matchRx; + + private string _lookFor; + private string _sendTo; + public string LookFor { get { return this._lookFor; } - + set { if (this._lookFor != value) @@ -32,27 +32,27 @@ public string LookFor this._matchRx = null; } } - } - + } + public string SendTo { get { return this._sendTo; } - + set { 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 + } + + // 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( + RegexUtils.GetCachedRegex( "^" + RewriterUtils.ResolveUrl(applicationPath, this.LookFor) + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)); } diff --git a/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs b/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs index b15a49f476e..eb872637f0e 100644 --- a/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs +++ b/DNN Platform/Library/Entities/Urls/Config/RewriterRuleCollection.cs @@ -15,7 +15,7 @@ public virtual RewriterRule this[int index] { return (RewriterRule)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs index cdbc03c5243..65a7fb9e78a 100644 --- a/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs +++ b/DNN Platform/Library/Entities/Urls/CustomUrlDictController.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Entities.Urls using DotNetNuke.Services.Localization; internal static class CustomUrlDictController - { + { /// /// returns a tabId indexed dictionary of Friendly Urls. /// @@ -25,7 +25,7 @@ internal static class CustomUrlDictController /// /// /// - internal static SharedDictionary> FetchCustomUrlDictionary( + internal static SharedDictionary> FetchCustomUrlDictionary( int portalId, bool forceRebuild, bool bypassCache, @@ -34,10 +34,10 @@ internal static SharedDictionary> FetchCus 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); @@ -45,7 +45,7 @@ internal static SharedDictionary> FetchCus 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(); @@ -60,7 +60,7 @@ internal static SharedDictionary> FetchCus urlDict = BuildUrlDictionary(urlDict, portalId, settings, ref customAliasForTabs); urlPortals.Add(portalId); - cc.StoreFriendlyUrlIndexInCache( + cc.StoreFriendlyUrlIndexInCache( urlDict, urlPortals, customAliasForTabs, settings, @@ -79,15 +79,15 @@ internal static SharedDictionary> FetchCus 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 @@ -102,7 +102,7 @@ internal static void InvalidateDictionary() /// only one culture for the Url, it will be that culture. /// /// - private static SharedDictionary> BuildUrlDictionary( + private static SharedDictionary> BuildUrlDictionary( SharedDictionary> existingTabs, int portalId, FriendlyUrlSettings settings, @@ -114,12 +114,12 @@ private static SharedDictionary> BuildUrlD { existingTabs = new SharedDictionary>(); } - + if (customAliasTabs == null) { customAliasTabs = new SharedDictionary(); } - + // go through each tab in the found list foreach (TabInfo tab in tabs.Values) { @@ -141,7 +141,7 @@ private static SharedDictionary> BuildUrlD if (redirect.HttpStatus == "200") { string url = redirect.Url; - + // 770 : add in custom alias into the tab path for the custom Urls if (redirect.PortalAliasUsage != PortalAliasUsageType.Default && redirect.PortalAliasId > 0) { @@ -153,7 +153,7 @@ private static SharedDictionary> BuildUrlD url = customHttpAlias + "::" + url; } } - + string cultureKey = redirect.CultureCode.ToLowerInvariant(); var locales = LocaleController.Instance.GetLocales(portalId).Values; if (string.IsNullOrEmpty(cultureKey)) @@ -171,10 +171,10 @@ private static SharedDictionary> BuildUrlD } } } - + return existingTabs; - } - + } + private static void AddEntryToDictionary(SharedDictionary> existingTabs, int portalId, TabInfo tab, string cultureKey, string url) { int tabid = tab.TabID; @@ -187,14 +187,14 @@ private static void AddEntryToDictionary(SharedDictionary entry = existingTabs[tabid]; - + // replace tab if existing but was retreieved from tabs call if (tab.PortalID == portalId || portalId == -1) { @@ -211,6 +211,6 @@ private static void AddEntryToDictionary(SharedDictionary /// 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). @@ -30,7 +30,7 @@ public abstract class ExtensionUrlProvider /// /// 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); @@ -47,7 +47,7 @@ public abstract class ExtensionUrlProvider /// 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( + public abstract string ChangeFriendlyUrl( TabInfo tab, string friendlyUrlPath, FriendlyUrlOptions options, @@ -55,62 +55,7 @@ public abstract string ChangeFriendlyUrl( ref string endingPageName, out bool useDnnPagePath, ref List messages); - - protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options) - { - bool changed; - string result = options != null - ? FriendlyUrlController.CleanNameForUrl(urlValue, options, out changed) - : FriendlyUrlController.CleanNameForUrl(urlValue, null, out changed); - - return result; - } - protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options, out bool replacedUnwantedChars) - { - return FriendlyUrlController.CleanNameForUrl(urlValue, options, out replacedUnwantedChars); - } - - protected string CreateQueryStringFromParameters(string[] urlParms, int skipUpToPosition) - { - string result = string.Empty; - int i = 0; - bool odd = true; - int size = urlParms.GetUpperBound(0) - skipUpToPosition; - if (size >= 0 && urlParms.GetUpperBound(0) >= 0) - { - var qs = new StringBuilder(urlParms.GetUpperBound(0)); - foreach (string urlPathPart in urlParms) - { - if (i > skipUpToPosition) // skip over the parts we don't want - { - if (odd) - { - qs.Append("&" + urlPathPart); - } - else - { - qs.Append("=" + urlPathPart); - } - - // switch odd/even - odd = !odd; - } - - i++; - } - - result = qs.ToString(); - } - - return result; - } - - protected string EnsureLeadingChar(string leading, string path) - { - return FriendlyUrlController.EnsureLeadingChar(leading, path); - } - /// /// /// @@ -121,7 +66,7 @@ protected string EnsureLeadingChar(string leading, string path) /// /// /// - public abstract bool CheckForRedirect( + public abstract bool CheckForRedirect( int tabId, int portalid, string httpAlias, @@ -152,7 +97,7 @@ public abstract bool CheckForRedirect( /// Warning: It's unwise to do a specific database lookup for each call of this method. This method needs to be high-performance so should use a stateless method (ie, regex parse) or, if looking up database values, cached hashtables or thread-safe dictionaries. /// /// Querystring value in key=value format, which will be used as an input to the rewriting function. - public abstract string TransformFriendlyUrlToQueryString( + public abstract string TransformFriendlyUrlToQueryString( string[] urlParms, int tabId, int portalId, FriendlyUrlOptions options, @@ -160,8 +105,8 @@ public abstract string TransformFriendlyUrlToQueryString( PortalAliasInfo portalAlias, ref List messages, out int status, - out string location); - + out string location); + /// /// This method is called to check whether to do a Url Rewrite on all Tabs specified by the provider. /// @@ -177,6 +122,61 @@ public virtual bool AlwaysCallForRewrite(int portalId) public string EnsureNotLeadingChar(string leading, string path) { return FriendlyUrlController.EnsureNotLeadingChar(leading, path); - } + } + + protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options) + { + bool changed; + string result = options != null + ? FriendlyUrlController.CleanNameForUrl(urlValue, options, out changed) + : FriendlyUrlController.CleanNameForUrl(urlValue, null, out changed); + + return result; + } + + protected string CleanNameForUrl(string urlValue, FriendlyUrlOptions options, out bool replacedUnwantedChars) + { + return FriendlyUrlController.CleanNameForUrl(urlValue, options, out replacedUnwantedChars); + } + + protected string CreateQueryStringFromParameters(string[] urlParms, int skipUpToPosition) + { + string result = string.Empty; + int i = 0; + bool odd = true; + int size = urlParms.GetUpperBound(0) - skipUpToPosition; + if (size >= 0 && urlParms.GetUpperBound(0) >= 0) + { + var qs = new StringBuilder(urlParms.GetUpperBound(0)); + foreach (string urlPathPart in urlParms) + { + if (i > skipUpToPosition) // skip over the parts we don't want + { + if (odd) + { + qs.Append("&" + urlPathPart); + } + else + { + qs.Append("=" + urlPathPart); + } + + // switch odd/even + odd = !odd; + } + + i++; + } + + result = qs.ToString(); + } + + return result; + } + + protected string EnsureLeadingChar(string leading, string path) + { + return FriendlyUrlController.EnsureLeadingChar(leading, path); + } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs index cc2cadf9d66..a37cbb3e079 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderController.cs @@ -26,10 +26,11 @@ namespace DotNetNuke.Entities.Urls public class ExtensionUrlProviderController { private static readonly object providersBuildLock = new object(); - private static readonly Regex RewrittenUrlRegex = new Regex( + + private static readonly Regex RewrittenUrlRegex = new Regex( @"(?(?:\?|&)tabid=\d+)(?&[^=]+=[^&]*)*", - RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); + public static void DeleteProvider(ExtensionUrlProviderInfo urlProvider) { DataProvider.Instance().DeleteExtensionUrlProvider(urlProvider.ExtensionUrlProviderId); @@ -41,7 +42,256 @@ public static void DisableProvider(int providerId, int portalId) DataProvider.Instance().UpdateExtensionUrlProvider(providerId, false); ClearCache(portalId); } - + + public static void EnableProvider(int providerId, int portalId) + { + DataProvider.Instance().UpdateExtensionUrlProvider(providerId, true); + ClearCache(portalId); + } + + public static List GetProviders(int portalId) + { + return CBO.FillCollection(DataProvider.Instance().GetExtensionUrlProviders(portalId)); + } + + /// + /// Loads the module providers. + /// + /// + /// + /// Note : similar copy for UI purposes in ConfigurationController.cs. + public static List GetModuleProviders(int portalId) + { + var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + var moduleProviders = CBO.GetCachedObject>( + new CacheItemArgs( + cacheKey, + 60, + CacheItemPriority.High, + portalId), + c => + { + var id = (int)c.Params[0]; + IDataReader dr = DataProvider.Instance().GetExtensionUrlProviders(id); + try + { + var providers = new List(); + var providerConfigs = CBO.FillCollection(dr, new List(), false); + + foreach (var providerConfig in providerConfigs) + { + var providerType = Reflection.CreateType(providerConfig.ProviderType); + if (providerType == null) + { + continue; + } + + var provider = Reflection.CreateObject(providerType) as ExtensionUrlProvider; + if (provider == null) + { + continue; + } + + provider.ProviderConfig = providerConfig; + provider.ProviderConfig.PortalId = id; + providers.Add(provider); + } + + if (dr.NextResult()) + { + // Setup Settings + while (dr.Read()) + { + var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); + var key = Null.SetNullString(dr["SettingName"]); + var value = Null.SetNullString(dr["SettingValue"]); + + var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); + if (provider != null) + { + provider.ProviderConfig.Settings[key] = value; + } + } + } + + if (dr.NextResult()) + { + // Setup Tabs + while (dr.Read()) + { + var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); + var tabId = Null.SetNullInteger(dr["TabID"]); + + var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); + if (provider != null && !provider.ProviderConfig.TabIds.Contains(tabId)) + { + provider.ProviderConfig.TabIds.Add(tabId); + } + } + } + + return providers; + } + finally + { + // Close reader + CBO.CloseDataReader(dr, true); + } + }); + + return moduleProviders; + } + + public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings settings) + { + return 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 : settings.PageExtension, + }; + } + + /// + /// logs an exception related to a module provider once per cache-lifetime. + /// + /// + /// + /// + /// + /// + public static void LogModuleProviderExceptionInRequest(Exception ex, string status, + ExtensionUrlProvider provider, + UrlAction result, + List messages) + { + if (ex != null) + { + string moduleProviderName = "Unknown Provider"; + string moduleProviderVersion = "Unknown Version"; + if (provider != null) + { + moduleProviderName = provider.ProviderConfig.ProviderName; + moduleProviderVersion = provider.GetType().Assembly.GetName(false).Version.ToString(); + } + + // this logic prevents a site logging an exception for every request made. Instead + // the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. + // create a cache key for this exception type + string cacheKey = ex.GetType().ToString(); + + // see if there is an existing object logged for this exception type + object existingEx = DataCache.GetCache(cacheKey); + if (existingEx == null) + { + // if there was no existing object logged for this exception type, this is a new exception + DateTime expire = DateTime.Now.AddHours(1); + DataCache.SetCache(cacheKey, cacheKey, expire); + + // just store the cache key - it doesn't really matter + // create a log event + string productVer = DotNetNukeContext.Current.Application.Version.ToString(); + var log = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; + log.AddProperty( + "Url Rewriting Extension Url Provider Exception", + "Exception in Url Rewriting Process"); + log.AddProperty("Provider Name", moduleProviderName); + log.AddProperty("Provider Version", moduleProviderVersion); + log.AddProperty("Http Status", status); + log.AddProperty("Product Version", productVer); + if (result != null) + { + log.AddProperty("Original Path", result.OriginalPath ?? "null"); + log.AddProperty("Raw Url", result.RawUrl ?? "null"); + log.AddProperty("Final Url", result.FinalUrl ?? "null"); + + log.AddProperty("Rewrite Result", !string.IsNullOrEmpty(result.RewritePath) + ? result.RewritePath + : "[no rewrite]"); + log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) + ? "[no redirect]" + : result.FinalUrl); + log.AddProperty("Action", result.Action.ToString()); + log.AddProperty("Reason", result.Reason.ToString()); + log.AddProperty("Portal Id", result.PortalId.ToString()); + log.AddProperty("Tab Id", result.TabId.ToString()); + log.AddProperty("Http Alias", result.PortalAlias != null ? result.PortalAlias.HTTPAlias : "Null"); + + if (result.DebugMessages != null) + { + int i = 1; + foreach (string debugMessage in result.DebugMessages) + { + string msg = debugMessage; + if (debugMessage == null) + { + msg = "[message was null]"; + } + + log.AddProperty("Debug Message[result] " + i.ToString(), msg); + i++; + } + } + } + else + { + log.AddProperty("Result", "Result value null"); + } + + if (messages != null) + { + int i = 1; + foreach (string msg in messages) + { + log.AddProperty("Debug Message[raw] " + i.ToString(), msg); + i++; + } + } + + log.AddProperty("Exception Type", ex.GetType().ToString()); + log.AddProperty("Message", ex.Message); + log.AddProperty("Stack Trace", ex.StackTrace); + if (ex.InnerException != null) + { + log.AddProperty("Inner Exception Message", ex.InnerException.Message); + log.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); + } + + log.BypassBuffering = true; + LogController.Instance.AddLog(log); + } + } + } + + public static void SaveProvider(ExtensionUrlProviderInfo provider) + { + provider.ExtensionUrlProviderId = DataProvider.Instance().AddExtensionUrlProvider( + provider.ExtensionUrlProviderId, + provider.DesktopModuleId, + provider.ProviderName, + provider.ProviderType, + provider.SettingsControlSrc, + provider.IsActive, + provider.RewriteAllUrls, + provider.RedirectAllUrls, + provider.ReplaceAllUrls); + } + + public static void SaveSetting(int providerId, int portalId, string settingName, string settingValue) + { + DataProvider.Instance().SaveExtensionUrlProviderSetting(providerId, portalId, settingName, settingValue); + ClearCache(portalId); + } + /// /// Checks to see if any providers are marked as 'always call for rewrites'. /// @@ -57,7 +307,7 @@ internal static bool CheckForAlwaysCallProviders(int portalId, int tabId, Friend if (alwaysCallTabids == null) { alwaysCallTabids = new List(); // create new list - + // nothing in cache, build list List providers = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); foreach (ExtensionUrlProvider provider in providers) @@ -84,20 +334,20 @@ internal static bool CheckForAlwaysCallProviders(int portalId, int tabId, Friend } } } - + // now store back in cache CacheController.StoreAlwaysCallProviderTabs(portalId, alwaysCallTabids, settings); } - + if (alwaysCallTabids.Contains(tabId) || alwaysCallTabids.Contains(RewriteController.AllTabsRewrite)) { checkForAlwaysCallResult = true; } - + return checkForAlwaysCallResult; } - internal static bool CheckForRedirect( + internal static bool CheckForRedirect( Uri requestUri, UrlAction result, NameValueCollection queryStringCol, @@ -135,7 +385,7 @@ internal static bool CheckForRedirect( { // log module provider exception LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, result, messages); - + // return defaults redirected = false; location = string.Empty; @@ -144,88 +394,15 @@ internal static bool CheckForRedirect( { providerName = activeProvider.ProviderConfig.ProviderName; } - + if (result != null) { result.DebugMessages.Add("Exception in provider [" + providerName + "] :" + ex.Message); } } - - 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); + return redirected; } - - /// - /// 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). @@ -238,8 +415,8 @@ internal static bool CheckForSiteRootRewrite(int portalId, FriendlyUrlSettings s // list should have returned all providers with site root rewrite, but double check here in case of faulty third-party logic return providers.Any(provider => provider.AlwaysUsesDnnPagePath(portalId) == false); } - - internal static bool GetUrlFromExtensionUrlProviders( + + internal static bool GetUrlFromExtensionUrlProviders( int portalId, TabInfo tab, FriendlyUrlSettings settings, @@ -259,7 +436,7 @@ internal static bool GetUrlFromExtensionUrlProviders( { messages = new List(); } - + try { List providersToCall = GetProvidersToCall(tab.TabID, portalId, settings, @@ -269,9 +446,9 @@ internal static bool GetUrlFromExtensionUrlProviders( { activeProvider = provider; // keep for exception purposes bool useDnnPagePath; - + // go through and call each provider to generate the friendly urls for the module - string customPath = provider.ChangeFriendlyUrl( + string customPath = provider.ChangeFriendlyUrl( tab, friendlyUrlPath, options, @@ -284,7 +461,7 @@ internal static bool GetUrlFromExtensionUrlProviders( { endingPageName = Globals.glbDefaultPage; // set back to default.aspx if provider cleared it } - + // now check to see if a change was made or not. Don't trust the provider. if (!string.IsNullOrEmpty(customPath)) { @@ -304,17 +481,17 @@ internal static bool GetUrlFromExtensionUrlProviders( catch (Exception ex) { LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, null, messages); - + // reset all values to defaults wasChanged = false; changedPath = friendlyUrlPath; changeToSiteRoot = false; } - + return wasChanged; } - internal static bool TransformFriendlyUrlPath( + internal static bool TransformFriendlyUrlPath( string newUrl, string tabKeyVal, string[] urlParms, @@ -337,8 +514,8 @@ internal static bool TransformFriendlyUrlPath( { tabId = RewriteController.SiteRootRewrite; } - - List providersToCall = GetProvidersToCall( + + List providersToCall = GetProvidersToCall( tabId, result.PortalId, settings, @@ -347,7 +524,7 @@ internal static bool TransformFriendlyUrlPath( { // now check for providers by calling the providers int upperBound = urlParms.GetUpperBound(0); - + // clean extension off parameters array var parms = new string[upperBound + 1]; Array.ConstrainedCopy(urlParms, 0, parms, 0, upperBound + 1); @@ -356,18 +533,18 @@ internal static bool TransformFriendlyUrlPath( bool replaced; parms[upperBound] = RewriteController.CleanExtension(parms[upperBound], settings, out replaced); } - + // get options from current settings FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); foreach (ExtensionUrlProvider provider in providersToCall) { // set active provider for exception handling activeProvider = provider; - + // call down to specific providers and see if we get a rewrite string location; int status; - string queryString = provider.TransformFriendlyUrlToQueryString( + string queryString = provider.TransformFriendlyUrlToQueryString( parms, result.TabId, result.PortalId, @@ -382,7 +559,7 @@ internal static bool TransformFriendlyUrlPath( if (!string.IsNullOrEmpty(queryString) && queryString != newUrl) { rewriteDone = true; - + // check for duplicate tabIds. string qsRemainder = null; if (Regex.IsMatch(queryString, @"tabid=\d+", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) @@ -396,11 +573,11 @@ internal static bool TransformFriendlyUrlPath( // keep any other querystring remainders qsRemainder = rewrittenUrlMatch.Groups["qs"].Captures.Cast().Aggregate(string.Empty, (current, qsCapture) => current + qsCapture.Value); // initialise } - + // supplied value overwrites existing value, so remove from the rewritten url rewrittenUrl = RewrittenUrlRegex.Replace(rewrittenUrl, string.Empty); } - + if (rewrittenUrl.Contains("?") == false) { // use a leading ?, not a leading & @@ -420,7 +597,7 @@ internal static bool TransformFriendlyUrlPath( { rewrittenUrl += qsRemainder; } - + break; } } @@ -445,7 +622,7 @@ internal static bool TransformFriendlyUrlPath( result.Action = ActionType.Output500; break; } - + newAction = true; // not doing a 200 status break; } @@ -456,7 +633,7 @@ internal static bool TransformFriendlyUrlPath( { // log module provider exception LogModuleProviderExceptionInRequest(ex, "500 Internal Server Error", activeProvider, result, messages); - + // reset values to initial rewriteDone = false; rewrittenUrl = newUrl; @@ -466,263 +643,87 @@ internal static bool TransformFriendlyUrlPath( { providerName = activeProvider.ProviderConfig.ProviderName; } - + if (result != null) { result.DebugMessages.Add("Exception in provider [" + providerName + "] :" + ex.Message); } } - + return rewriteDone; - } + } - public static void EnableProvider(int providerId, int portalId) + private static void ClearCache() { - DataProvider.Instance().UpdateExtensionUrlProvider(providerId, true); - ClearCache(portalId); + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + ClearCache(portal.PortalID); + } } - public static List GetProviders(int portalId) + private static void ClearCache(int portalId) { - return CBO.FillCollection(DataProvider.Instance().GetExtensionUrlProviders(portalId)); + var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); + DataCache.RemoveCache(cacheKey); } /// - /// Loads the module providers. + /// Returns the providers to call. Returns tabid matches first, and any portal id matches after that. /// + /// /// + /// + /// /// - /// Note : similar copy for UI purposes in ConfigurationController.cs. - public static List GetModuleProviders(int portalId) + private static List GetProvidersToCall( + int tabId, + int portalId, + FriendlyUrlSettings settings, + Guid parentTraceId) { - var cacheKey = string.Format("ExtensionUrlProviders_{0}", portalId); - var moduleProviders = CBO.GetCachedObject>( - new CacheItemArgs( - cacheKey, - 60, - CacheItemPriority.High, - portalId), - c => - { - var id = (int)c.Params[0]; - IDataReader dr = DataProvider.Instance().GetExtensionUrlProviders(id); - try - { - var providers = new List(); - var providerConfigs = CBO.FillCollection(dr, new List(), false); - - foreach (var providerConfig in providerConfigs) - { - var providerType = Reflection.CreateType(providerConfig.ProviderType); - if (providerType == null) - { - continue; - } - - var provider = Reflection.CreateObject(providerType) as ExtensionUrlProvider; - if (provider == null) - { - continue; - } - - provider.ProviderConfig = providerConfig; - provider.ProviderConfig.PortalId = id; - providers.Add(provider); - } - - if (dr.NextResult()) - { - // Setup Settings - while (dr.Read()) - { - var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); - var key = Null.SetNullString(dr["SettingName"]); - var value = Null.SetNullString(dr["SettingValue"]); - - var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); - if (provider != null) - { - provider.ProviderConfig.Settings[key] = value; - } - } - } - - if (dr.NextResult()) - { - // Setup Tabs - while (dr.Read()) - { - var extensionUrlProviderId = Null.SetNullInteger(dr["ExtensionUrlProviderID"]); - var tabId = Null.SetNullInteger(dr["TabID"]); - - var provider = providers.SingleOrDefault(p => p.ProviderConfig.ExtensionUrlProviderId == extensionUrlProviderId); - if (provider != null && !provider.ProviderConfig.TabIds.Contains(tabId)) - { - provider.ProviderConfig.TabIds.Add(tabId); - } - } - } - - return providers; - } - finally - { - // Close reader - CBO.CloseDataReader(dr, true); - } - }); - - return moduleProviders; - } + List providers; - public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings settings) - { - return new FriendlyUrlOptions + // 887 : introduce lockable code to prevent caching race errors + lock (providersBuildLock) { - 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 : settings.PageExtension, - }; - } + bool definitelyNoProvider; - /// - /// logs an exception related to a module provider once per cache-lifetime. - /// - /// - /// - /// - /// - /// - public static void LogModuleProviderExceptionInRequest(Exception ex, string status, - ExtensionUrlProvider provider, - UrlAction result, - List messages) - { - if (ex != null) - { - string moduleProviderName = "Unknown Provider"; - string moduleProviderVersion = "Unknown Version"; - if (provider != null) - { - moduleProviderName = provider.ProviderConfig.ProviderName; - moduleProviderVersion = provider.GetType().Assembly.GetName(false).Version.ToString(); - } - - // this logic prevents a site logging an exception for every request made. Instead - // the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. - // create a cache key for this exception type - string cacheKey = ex.GetType().ToString(); - - // see if there is an existing object logged for this exception type - object existingEx = DataCache.GetCache(cacheKey); - if (existingEx == null) + // 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 { - // if there was no existing object logged for this exception type, this is a new exception - DateTime expire = DateTime.Now.AddHours(1); - DataCache.SetCache(cacheKey, cacheKey, expire); - - // just store the cache key - it doesn't really matter - // create a log event - string productVer = DotNetNukeContext.Current.Application.Version.ToString(); - var log = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; - log.AddProperty( - "Url Rewriting Extension Url Provider Exception", - "Exception in Url Rewriting Process"); - log.AddProperty("Provider Name", moduleProviderName); - log.AddProperty("Provider Version", moduleProviderVersion); - log.AddProperty("Http Status", status); - log.AddProperty("Product Version", productVer); - if (result != null) - { - log.AddProperty("Original Path", result.OriginalPath ?? "null"); - log.AddProperty("Raw Url", result.RawUrl ?? "null"); - log.AddProperty("Final Url", result.FinalUrl ?? "null"); + // get all providers for the portal + var allProviders = GetModuleProviders(portalId).Where(p => p.ProviderConfig.IsActive).ToList(); - log.AddProperty("Rewrite Result", !string.IsNullOrEmpty(result.RewritePath) - ? result.RewritePath - : "[no rewrite]"); - log.AddProperty("Redirect Location", string.IsNullOrEmpty(result.FinalUrl) - ? "[no redirect]" - : result.FinalUrl); - log.AddProperty("Action", result.Action.ToString()); - log.AddProperty("Reason", result.Reason.ToString()); - log.AddProperty("Portal Id", result.PortalId.ToString()); - log.AddProperty("Tab Id", result.TabId.ToString()); - log.AddProperty("Http Alias", result.PortalAlias != null ? result.PortalAlias.HTTPAlias : "Null"); + // store the list of tabs for this portal that have a provider attached + CacheController.StoreListOfTabsWithProviders(allProviders, portalId, settings); - if (result.DebugMessages != null) - { - int i = 1; - foreach (string debugMessage in result.DebugMessages) - { - string msg = debugMessage; - if (debugMessage == null) - { - msg = "[message was null]"; - } - - log.AddProperty("Debug Message[result] " + i.ToString(), msg); - i++; - } - } - } - else - { - log.AddProperty("Result", "Result value null"); - } - - if (messages != null) - { - int i = 1; - foreach (string msg in messages) - { - log.AddProperty("Debug Message[raw] " + i.ToString(), msg); - i++; - } - } - - log.AddProperty("Exception Type", ex.GetType().ToString()); - log.AddProperty("Message", ex.Message); - log.AddProperty("Stack Trace", ex.StackTrace); - if (ex.InnerException != null) + // 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) { - log.AddProperty("Inner Exception Message", ex.InnerException.Message); - log.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); + // find if a module is specific to a tab + providersToCall = new List(); + providersToCall.AddRange(allProviders); } - - log.BypassBuffering = true; - LogController.Instance.AddLog(log); } + + // always return an instantiated provider collection + providers = providersToCall ?? new List(); } - } - public static void SaveProvider(ExtensionUrlProviderInfo provider) - { - provider.ExtensionUrlProviderId = DataProvider.Instance().AddExtensionUrlProvider( - provider.ExtensionUrlProviderId, - provider.DesktopModuleId, - provider.ProviderName, - provider.ProviderType, - provider.SettingsControlSrc, - provider.IsActive, - provider.RewriteAllUrls, - provider.RedirectAllUrls, - provider.ReplaceAllUrls); + // return the collection of module providers + return providers; } - - public static void SaveSetting(int providerId, int portalId, string settingName, string settingValue) - { - DataProvider.Instance().SaveExtensionUrlProviderSetting(providerId, portalId, settingName, settingValue); - ClearCache(portalId); - } } } diff --git a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs index 917e61a1dc8..c9ffb52ec5f 100644 --- a/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs +++ b/DNN Platform/Library/Entities/Urls/ExtensionUrlProviderInfo.cs @@ -24,10 +24,10 @@ public ExtensionUrlProviderInfo() /// /// Gets a value indicating whether when true, the module provider will be used for all tabs in the current portal. Including a specific tabid switches value to false. /// - public bool AllTabs - { - get { return this.TabIds.Count == 0; } - } + public bool AllTabs + { + get { return this.TabIds.Count == 0; } + } /// /// Gets or sets the DesktopModuleId is used to associate a particular Extension Url Provider with a specific DotNetNuke extension. diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs index e78a517aa02..a5b4cb3202b 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlController.cs @@ -828,6 +828,92 @@ public static string EnsureLeadingChar(string leading, string path) return path; } + public static string EnsureNotLeadingChar(string leading, string path) + { + if (leading != null && path != null + && leading.Length <= path.Length && leading != string.Empty) + { + string start = path.Substring(0, leading.Length); + if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) == 0) + { + // matches start, take leading off + path = path.Substring(leading.Length); + } + } + + return path; + } + + // 737 : detect mobile and other types of browsers + public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse response, FriendlyUrlSettings settings) + { + var browserType = BrowserTypes.Normal; + if (request != null && settings != null) + { + bool isCookieSet = false; + bool isMobile = false; + if (CanUseMobileDevice(request, response)) + { + HttpCookie viewMobileCookie = response.Cookies[MobileViewSiteCookieName]; + if (viewMobileCookie != null && bool.TryParse(viewMobileCookie.Value, out isMobile)) + { + isCookieSet = true; + } + + if (isMobile == false) + { + if (!isCookieSet) + { + isMobile = IsMobileClient(); + if (isMobile) + { + browserType = BrowserTypes.Mobile; + } + + // Store the result as a cookie. + if (viewMobileCookie == null) + { + response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) + { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); + } + else + { + viewMobileCookie.Value = isMobile.ToString(); + } + } + } + else + { + browserType = BrowserTypes.Mobile; + } + } + } + + return browserType; + } + + public static string ValidateUrl(string cleanUrl, int validateUrlForTabId, PortalSettings settings, out bool modified) + { + modified = false; + bool isUnique; + var uniqueUrl = cleanUrl; + int counter = 0; + do + { + if (counter > 0) + { + uniqueUrl = uniqueUrl + counter.ToString(CultureInfo.InvariantCulture); + modified = true; + } + + isUnique = ValidateUrl(uniqueUrl, validateUrlForTabId, settings); + counter++; + } + while (!isUnique); + + return uniqueUrl; + } + internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) { var canUseMobileDevice = true; @@ -917,8 +1003,7 @@ private static void CheckIllegalChars(string illegalChars, ref string ch, ref bo ch = resultingCh.ToString(); } - private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, - ref bool replacedUnwantedChars) + private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, ref bool replacedUnwantedChars) { if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) { @@ -939,92 +1024,6 @@ private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string } } - public static string EnsureNotLeadingChar(string leading, string path) - { - if (leading != null && path != null - && leading.Length <= path.Length && leading != string.Empty) - { - string start = path.Substring(0, leading.Length); - if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) == 0) - { - // matches start, take leading off - path = path.Substring(leading.Length); - } - } - - return path; - } - - // 737 : detect mobile and other types of browsers - public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse response, FriendlyUrlSettings settings) - { - var browserType = BrowserTypes.Normal; - if (request != null && settings != null) - { - bool isCookieSet = false; - bool isMobile = false; - if (CanUseMobileDevice(request, response)) - { - HttpCookie viewMobileCookie = response.Cookies[MobileViewSiteCookieName]; - if (viewMobileCookie != null && bool.TryParse(viewMobileCookie.Value, out isMobile)) - { - isCookieSet = true; - } - - if (isMobile == false) - { - if (!isCookieSet) - { - isMobile = IsMobileClient(); - if (isMobile) - { - browserType = BrowserTypes.Mobile; - } - - // Store the result as a cookie. - if (viewMobileCookie == null) - { - response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) - { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); - } - else - { - viewMobileCookie.Value = isMobile.ToString(); - } - } - } - else - { - browserType = BrowserTypes.Mobile; - } - } - } - - return browserType; - } - - public static string ValidateUrl(string cleanUrl, int validateUrlForTabId, PortalSettings settings, out bool modified) - { - modified = false; - bool isUnique; - var uniqueUrl = cleanUrl; - int counter = 0; - do - { - if (counter > 0) - { - uniqueUrl = uniqueUrl + counter.ToString(CultureInfo.InvariantCulture); - modified = true; - } - - isUnique = ValidateUrl(uniqueUrl, validateUrlForTabId, settings); - counter++; - } - while (!isUnique); - - return uniqueUrl; - } - private static bool ValidateUrl(string url, int validateUrlForTabId, PortalSettings settings) { // Try and get a user by the url diff --git a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs index a8642a0335a..64ceca2339a 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlOptions.cs @@ -17,19 +17,18 @@ public class FriendlyUrlOptions { 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; - + // 922 : change to use regexMatch pattern for allowable characters public string RegexMatch; public Dictionary ReplaceCharWithChar = new Dictionary(); public string ReplaceChars; public bool ReplaceDoubleChars; public string SpaceEncoding; + private static readonly object _regexLookupLock = new object(); + private static readonly Dictionary _regexLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); public bool CanGenerateNonStandardPath { @@ -62,17 +61,17 @@ public Regex RegexMatchRegex 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, + 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 4f575f0b74a..4fdad7585c7 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlPathController.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Entities.Urls using DotNetNuke.Entities.Users; internal class FriendlyUrlPathController - { + { /// /// This method checks the list of rules for parameter replacement and modifies the parameter path accordingly. /// @@ -26,7 +26,7 @@ internal class FriendlyUrlPathController /// /// /// - internal static bool CheckParameterRegexReplacement( + internal static bool CheckParameterRegexReplacement( string parameterPath, TabInfo tab, FriendlyUrlSettings settings, @@ -64,12 +64,12 @@ internal static bool CheckParameterRegexReplacement( { parmReplaces = new List(); } - + // add in the all replaces List allReplaces = replaceActions[-1]; parmReplaces.AddRange(allReplaces); // add the 'all' range to the tab range } - + if (parmReplaces != null) { // OK what we have now is a list of replaces for the currently requested tab (either because it was specified by tab id, @@ -79,7 +79,7 @@ internal static bool CheckParameterRegexReplacement( foreach (ParameterReplaceAction parmReplace in parmReplaces) { // do a regex on the 'lookFor' in the parameter path - var parmRegex = RegexUtils.GetCachedRegex( + var parmRegex = RegexUtils.GetCachedRegex( parmReplace.LookFor, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); if (parmRegex.IsMatch(parameterPath)) @@ -87,13 +87,13 @@ internal static bool CheckParameterRegexReplacement( replacedPath = parmRegex.Replace(parameterPath, parmReplace.ReplaceWith); messages.Add(parmReplace.Name + " replace rule match, replaced : " + parameterPath + " with: " + replacedPath); replaced = true; - + // 593: if this replacement is marked as a site root replacement, we will be // removing the page path from the final url changeToSiteRoot = parmReplace.ChangeToSiteRoot; break; } - + messages.Add(parmReplace.Name + " replace rule not matched {" + parameterPath + "}"); } } @@ -106,11 +106,11 @@ internal static bool CheckParameterRegexReplacement( } } } - + return replaced; } - internal static bool CheckUserProfileReplacement( + internal static bool CheckUserProfileReplacement( string newPath, TabInfo tab, PortalSettings portalSettings, @@ -126,7 +126,7 @@ internal static bool CheckUserProfileReplacement( { meessages = new List(); } - + bool urlWasChanged = false; // initialise defaults to always return valid items @@ -141,10 +141,10 @@ internal static bool CheckUserProfileReplacement( { int userId; string rawUserId, remainingPath; - + // split the userid and other profile parameters from the friendly url path, // and return the userid and remaining parts as separate items - SplitUserIdFromFriendlyUrlPath( + SplitUserIdFromFriendlyUrlPath( newPath, "UserId", string.Empty, @@ -199,9 +199,9 @@ internal static bool CheckUserProfileReplacement( } } } - + changedPath = "/" + urlName; - + // append any extra remaining path value to the end if (!string.IsNullOrEmpty(remainingPath)) { @@ -214,11 +214,11 @@ internal static bool CheckUserProfileReplacement( changedPath += remainingPath; } } - + urlWasChanged = true; changeToSiteRoot = true; // we will be doing domain.com/urlname allowOtherParameters = false; - + // can't have any others (wouldn't have matched in the regex if there were) } else @@ -227,10 +227,10 @@ internal static bool CheckUserProfileReplacement( } } } - + return urlWasChanged; - } - + } + /// /// Splits out the userid value from the supplied Friendly Url Path. /// @@ -239,7 +239,7 @@ internal static bool CheckUserProfileReplacement( /// /// The remaining path not associated with the user id. /// - private static void SplitUserIdFromFriendlyUrlPath( + private static void SplitUserIdFromFriendlyUrlPath( string urlPath, string parmName, string otherParametersPath, @@ -250,7 +250,7 @@ private static void SplitUserIdFromFriendlyUrlPath( 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)) { @@ -259,7 +259,7 @@ private static void SplitUserIdFromFriendlyUrlPath( { 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); @@ -269,7 +269,7 @@ private static void SplitUserIdFromFriendlyUrlPath( 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) @@ -294,23 +294,23 @@ private static void SplitUserIdFromFriendlyUrlPath( 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) @@ -328,12 +328,12 @@ private static void SplitUserIdFromFriendlyUrlPath( 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 b28facf2d3e..15ce466a1de 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlProviderBase.cs @@ -34,7 +34,7 @@ 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 1e16d3da195..6a247b3ecbd 100644 --- a/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs +++ b/DNN Platform/Library/Entities/Urls/FriendlyUrlSettings.cs @@ -11,11 +11,55 @@ namespace DotNetNuke.Entities.Urls [Serializable] public class FriendlyUrlSettings - { + { public const string ReplaceSpaceWithNothing = "None"; public const string SpaceEncodingPlus = "+"; public const string SpaceEncodingHex = "%20"; - + + // Settings Keys + public const string DeletedTabHandlingTypeSetting = "AUM_DeletedTabHandlingType"; + public const string ForceLowerCaseSetting = "AUM_ForceLowerCase"; + public const string PageExtensionSetting = "AUM_PageExtension"; + public const string PageExtensionUsageSetting = "AUM_PageExtensionUsage"; + public const string RedirectOldProfileUrlSetting = "AUM_RedirectOldProfileUrl"; + public const string RedirectUnfriendlySetting = "AUM_RedirectUnfriendly"; + public const string ReplaceSpaceWithSetting = "AUM_ReplaceSpaceWith"; + public const string UrlFormatSetting = "AUM_UrlFormat"; + public const string RedirectMixedCaseSetting = "AUM_RedirectMixedCase"; + public const string SpaceEncodingValueSetting = "AUM_SpaceEncodingValue"; + public const string AutoAsciiConvertSetting = "AUM_AutoAsciiConvert"; + public const string ReplaceCharsSetting = "AUM_ReplaceChars"; + public const string CheckForDuplicatedUrlsSetting = "AUM_CheckForDuplicatedUrls"; + public const string FriendlyAdminHostUrlsSetting = "AUM_FriendlyAdminHostUrls"; + public const string EnableCustomProvidersSetting = "AUM_EnableCustomProviders"; + public const string ReplaceCharWithCharSetting = "AUM_ReplaceCharWithChar"; + public const string IgnoreRegexSetting = "AUM_IgnoreUrlRegex"; + public const string SiteUrlsOnlyRegexSetting = "AUM_SiteUrlsOnlyRegex"; + public const string DoNotRedirectUrlRegexSetting = "AUM_DoNotRedirectUrlRegex"; + public const string DoNotRedirectHttpsUrlRegexSetting = "AUM_DoNotRedirectHttpsUrlRegex"; + public const string PreventLowerCaseUrlRegexSetting = "AUM_PreventLowerCaseUrlRegex"; + public const string DoNotUseFriendlyUrlRegexSetting = "AUM_DoNotUseFriendlyUrlRegex"; + public const string KeepInQueryStringRegexSetting = "AUM_KeepInQueryStringRegex"; + public const string UrlsWithNoExtensionRegexSetting = "AUM_UrlsWithNoExtensionRegex"; + public const string ValidFriendlyUrlRegexSetting = "AUM_ValidFriendlyUrlRegex"; + public const string DoNotRewriteRegExSetting = "AUM_DoNotRewriteRegEx"; + public const string UsePortalDefaultLanguageSetting = "AUM_UsePortalDefaultLanguage"; + public const string AllowDebugCodeSetting = "AUM_AllowDebugCode"; + public const string LogCacheMessagesSetting = "AUM_LogCacheMessages"; + public const string VanityUrlPrefixSetting = "AUM_VanityUrlPrefix"; + public const string RedirectDefaultPageSetting = "AUM_RedirectDefaultPage"; + public const string SslClientRedirectSetting = "AUM_SSLClientRedirect"; + public const string IllegalCharsSetting = "AUM_IllegalChars"; + public const string ReplaceDoubleCharsSetting = "AUM_ReplaceDoubleChars"; + public const string Regex404Setting = "AUM_Regex404"; + public const string Url404Setting = "AUM_Url404"; + public const string Url500Setting = "AUM_Url500"; + public const string UseBaseFriendlyUrlsSetting = "AUM_UseBaseFriendlyUrls"; + public const string InternalAliasesSetting = "AUM_InternalAliases"; + public const string ProcessRequestsSetting = "AUM_ProcessRequests"; + public const string CacheTimeSetting = "AUM_CacheTime"; + public const string IncludePageNameSetting = "AUM_IncludePageName"; + private readonly IHostController _hostControllerInstance = HostController.Instance; // 894 : new switch to disable custom url provider @@ -60,54 +104,8 @@ public class FriendlyUrlSettings private string _vanityUrlPrefix; private TimeSpan? _cacheTime; private List _processRequestList; - private Dictionary _replaceCharacterDictionary; - - internal List PortalValues { get; private set; } + private Dictionary _replaceCharacterDictionary; - // Settings Keys - public const string DeletedTabHandlingTypeSetting = "AUM_DeletedTabHandlingType"; - public const string ForceLowerCaseSetting = "AUM_ForceLowerCase"; - public const string PageExtensionSetting = "AUM_PageExtension"; - public const string PageExtensionUsageSetting = "AUM_PageExtensionUsage"; - public const string RedirectOldProfileUrlSetting = "AUM_RedirectOldProfileUrl"; - public const string RedirectUnfriendlySetting = "AUM_RedirectUnfriendly"; - public const string ReplaceSpaceWithSetting = "AUM_ReplaceSpaceWith"; - public const string UrlFormatSetting = "AUM_UrlFormat"; - public const string RedirectMixedCaseSetting = "AUM_RedirectMixedCase"; - public const string SpaceEncodingValueSetting = "AUM_SpaceEncodingValue"; - public const string AutoAsciiConvertSetting = "AUM_AutoAsciiConvert"; - public const string ReplaceCharsSetting = "AUM_ReplaceChars"; - public const string CheckForDuplicatedUrlsSetting = "AUM_CheckForDuplicatedUrls"; - public const string FriendlyAdminHostUrlsSetting = "AUM_FriendlyAdminHostUrls"; - public const string EnableCustomProvidersSetting = "AUM_EnableCustomProviders"; - public const string ReplaceCharWithCharSetting = "AUM_ReplaceCharWithChar"; - public const string IgnoreRegexSetting = "AUM_IgnoreUrlRegex"; - public const string SiteUrlsOnlyRegexSetting = "AUM_SiteUrlsOnlyRegex"; - public const string DoNotRedirectUrlRegexSetting = "AUM_DoNotRedirectUrlRegex"; - public const string DoNotRedirectHttpsUrlRegexSetting = "AUM_DoNotRedirectHttpsUrlRegex"; - public const string PreventLowerCaseUrlRegexSetting = "AUM_PreventLowerCaseUrlRegex"; - public const string DoNotUseFriendlyUrlRegexSetting = "AUM_DoNotUseFriendlyUrlRegex"; - public const string KeepInQueryStringRegexSetting = "AUM_KeepInQueryStringRegex"; - public const string UrlsWithNoExtensionRegexSetting = "AUM_UrlsWithNoExtensionRegex"; - public const string ValidFriendlyUrlRegexSetting = "AUM_ValidFriendlyUrlRegex"; - public const string DoNotRewriteRegExSetting = "AUM_DoNotRewriteRegEx"; - public const string UsePortalDefaultLanguageSetting = "AUM_UsePortalDefaultLanguage"; - public const string AllowDebugCodeSetting = "AUM_AllowDebugCode"; - public const string LogCacheMessagesSetting = "AUM_LogCacheMessages"; - public const string VanityUrlPrefixSetting = "AUM_VanityUrlPrefix"; - public const string RedirectDefaultPageSetting = "AUM_RedirectDefaultPage"; - public const string SslClientRedirectSetting = "AUM_SSLClientRedirect"; - public const string IllegalCharsSetting = "AUM_IllegalChars"; - public const string ReplaceDoubleCharsSetting = "AUM_ReplaceDoubleChars"; - public const string Regex404Setting = "AUM_Regex404"; - public const string Url404Setting = "AUM_Url404"; - public const string Url500Setting = "AUM_Url500"; - public const string UseBaseFriendlyUrlsSetting = "AUM_UseBaseFriendlyUrls"; - public const string InternalAliasesSetting = "AUM_InternalAliases"; - public const string ProcessRequestsSetting = "AUM_ProcessRequests"; - public const string CacheTimeSetting = "AUM_CacheTime"; - public const string IncludePageNameSetting = "AUM_IncludePageName"; - public FriendlyUrlSettings(int portalId) { this.PortalId = portalId < -1 ? -1 : portalId; @@ -129,8 +127,6 @@ public FriendlyUrlSettings(int portalId) } } } - - public List InternalAliasList { get; private set; } public List ProcessRequestList { @@ -152,12 +148,6 @@ public List ProcessRequestList } } - public int PortalId { get; private set; } - - public bool IsDirty { get; private set; } - - public bool IsLoading { get; private set; } - public bool AllowDebugCode { get @@ -172,22 +162,6 @@ public bool AllowDebugCode } } - public bool AutoAsciiConvert - { - get - { - if (!this._autoAsciiConvert.HasValue) - { - // urls to be modified in the output html stream - this._autoAsciiConvert = this.GetBooleanSetting(AutoAsciiConvertSetting, false); - } - - return this._autoAsciiConvert.Value; - } - - internal set { this._autoAsciiConvert = value; } - } - public TimeSpan CacheTime { get @@ -196,7 +170,7 @@ public TimeSpan CacheTime { this._cacheTime = new TimeSpan(0, this.GetIntegerSetting(CacheTimeSetting, 1440), 0); } - + return this._cacheTime.Value; } } @@ -210,11 +184,131 @@ public bool CheckForDuplicateUrls // 793 : checkforDupUrls not being read this._checkForDuplicateUrls = this.GetBooleanSetting(CheckForDuplicatedUrlsSetting, true); } - + return this._checkForDuplicateUrls.Value; } } + public DNNPageForwardType ForwardExternalUrlsType + { + get + { + return DNNPageForwardType.Redirect301; + } + } + + public bool EnableCustomProviders + { + get + { + if (!this._enableCustomProviders.HasValue) + { + // 894 : new switch to disable custom providers if necessary + this._enableCustomProviders = this.GetBooleanSetting(EnableCustomProvidersSetting, true); + } + + return this._enableCustomProviders.Value; + } + } + + public string IllegalChars + { + get + { + // 922 : new options for allowing user-configured replacement of characters + return this._illegalChars ?? (this._illegalChars = this.GetStringSetting(IllegalCharsSetting, @"<>/\?:&=+|%#")); + } + } + + public bool LogCacheMessages + { + get + { + if (!this._logCacheMessages.HasValue) + { + this._logCacheMessages = this.GetBooleanSetting(LogCacheMessagesSetting, false); + } + + return this._logCacheMessages.Value; + } + } + + public string Regex404 + { + get { return this._regex404 ?? (this._regex404 = this.GetStringSetting(Regex404Setting, string.Empty)); } + } + + public Dictionary ReplaceCharacterDictionary + { + get + { + if (this._replaceCharacterDictionary == null) + { + var replaceCharwithChar = this.GetStringSetting(ReplaceCharWithCharSetting, string.Empty); + this._replaceCharacterDictionary = CollectionExtensions.CreateDictionaryFromString(replaceCharwithChar == "[]" ? string.Empty : replaceCharwithChar, ';', ','); + } + + return this._replaceCharacterDictionary; + } + } + + public string ReplaceChars + { + get + { + // 922 : new options for allowing user-configured replacement of characters + return this._replaceChars ?? (this._replaceChars = this.GetStringSetting(ReplaceCharsSetting, @" &$+,/?~#<>()¿¡«»!""")); + } + } + + public bool ReplaceDoubleChars + { + get + { + if (!this._replaceDoubleChars.HasValue) + { + // 922 : new options for allowing user-configured replacement of characters + this._replaceDoubleChars = this.GetBooleanSetting(ReplaceDoubleCharsSetting, true); + } + + return this._replaceDoubleChars.Value; + } + } + + public string Url404 + { + get { return this._url404 ?? (this._url404 = this.GetStringSetting(Url404Setting, string.Empty)); } + } + + public string Url500 + { + get { return this._url500 ?? (this._url500 = this.GetStringSetting(Url500Setting, null) ?? this.Url404); } + } + + public List InternalAliasList { get; private set; } + + public int PortalId { get; private set; } + + public bool IsDirty { get; private set; } + + public bool IsLoading { get; private set; } + + public bool AutoAsciiConvert + { + get + { + if (!this._autoAsciiConvert.HasValue) + { + // urls to be modified in the output html stream + this._autoAsciiConvert = this.GetBooleanSetting(AutoAsciiConvertSetting, false); + } + + return this._autoAsciiConvert.Value; + } + + internal set { this._autoAsciiConvert = value; } + } + public DeletedTabHandlingType DeletedTabHandlingType { get @@ -229,7 +323,7 @@ public DeletedTabHandlingType DeletedTabHandlingType ? DeletedTabHandlingType.Do301RedirectToPortalHome : DeletedTabHandlingType.Do404Error; } - + internal set { var newValue = value.ToString(); @@ -245,11 +339,11 @@ public string DoNotIncludeInPathRegex // 742 : was not reading and saving value when 'doNotIncludeInPathRegex' used return this._doNotIncludeInPathRegex ?? (this._doNotIncludeInPathRegex = - this.GetStringSetting( + this.GetStringSetting( KeepInQueryStringRegexSetting, @"/nomo/\d+|/runningDefault/[^/]+|/popup/(?:true|false)|/(?:page|category|sort|tags)/[^/]+|tou/[^/]+|(/utm[^/]+/[^/]+)+")); } - + internal set { this._doNotIncludeInPathRegex = value; } } @@ -258,11 +352,11 @@ public string DoNotRedirectRegex get { // 541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code - return this._doNotRedirectRegex ?? (this._doNotRedirectRegex = this.GetStringSetting( + return this._doNotRedirectRegex ?? (this._doNotRedirectRegex = this.GetStringSetting( DoNotRedirectUrlRegexSetting, @"(\.axd)|/Rss\.aspx|/SiteMap\.aspx|\.ashx|/LinkClick\.aspx|/Providers/|/DesktopModules/|ctl=MobilePreview|/ctl/MobilePreview|/API/")); } - + internal set { this._doNotRedirectRegex = value; } } @@ -273,7 +367,7 @@ public string DoNotRedirectSecureRegex // 541 moved doNotRedirect and doNotRedirectRegex from under 'redirectUnfriendly' code return this._doNotRedirectSecureRegex ?? (this._doNotRedirectSecureRegex = this.GetStringSetting(DoNotRedirectHttpsUrlRegexSetting, string.Empty)); } - + internal set { this._doNotRedirectSecureRegex = value; } } @@ -285,7 +379,7 @@ public string DoNotRewriteRegex (this._doNotRewriteRegex = this.GetStringSetting(DoNotRewriteRegExSetting, @"/DesktopModules/|/Providers/|/LinkClick\.aspx|/profilepic\.ashx|/DnnImageHandler\.ashx|/__browserLink/|/API/")); } - + internal set { this._doNotRewriteRegex = value; } } @@ -297,10 +391,10 @@ public bool ForceLowerCase { this._forceLowerCase = this.GetBooleanSetting(ForceLowerCaseSetting, false); } - + return this._forceLowerCase.Value; } - + internal set { this._forceLowerCase = value; } } @@ -319,19 +413,11 @@ public bool ForcePortalDefaultLanguage // 810 : allow forcing of default language in rewrites this._forcePortalDefaultLanguage = this.GetBooleanSetting(UsePortalDefaultLanguageSetting, true); } - + return this._forcePortalDefaultLanguage.Value; } - - internal set { this._forcePortalDefaultLanguage = value; } - } - public DNNPageForwardType ForwardExternalUrlsType - { - get - { - return DNNPageForwardType.Redirect301; - } + internal set { this._forcePortalDefaultLanguage = value; } } public bool FriendlyAdminHostUrls @@ -342,25 +428,11 @@ public bool FriendlyAdminHostUrls { this._friendlyAdminHostUrls = this.GetBooleanSetting(FriendlyAdminHostUrlsSetting, true); } - + return this._friendlyAdminHostUrls.Value; } - - internal set { this._friendlyAdminHostUrls = value; } - } - public bool EnableCustomProviders - { - get - { - if (!this._enableCustomProviders.HasValue) - { - // 894 : new switch to disable custom providers if necessary - this._enableCustomProviders = this.GetBooleanSetting(EnableCustomProvidersSetting, true); - } - - return this._enableCustomProviders.Value; - } + internal set { this._friendlyAdminHostUrls = value; } } public string IgnoreRegex @@ -369,21 +441,12 @@ public string IgnoreRegex { return this._ignoreRegex ?? (this._ignoreRegex = - this.GetStringSetting( + this.GetStringSetting( IgnoreRegexSetting, @"(?/\?:&=+|%#")); - } + internal set { this._ignoreRegex = value; } } public bool IncludePageName @@ -397,21 +460,8 @@ public bool IncludePageName return this._includePageName.Value; } - - internal set { this._includePageName = value; } - } - public bool LogCacheMessages - { - get - { - if (!this._logCacheMessages.HasValue) - { - this._logCacheMessages = this.GetBooleanSetting(LogCacheMessagesSetting, false); - } - - return this._logCacheMessages.Value; - } + internal set { this._includePageName = value; } } public string NoFriendlyUrlRegex @@ -421,7 +471,7 @@ public string NoFriendlyUrlRegex // 655 : new noFriendlyUrlRegex value to ignore generation of certain urls return this._noFriendlyUrlRegex ?? (this._noFriendlyUrlRegex = this.GetStringSetting(DoNotUseFriendlyUrlRegexSetting, @"/Rss\.aspx")); } - + internal set { this._noFriendlyUrlRegex = value; } } @@ -457,10 +507,10 @@ public PageExtensionUsageType PageExtensionUsageType val = PageExtensionUsageType.Never; break; } - + return val; } - + internal set { var newValue = value.ToString(); @@ -476,10 +526,10 @@ public bool RedirectDefaultPage { this._redirectDefaultPage = this.GetBooleanSetting(RedirectDefaultPageSetting, false); } - + return this._redirectDefaultPage.Value; } - + internal set { this._redirectUnfriendly = value; } } @@ -491,10 +541,10 @@ public bool RedirectOldProfileUrl { this._redirectOldProfileUrl = PortalController.GetPortalSettingAsBoolean(RedirectOldProfileUrlSetting, this.PortalId, true); } - + return this._redirectOldProfileUrl.Value; } - + internal set { this._redirectOldProfileUrl = value; } } @@ -506,10 +556,10 @@ public bool RedirectUnfriendly { this._redirectUnfriendly = this.GetBooleanSetting(RedirectUnfriendlySetting, true); } - + return this._redirectUnfriendly.Value; } - + internal set { this._redirectUnfriendly = value; } } @@ -521,16 +571,11 @@ public bool RedirectWrongCase { this._redirectWrongCase = this.GetBooleanSetting(RedirectMixedCaseSetting, false); } - + return this._redirectWrongCase.Value; } - - internal set { this._redirectWrongCase = value; } - } - public string Regex404 - { - get { return this._regex404 ?? (this._regex404 = this.GetStringSetting(Regex404Setting, string.Empty)); } + internal set { this._redirectWrongCase = value; } } public string RegexMatch @@ -539,43 +584,6 @@ public string RegexMatch internal set { this._regexMatch = value; } } - public Dictionary ReplaceCharacterDictionary - { - get - { - if (this._replaceCharacterDictionary == null) - { - var replaceCharwithChar = this.GetStringSetting(ReplaceCharWithCharSetting, string.Empty); - this._replaceCharacterDictionary = CollectionExtensions.CreateDictionaryFromString(replaceCharwithChar == "[]" ? string.Empty : replaceCharwithChar, ';', ','); - } - - return this._replaceCharacterDictionary; - } - } - - public string ReplaceChars - { - get - { - // 922 : new options for allowing user-configured replacement of characters - return this._replaceChars ?? (this._replaceChars = this.GetStringSetting(ReplaceCharsSetting, @" &$+,/?~#<>()¿¡«»!""")); - } - } - - public bool ReplaceDoubleChars - { - get - { - if (!this._replaceDoubleChars.HasValue) - { - // 922 : new options for allowing user-configured replacement of characters - this._replaceDoubleChars = this.GetBooleanSetting(ReplaceDoubleCharsSetting, true); - } - - return this._replaceDoubleChars.Value; - } - } - public string ReplaceSpaceWith { get @@ -583,7 +591,7 @@ public string ReplaceSpaceWith // 791 : use threadlocking option return this._replaceSpaceWith ?? (this._replaceSpaceWith = this.GetStringSetting(ReplaceSpaceWithSetting, "-")); } - + internal set { this._replaceSpaceWith = value; } } @@ -601,10 +609,10 @@ public bool SSLClientRedirect { this._sslClientRedirect = this.GetBooleanSetting(SslClientRedirectSetting, false); } - + return this._sslClientRedirect.Value; } - + internal set { this._sslClientRedirect = value; } } @@ -612,23 +620,13 @@ public bool SSLClientRedirect public int TabId500 { get; private set; } - public string Url404 - { - get { return this._url404 ?? (this._url404 = this.GetStringSetting(Url404Setting, string.Empty)); } - } - - public string Url500 - { - get { return this._url500 ?? (this._url500 = this.GetStringSetting(Url500Setting, null) ?? this.Url404); } - } - public string UrlFormat { get { return this._urlFormat ?? (this._urlFormat = this.GetStringSetting(UrlFormatSetting, "advanced")); } - + internal set { this._urlFormat = value; } } @@ -644,10 +642,10 @@ public string UseBaseFriendlyUrls this._useBaseFriendlyUrls += ";"; } } - + return this._useBaseFriendlyUrls; } - + internal set { this._useBaseFriendlyUrls = value; } } @@ -657,11 +655,11 @@ public string UseSiteUrlsRegex { return this._useSiteUrlsRegex ?? (this._useSiteUrlsRegex = - this.GetStringSetting( + this.GetStringSetting( SiteUrlsOnlyRegexSetting, @"/rss\.aspx|Telerik.RadUploadProgressHandler\.ashx|BannerClickThrough\.aspx|(?:/[^/]+)*/Tabid/\d+/.*default\.aspx")); } - + internal set { this._useSiteUrlsRegex = value; } } @@ -673,7 +671,7 @@ public string ValidExtensionlessUrlsRegex return this._validExtensionlessUrlsRegex ?? (this._validExtensionlessUrlsRegex = this.GetStringSetting(UrlsWithNoExtensionRegexSetting, @"\.asmx/|\.ashx/|\.svc/|\.aspx/|\.axd/")); } - + internal set { this._validExtensionlessUrlsRegex = value; } } @@ -686,7 +684,7 @@ public string InternalAliases // allow for a list of internal aliases this.InternalAliases = this.GetStringSetting(InternalAliasesSetting, string.Empty); // calls the setter } - + return this._internalAliases; } @@ -701,8 +699,10 @@ public string VanityUrlPrefix { get { return this._vanityUrlPrefix ?? (this._vanityUrlPrefix = this.GetStringSetting(VanityUrlPrefixSetting, "users")); } internal set { this._vanityUrlPrefix = value; } - } - + } + + internal List PortalValues { get; private set; } + private bool GetBooleanSetting(string key, bool defaultValue) { // First Get the Host Value using the passed in value as default @@ -743,7 +743,7 @@ private string GetStringSetting(string key, string defaultValue) } return returnValue; - } + } private void ParseInternalAliases() { @@ -763,6 +763,6 @@ private void ParseInternalAliases() } } } - } + } } } diff --git a/DNN Platform/Library/Entities/Urls/PagingInfo.cs b/DNN Platform/Library/Entities/Urls/PagingInfo.cs index 12cb21a0542..9743aab8742 100644 --- a/DNN Platform/Library/Entities/Urls/PagingInfo.cs +++ b/DNN Platform/Library/Entities/Urls/PagingInfo.cs @@ -15,18 +15,6 @@ public PagingInfo(int pageNumber, int pageSize) this.PageSize = pageSize; } - public int PageNumber { get; private set; } - - public int PageSize { get; private set; } - - public int FirstRow { get; private set; } - - public int LastRow { get; private set; } - - public int TotalRows { get; private set; } - - public int TotalPages { get; private set; } - public bool IsLastPage { get @@ -42,6 +30,18 @@ public bool IsLastPage } } + public int PageNumber { get; private set; } + + public int PageSize { get; private set; } + + public int FirstRow { get; private set; } + + public int LastRow { get; private set; } + + public int TotalRows { get; private set; } + + public int TotalPages { get; private set; } + public void UpdatePageResults(int firstRow, int lastRow, int totalRows, int totalPages) { this.FirstRow = firstRow; diff --git a/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs b/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs index c9957cd76d5..3ef9d6f88be 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterRedirectAction.cs @@ -10,19 +10,19 @@ namespace DotNetNuke.Entities.Urls public class ParameterRedirectAction { public string Action { get; set; } - + public bool ChangeToSiteRoot { get; set; } - + public bool ForDefaultPage { get; set; } - + public string LookFor { get; set; } - + public string Name { get; set; } - + public int PortalId { get; set; } - + public string RedirectTo { get; set; } - + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs b/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs index 55720826aab..4c0577293f9 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterReplaceAction.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Entities.Urls public class ParameterReplaceAction { public bool ChangeToSiteRoot { get; set; } - + public string LookFor { get; set; } - + public string Name { get; set; } - + public int PortalId { get; set; } - + public string ReplaceWith { get; set; } - + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs b/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs index c737dc4a4e2..430dd2628b5 100644 --- a/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs +++ b/DNN Platform/Library/Entities/Urls/ParameterRewriteAction.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Entities.Urls public class ParameterRewriteAction { public bool ForSiteRoot { get; set; } - + public string LookFor { get; set; } - + public string Name { get; set; } - + public int PortalId { get; set; } - + public string RewriteTo { get; set; } - + public int TabId { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/PathSizes.cs b/DNN Platform/Library/Entities/Urls/PathSizes.cs index 8656a61c8bc..bc4af619b0c 100644 --- a/DNN Platform/Library/Entities/Urls/PathSizes.cs +++ b/DNN Platform/Library/Entities/Urls/PathSizes.cs @@ -9,11 +9,11 @@ namespace DotNetNuke.Entities.Urls public class PathSizes { public int MaxAliasDepth { get; set; } - + public int MaxTabPathDepth { get; set; } - + public int MinAliasDepth { get; set; } - + public int MinTabPathDepth { get; set; } public void SetAliasDepth(string httpAlias) @@ -23,7 +23,7 @@ public void SetAliasDepth(string httpAlias) { this.MaxAliasDepth = aliasPathDepth; } - + if (aliasPathDepth < this.MinAliasDepth) { this.MinAliasDepth = aliasPathDepth; @@ -36,7 +36,7 @@ public void SetTabPathDepth(int tabPathDepth) { this.MaxTabPathDepth = tabPathDepth; } - + if (tabPathDepth < this.MinTabPathDepth) { this.MinTabPathDepth = tabPathDepth; diff --git a/DNN Platform/Library/Entities/Urls/RedirectController.cs b/DNN Platform/Library/Entities/Urls/RedirectController.cs index db2d75682cd..2f9c7d64f9f 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectController.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectController.cs @@ -28,25 +28,25 @@ internal static void CancelRedirect(ref UrlAction result, HttpContext context, F result.Action = ActionType.Continue; result.Reason = RedirectReason.Not_Redirected; result.FinalUrl = null; - + // clean the path for the rewrite NameValueCollection queryString = null; if (context != null) { queryString = context.Request.QueryString; } - + result.RewritePath = RedirectTokens.RemoveAnyRedirectTokens(result.RewritePath, queryString); - + // redo the rewrite to fix up the problem. The user has ticked 'permanent redirect' but hasn't supplied a forwarding Url if (context != null) - + // if no context supplied, means no rewrite was required because querystring didn't contain do301 action { // RewriterUtils.RewriteUrl(context, result.RewritePath, settings.RebaseClientPath); RewriterUtils.RewriteUrl(context, result.RewritePath); } - + result.DebugMessages.Add(message); } @@ -59,7 +59,7 @@ internal static void CancelRedirect(ref UrlAction result, HttpContext context, F /// /// /// - internal static bool CheckForModuleProviderRedirect( + internal static bool CheckForModuleProviderRedirect( Uri requestUri, ref UrlAction result, NameValueCollection queryStringCol, @@ -68,7 +68,7 @@ internal static bool CheckForModuleProviderRedirect( { var messages = new List(); string location; - bool redirected = ExtensionUrlProviderController.CheckForRedirect( + bool redirected = ExtensionUrlProviderController.CheckForRedirect( requestUri, result, queryStringCol, @@ -80,18 +80,18 @@ internal static bool CheckForModuleProviderRedirect( { result.DebugMessages.AddRange(messages); } - + if (redirected) { result.FinalUrl = location; result.Action = ActionType.Redirect301; result.Reason = RedirectReason.Custom_Redirect; } - + return redirected; } - internal static bool CheckForParameterRedirect( + internal static bool CheckForParameterRedirect( Uri requestUri, ref UrlAction result, NameValueCollection queryStringCol, @@ -101,18 +101,18 @@ internal static bool CheckForParameterRedirect( // them agains the list of regex expressions on the friendlyurls.config file, and redirecting to the same page // but with new parameters, if there was a match bool redirect = false; - + // get the redirect actions for this portal var messages = new List(); Dictionary> redirectActions = CacheController.GetParameterRedirects(settings, result.PortalId, ref messages); if (redirectActions != null && redirectActions.Count > 0) { try - { + { string rewrittenUrl = result.RewritePath ?? result.RawUrl; List parmRedirects = null; - + // find the matching redirects for the tabid int tabId = result.TabId; if (tabId > -1) @@ -123,7 +123,7 @@ internal static bool CheckForParameterRedirect( parmRedirects = redirectActions[tabId]; } } - + // check for 'all tabs' redirections if (redirectActions.ContainsKey(-1)) // -1 means 'all tabs' - rewriting across all tabs { @@ -132,13 +132,13 @@ internal static bool CheckForParameterRedirect( { parmRedirects = new List(); } - + // add in the all redirects List allRedirects = redirectActions[-1]; parmRedirects.AddRange(allRedirects); // add the 'all' range to the tab range tabId = result.TabId; } - + if (redirectActions.ContainsKey(-2) && result.OriginalPath.ToLowerInvariant().Contains("default.aspx")) { // for the default.aspx page @@ -146,12 +146,12 @@ internal static bool CheckForParameterRedirect( { parmRedirects = new List(); } - + List defaultRedirects = redirectActions[-2]; parmRedirects.AddRange(defaultRedirects); // add the default.aspx redirects to the list tabId = result.TabId; } - + // 726 : allow for site-root redirects, ie redirects where no page match if (redirectActions.ContainsKey(-3)) { @@ -160,11 +160,11 @@ internal static bool CheckForParameterRedirect( { parmRedirects = new List(); } - + List siteRootRedirects = redirectActions[-3]; parmRedirects.AddRange(siteRootRedirects); // add the site root redirects to the collection } - + // OK what we have now is a list of redirects for the currently requested tab (either because it was specified by tab id, // or because there is a replaced for 'all tabs' if (parmRedirects != null && parmRedirects.Count > 0 && rewrittenUrl != null) @@ -174,13 +174,13 @@ internal static bool CheckForParameterRedirect( // regex test each replaced to see if there is a match between the parameter string // and the parmRedirect string compareWith = rewrittenUrl; - var redirectRegex = RegexUtils.GetCachedRegex( + var redirectRegex = RegexUtils.GetCachedRegex( parmRedirect.LookFor, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); Match regexMatch = redirectRegex.Match(compareWith); bool success = regexMatch.Success; bool siteRootTried = false; - + // if no match, but there is a site root redirect to try if (!success && parmRedirect.TabId == -3) { @@ -189,7 +189,7 @@ internal static bool CheckForParameterRedirect( regexMatch = redirectRegex.Match(compareWith); success = regexMatch.Success; } - + if (!success) { result.DebugMessages.Add(parmRedirect.Name + " redirect not matched (" + rewrittenUrl + @@ -214,9 +214,9 @@ internal static bool CheckForParameterRedirect( result.DebugMessages.Add(parmRedirect.Name + " redirect matched with (" + compareWith + "), replaced with " + parms); } - + string finalUrl = string.Empty; - + // now we need to generate the friendly Url // first check to see if the parameter replacement string has a destination tabid specified @@ -233,11 +233,11 @@ internal static bool CheckForParameterRedirect( // changes the tabid of page, effects a page redirect along with a parameter redirect int.TryParse(parmPart, out tabId); parms = parms.Replace("tabid/" + tabId.ToString(), string.Empty); - + // remove the tabid/xx from the path break; // that's it, we're finished } - + if (parmPart.Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) { tabIdNext = true; @@ -251,7 +251,7 @@ internal static bool CheckForParameterRedirect( PortalInfo portal = CacheController.GetPortal(result.PortalId, true); tabId = portal.HomeTabId; } - + if (parmRedirect.ChangeToSiteRoot) { // when change to siteroot requested, new path goes directly off the portal alias @@ -267,7 +267,7 @@ internal static bool CheckForParameterRedirect( if (tab != null) { string path = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tab.TabID, string.Empty); - string friendlyUrlNoParms = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + string friendlyUrlNoParms = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( tab, path, Globals.glbDefaultPage, @@ -279,10 +279,10 @@ internal static bool CheckForParameterRedirect( { friendlyUrlNoParms += "/"; } - + finalUrl = friendlyUrlNoParms; } - + if (tab == null) { result.DebugMessages.Add(parmRedirect.Name + @@ -301,12 +301,12 @@ internal static bool CheckForParameterRedirect( } } } - + if (parms.StartsWith("//")) { parms = parms.Substring(2); } - + if (parms.StartsWith("/")) { parms = parms.Substring(1); @@ -318,14 +318,14 @@ internal static bool CheckForParameterRedirect( { parms = parms.TrimEnd('/'); } - + if (parms.Length > 0) { // we are adding more parms onto the end, so remove the page extension // from the parameter list // 946 : exception when settings.PageExtension value is empty parms += settings.PageExtension; - + // 816: if page extension is /, then don't do this if (settings.PageExtension != "/" && string.IsNullOrEmpty(settings.PageExtension) == false) @@ -341,13 +341,13 @@ internal static bool CheckForParameterRedirect( if (settings.PageExtension != "/" && string.IsNullOrEmpty(settings.PageExtension) == false) { - finalUrl = finalUrl.Replace( + finalUrl = finalUrl.Replace( settings.PageExtension + "/", settings.PageExtension); } } } - + // put the replaced parms back on the end finalUrl += parms; @@ -366,12 +366,12 @@ internal static bool CheckForParameterRedirect( result.Action = ActionType.Output404; break; } - + redirect = true; break; } } - } + } } catch (Exception ex) { @@ -386,7 +386,7 @@ internal static bool CheckForParameterRedirect( } } } - + return redirect; } @@ -402,7 +402,7 @@ internal static bool CheckForParameterRedirect( /// /// /// 823 : Moved from CheckForRedirects to allow call earlier in pipeline. - internal static string GetTabRedirectUrl( + internal static string GetTabRedirectUrl( TabInfo tab, FriendlyUrlSettings settings, string cleanPath, @@ -411,7 +411,7 @@ internal static string GetTabRedirectUrl( Guid parentTraceId) { string bestFriendlyUrl = null; - + // 592 : check for permanent redirect permRedirect = tab.PermanentRedirect; int redirectTabId; @@ -422,7 +422,7 @@ internal static string GetTabRedirectUrl( if (redirectTab != null) { // now get the friendly url for that tab - bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + bestFriendlyUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( redirectTab, cleanPath, Globals.glbDefaultPage, @@ -448,7 +448,7 @@ internal static string GetTabRedirectUrl( permRedirect = false; } } - + return bestFriendlyUrl; } } diff --git a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs index 7927efcf1ba..e72bf55a75b 100644 --- a/DNN Platform/Library/Entities/Urls/RedirectTokens.cs +++ b/DNN Platform/Library/Entities/Urls/RedirectTokens.cs @@ -18,14 +18,14 @@ namespace DotNetNuke.Entities.Urls /// internal static class RedirectTokens { - private static readonly Regex RewritePathRx = new Regex( + private static readonly Regex RewritePathRx = new Regex( @"&rr=(?[^&].)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex RedirectTokensRx = new Regex( + private static readonly Regex RedirectTokensRx = new Regex( @"(?<=(?

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

    /// Adds on a redirect reason to the rewrite path. /// @@ -40,13 +40,13 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath GetRedirectActionTokenAndValue(action, out token, out value); string tokenAndValue = token + "=" + value; bool addToken = true; - + // look for existing action bool hasDupes; - Dictionary tokensAndValues = GetRedirectTokensAndValuesFromRewritePath( + Dictionary tokensAndValues = GetRedirectTokensAndValuesFromRewritePath( existingRewritePath, out hasDupes); - + // can't overwrite existing tokens in certain cases if (tokensAndValues.Count > 0) { @@ -58,10 +58,10 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath result = existingRewritePath.Replace("do301=check", tokenAndValue); } } - + addToken = false; // already done } - + if (addToken) { if (result.Contains(tokenAndValue) == false) @@ -92,7 +92,7 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath } } } - + return result; } @@ -107,7 +107,7 @@ internal static string AddRedirectReasonToRewritePath(string existingRewritePath /// New action value for UrlAction object. /// New redirect reason value for UrlAction object. /// Url to used for rewrite process. - internal static void DetermineRedirectReasonAndAction( + internal static void DetermineRedirectReasonAndAction( string rewrittenUrl, UrlAction result, bool wasParms, @@ -124,13 +124,13 @@ internal static void DetermineRedirectReasonAndAction( // get the action type from the rewrite path ActionType foundAction; bool actionInPath = GetActionFromRewritePath(rewrittenUrl, out foundAction); - + // only overrwrite action if it was found in the rewrite path if (actionInPath) { action = foundAction; } - + // get the list of redirect reason tokens from the url List redirectReasons = GetRedirectReasonTokensFromRewritePath(rewrittenUrl); @@ -139,7 +139,7 @@ internal static void DetermineRedirectReasonAndAction( { redirectReasons.Add("cr"); } - + bool clearActionToken = false; foreach (string rrTkn in redirectReasons) { @@ -167,7 +167,7 @@ internal static void DetermineRedirectReasonAndAction( { // if no parms, then we're not doing a userprofileaction redirect reason = RedirectReason.Custom_Redirect; - + // then check for a 301 redirect action = ActionType.CheckFor301; } @@ -179,7 +179,7 @@ internal static void DetermineRedirectReasonAndAction( // deleted tab dl // disabled tab db clearActionToken = true; - + // 626 Deleted tab hanlding not working properyly - override if (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error) { @@ -217,21 +217,21 @@ internal static void DetermineRedirectReasonAndAction( reason = RedirectReason.Site_Root_Home; clearActionToken = true; } - + break; - + default: // any other redirect with no reason is a custom redirect if (reason == RedirectReason.Not_Redirected) { reason = RedirectReason.Custom_Redirect; } - + clearActionToken = true; break; } } - + if (clearActionToken) { // clear both action and reason @@ -243,121 +243,6 @@ 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. @@ -391,24 +276,24 @@ internal static bool GetActionFromRewritePath(string rewrittenUrl, out ActionTyp action = ActionType.CheckFor301; } } - + break; case "do404": if (val == "true") { action = ActionType.Output404; } - + break; case "do302": if (val == "true") { action = ActionType.Redirect302; } - + break; } - + // if there is more than one match, if we have a solid action, then break if (action != ActionType.Continue) { @@ -416,7 +301,7 @@ internal static bool GetActionFromRewritePath(string rewrittenUrl, out ActionTyp } } } - + return found; } @@ -447,12 +332,12 @@ internal static string RemoveAnyRedirectTokens(string path, NameValueCollection { val = queryStringCol["do301"]; } - + if (string.IsNullOrEmpty(val)) { val = "true"; } - + // nix the 301 redirect query string value or terminal loops-a-plenty path = path.Replace("&do301=" + val, string.Empty); path = path.Replace("?do301=" + val, string.Empty); @@ -462,17 +347,17 @@ internal static string RemoveAnyRedirectTokens(string path, NameValueCollection { val = queryStringCol["do302"]; } - + if (string.IsNullOrEmpty(val)) { val = "true"; } - + // nix the 302 redirect query string value or terminal loops-a-plenty path = path.Replace("&do302=" + val, string.Empty); path = path.Replace("?do302=" + val, string.Empty); } - + return path; } @@ -484,14 +369,14 @@ internal static string RemoveAnyRedirectTokens(string path, NameValueCollection internal static string RemoveAnyRedirectTokensAndReasons(string rewritePath) { string result = RemoveAnyRedirectReasons(rewritePath); - + // regex expression matches a token and removes it Match tokenMatch = RedirectTokensRx.Match(result); if (tokenMatch.Success) { // tokenAndValue is the do301=true string tokenAndValue = tokenMatch.Value; - + // p is either a ? or a & string p = tokenMatch.Groups["p"].Value; if (p == "?") @@ -535,6 +420,121 @@ internal static void SetRedirectReasonAndAction(ref UrlAction result, FriendlyUr result.Action = action; result.Reason = reason; result.RewritePath = 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; + } } } diff --git a/DNN Platform/Library/Entities/Urls/RewriteController.cs b/DNN Platform/Library/Entities/Urls/RewriteController.cs index e338bec765f..3bb5204fe0c 100644 --- a/DNN Platform/Library/Entities/Urls/RewriteController.cs +++ b/DNN Platform/Library/Entities/Urls/RewriteController.cs @@ -27,23 +27,23 @@ public class RewriteController internal const int SiteRootRewrite = -3; internal const int AllTabsRewrite = -1; - private static readonly Regex TabIdRegex = new Regex( + private static readonly Regex TabIdRegex = new Regex( @"(?:\?|\&)tabid\=(?[\d]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex UrlParamsRegex = new Regex(@"&[^=]+(?:&|$)", RegexOptions.Compiled); - private static readonly Regex CultureMatchRegex = new Regex( + private static readonly Regex CultureMatchRegex = new Regex( "([A-Za-z]{2})-([A-Za-z]{2})", RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex LangMatchRegex = new Regex( + private static readonly Regex LangMatchRegex = new Regex( "/language/(?.[^/]+)(?:/|$)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - private static readonly Regex RewriteParamsRegex = new Regex( + private static readonly Regex RewriteParamsRegex = new Regex( @"(?:\&|\?)(?:(?.[^\=\&]*)\=(?.[^\=\&]*))", - RegexOptions.IgnoreCase | RegexOptions.Compiled); + RegexOptions.IgnoreCase | RegexOptions.Compiled); internal static string CheckLanguageMatch(ref string url, UrlAction result) { @@ -57,7 +57,7 @@ internal static string CheckLanguageMatch(ref string url, UrlAction result) // 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; @@ -78,10 +78,10 @@ internal static string CheckLanguageMatch(ref string url, UrlAction result) } } } - + return langParms; } - + /// /// appends a language/culture code value if it is not already present in the rewrite path. /// @@ -91,7 +91,7 @@ internal static string CheckLanguageMatch(ref string url, UrlAction result) 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=")) { @@ -105,7 +105,7 @@ internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string rewritePath += "?language=" + cultureCode; } } - + return changed; } @@ -117,7 +117,7 @@ internal static bool AddLanguageCodeToRewritePath(ref string rewritePath, string /// The selected skin. /// /// - /// 852 : Add skin src to rewrite path for specific aliases. + /// 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) { @@ -128,7 +128,7 @@ internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string re { 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)) { @@ -150,1798 +150,1798 @@ internal static bool AddSkinToRewritePath(int tabId, int portalId, ref string re } } } - + return changed; } - - private static string AddQueryStringToRewritePath(string rewritePath, string queryString) + + /// + /// Checks for exclusions on Rewriting the path, based on a regex pattern. + /// + /// + /// + /// + /// + internal static bool CanRewriteRequest(UrlAction result, string requestedPath, FriendlyUrlSettings settings) { - // now add back querystring if they existed - if (queryString != string.Empty) + bool retVal; + try { - bool rewritePathHasQuery = rewritePath.IndexOf("?", StringComparison.Ordinal) != -1; - if (queryString.StartsWith("?")) + // 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))) { - queryString = queryString.Substring(1); + retVal = true; + result.CanRewrite = StateBoolean.True; } - - string[] parms = queryString.Split('&'); - - // iterate through the array of parameters - for (int i = 0; i < parms.Length; i++) + else { - bool hasValue = false; - - // get parameter name - string parmName = parms[i]; - - // check if parm name contains a value as well - if (parmName.IndexOf("=", StringComparison.Ordinal) != -1) - { - // snip off the =value part of the parm - parmName = parmName.Substring(0, parmName.IndexOf("=", StringComparison.Ordinal)); - hasValue = true; - } - - // 597 : do a compare with the '=' on the end to only - // compare the entire parmname, not just the start - string comparePath1 = "?" + parmName.ToLowerInvariant(); - string comparePath2 = "&" + parmName.ToLowerInvariant(); - if (hasValue) - { - comparePath1 += "="; - comparePath2 += "="; - } - - // check if parameter already exists in the rewrite path - // we only want to add the querystring back on if the - // query string keys were not already shown in the friendly - // url path - if (!rewritePath.ToLowerInvariant().Contains(comparePath1) - && !rewritePath.ToLowerInvariant().Contains(comparePath2)) - { - // 622 : remove encoding from querystring paths - // 699 : reverses 622 because works from Request.QUeryString instead of Request.Url.Query - // string queryStringPiece = System.Web.HttpUtility.UrlDecode(parms[i]); - string queryStringPiece = parms[i]; - - // no decoding - querystring passes through rewriting process untouched - // add parameter to SendTo value - if (rewritePathHasQuery) - { - rewritePath = rewritePath + "&" + queryStringPiece; - } - else - { - rewritePath = rewritePath + "?" + queryStringPiece; - rewritePathHasQuery = true; - } - } + retVal = false; + result.CanRewrite = StateBoolean.False; } + + // } } - - return rewritePath; + catch (Exception ex) + { + retVal = true; // always rewrite if an error in the regex + + UrlRewriterUtils.LogExceptionInRequest(ex, "NotSet", result); + result.Ex = ex; + } + + return retVal; } - private static string CheckIfPortalAlias(string url, NameValueCollection querystringCol, UrlAction result, FriendlyUrlSettings settings, SharedDictionary tabDict) + internal static string CleanExtension(string value, string extension, out bool replaced) { - string newUrl = url; - bool reWritten = false; + return CleanExtension(value, extension, string.Empty, out replaced); + } - string defaultPage = Globals.glbDefaultPage.ToLowerInvariant(); - string portalAliasUrl = url.ToLowerInvariant().Replace("/" + defaultPage, string.Empty); - - // if there is a straight match on a portal alias, it's the home page for that portal requested - var portalAlias = PortalAliasController.Instance.GetPortalAlias(portalAliasUrl); - if (portalAlias != null) - { - // special case : sometimes, some servers issue root/default.aspx when root/ was requested, sometimes not. It depends - // on other server software installed (apparently) - // so check the raw Url and the url, and see if they are the same except for the /default.aspx - string rawUrl = result.RawUrl; - if (url.ToLowerInvariant().EndsWith(rawUrl + defaultPage.ToLowerInvariant())) - { - // special case - change the url to be equal to the raw Url - url = url.Substring(0, url.Length - defaultPage.Length); - } + internal static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms, out bool replaced) + { + return CleanExtension(value, settings.PageExtension, langParms, out replaced); + } - if (settings.RedirectDefaultPage - && url.EndsWith("/" + defaultPage, StringComparison.InvariantCultureIgnoreCase) - && result.RedirectAllowed) + internal static string CleanExtension(string value, FriendlyUrlSettings settings, out bool replaced) + { + return CleanExtension(value, settings.PageExtension, string.Empty, out replaced); + } + + internal static string CleanExtension(string value, string extension, string langParms, out bool replaced) + { + string result = value; + string ext = extension.ToLowerInvariant(); + replaced = false; + if (result.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase) && ext != string.Empty) + { + result = result.Substring(0, result.Length - ext.Length); + replaced = true; + } + else + { + if (result.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)) { - result.Reason = RedirectReason.Site_Root_Home; - result.FinalUrl = Globals.AddHTTP(portalAliasUrl + "/"); - result.Action = ActionType.Redirect301; + result = result.Substring(0, result.Length - 5); + replaced = true; } else { - // special case -> look in the tabdict for a blank intercept - // 735 : switch to custom method for getting portal - PortalInfo portal = CacheController.GetPortal(portalAlias.PortalID, true); - if (portal.HomeTabId == -1) + // object not set errors when language parameters used + if (string.IsNullOrEmpty(langParms) == false) { - string tabKey = url; - if (tabKey.EndsWith("/")) - { - tabKey = tabKey.TrimEnd('/'); - } - - tabKey += "::"; - using (tabDict.GetReadLock()) - { - if (tabDict.ContainsKey(tabKey)) - { - newUrl = tabDict[tabKey]; - reWritten = true; - } - } - - // if no home tab, but matched a portal alias, and no trailing /default.aspx - // and no 'newUrl' value because not rewritten, then append the /default.aspx - // and ask for a rewrite on that one. - // DNNDEV-27291 - if (reWritten == false) + // safely remove .aspx from the language path without doing a full .aspx -> "" replace on the entire path + if (string.IsNullOrEmpty(result) == false && + result.EndsWith(".aspx" + langParms, StringComparison.InvariantCultureIgnoreCase)) { - // Need to determine if this is a child alias - newUrl = "/" + Globals.glbDefaultPage; - reWritten = true; + result = result.Substring(0, result.Length - (5 + langParms.Length)) + langParms; + replaced = true; } } - else + else if (result.EndsWith("/")) { - // set rewrite to home page of site - // 760: check for portal alias specific culture before choosing home tabid - bool checkForCustomAlias = false; - bool customTabAlias = false; - - // check for culture-specific aliases - string culture = null; - var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); + result = result.Substring(0, result.Length - 1); + replaced = true; + } + } + } - // if there are chosen portal aliases, check to see if the found alias is one of them - // if not, then will check for a custom alias per tab - if (!portalAliases.ContainsAlias(portal.PortalID, portalAlias.HTTPAlias)) - { - checkForCustomAlias = true; - } - else - { - // check for a specific culture for the alias - culture = portalAliases.GetCultureByPortalIdAndAlias(portal.PortalID, portalAlias.HTTPAlias); - } - - if (checkForCustomAlias) - { - // ok, this isnt' a chosen portal alias, check the list of custom aliases - List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); - if (customAliasesForTabs != null && customAliasesForTabs.Contains(portalAlias.HTTPAlias.ToLowerInvariant())) - { - // ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context - string tabKey = url.ToLowerInvariant(); - if (tabKey.EndsWith("/")) - { - tabKey = tabKey.TrimEnd('/'); - } - - if (tabKey.EndsWith("/default.aspx")) - { - tabKey = tabKey.Substring(0, tabKey.Length - 13); // 13 = "/default.aspx".length - } - - tabKey += "::"; - using (tabDict.GetReadLock()) - { - if (tabDict.ContainsKey(tabKey)) - { - newUrl = tabDict[tabKey]; - reWritten = true; - customTabAlias = true; // this alias is used as the alias for a custom tab - } - } - } - } - - if (customTabAlias == false) - { - int tabId; - if (!string.IsNullOrEmpty(querystringCol["TabId"])) - { - tabId = Convert.ToInt32(querystringCol["TabId"]); - result.Action = ActionType.CheckFor301; - } - else - { - // not a custom alias for a specific tab, so it must be the home page for the portal we identified, - // if its first request and splash page defined, then redirec to splash page. - if (portal.SplashTabId > Null.NullInteger && HttpContext.Current != null && - !HttpContext.Current.Request.Cookies.AllKeys.Contains("SplashPageView")) - { - tabId = portal.SplashTabId; - HttpContext.Current.Response.Cookies.Add( - new HttpCookie("SplashPageView", "true") { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); - result.Action = ActionType.Redirect302; - result.Reason = RedirectReason.Requested_SplashPage; - } - else - { - tabId = portal.HomeTabId; - } - - if (culture == null) - { - culture = portal.DefaultLanguage; // set culture to default if not found specifically - } - else - { - // if there is a specific culture for this alias, and it's different to the default language, then - // go check for a specific culture home page (5.5 and later) - tabId = TabPathHelper.GetHomePageTabIdForCulture( - portal.DefaultLanguage, - portal.PortalID, - culture, - tabId); - } - } - - // see if there is a skin for the alias/culture combination - string skin = TabPathHelper.GetTabAliasSkinForTabAndAlias( - portalAlias.PortalID, - portalAlias.HTTPAlias, culture); - if (string.IsNullOrEmpty(skin) == false) - { - newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty, "skinSrc=" + skin); - } - else - { - newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty); - } - - // DNN-3789 always call this method as culture is defined by GetPageLocale - AddLanguageCodeToRewritePath(ref newUrl, culture); - - // add on language specified by current portal alias - reWritten = true; - } - } - } - - if (reWritten) - { - // check for replaced to site root from /default.aspx - // 838 set redirect reason and action from result - SetRewriteParameters(ref result, newUrl); - ActionType action; - RedirectReason reason; - string resultingUrl; - RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, true, settings, out resultingUrl, out reason, out action); - newUrl = resultingUrl; - result.Action = action; - result.Reason = reason; - } - } - - return newUrl; + return result; } - private static bool CheckSpecialCase(string tabKeyVal, SharedDictionary tabDict) + /// + /// Returns either the rewritten path (if a rewrite used) or the requested path (if no rewrite used). + /// + /// + /// + /// Url suitable for input into friendly url generation routine. + internal static string GetRewriteOrRequestedPath(UrlAction result, Uri requestUri) { - bool found = false; - int pathStart = tabKeyVal.LastIndexOf("::", StringComparison.Ordinal); // look for portal alias separator - int lastPath = tabKeyVal.LastIndexOf('/'); - - // get any path separator in the tab path portion - if (pathStart > lastPath) - { - lastPath = pathStart; - } - - if (lastPath >= 0) + var pathOnly = result.RewritePath; + if (result.DoRewrite == false) { - int defaultStart = tabKeyVal.IndexOf("default", lastPath, StringComparison.OrdinalIgnoreCase); - - // no .aspx on the end anymore - if (defaultStart > 0 && defaultStart > lastPath) - - // there is a default in the path, and it's not the entire path (ie pagnamedefault and not default) + // if no rewrite, then the path should have been a non-friendly path, and therefore can be passed in to get the friendly Url + pathOnly = requestUri.Authority + requestUri.PathAndQuery; + int aliasEnd = + pathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) + + result.PortalAlias.HTTPAlias.Length; + if (aliasEnd > -1) { - tabKeyVal = tabKeyVal.Substring(0, defaultStart); - - // get rid of the default.aspx part - using (tabDict.GetReadLock()) - { - found = tabDict.ContainsKey(tabKeyVal); - - // lookup the tabpath in the tab dictionary again - } + pathOnly = pathOnly.Substring(aliasEnd); } + + pathOnly = HttpUtility.UrlDecode(pathOnly, Encoding.UTF8); } - - return found; + + return pathOnly; } - private static UserInfo GetUser(int portalId, string vanityUrl) + internal static string GetTabFromDictionary(string url, NameValueCollection querystringCol, FriendlyUrlSettings settings, UrlAction result, Guid parentTraceId) { - string cacheKey = string.Format(CacheController.VanityUrlLookupKey, portalId); - var vanityUrlLookupDictionary = CBO.GetCachedObject>( - new CacheItemArgs(cacheKey, 20, CacheItemPriority.High, portalId), - c => new Dictionary()); + // retrive the tab dictionary from the cache and get the path depth values + int maxAliasPathDepth; + int maxTabPathDepth; + int minAliasPathDepth; + int minTabPathDepth; + int curAliasPathDepth = 0; - if (!vanityUrlLookupDictionary.ContainsKey(vanityUrl)) - { - vanityUrlLookupDictionary[vanityUrl] = UserController.GetUserByVanityUrl(portalId, vanityUrl); - } + var tabDict = TabIndexController.FetchTabDictionary( + result.PortalId, + out minTabPathDepth, + out maxTabPathDepth, + out minAliasPathDepth, + out maxAliasPathDepth, + settings, + false, + result.BypassCachedDictionary, + parentTraceId); - return vanityUrlLookupDictionary[vanityUrl]; - } - - private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrlSettings settings, SharedDictionary tabDict, ref string newUrl) - { - bool found; - string userParam = string.Empty; - string tabLookUpKey = tabKeyVal; - using (tabDict.GetReadLock()) + // clean up and prepare the url for scanning + if (url.EndsWith("/")) { - found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary + url = url.TrimEnd('/'); } - // special case, if no extensions and the last part of the tabKeyVal contains default.aspx, then - // split off the default.aspx part and try again - compensating for gemini issue http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=8651&PROJID=39 - if (!found && settings.PageExtensionUsageType != PageExtensionUsageType.AlwaysUse) + // ok now scan for the language modifier + string langParms = CheckLanguageMatch(ref url, result); + + // clean off the extension before checking the url matches, but + // remember if an extension existed + bool hadExtension; + string cleanUrl = CleanExtension(url, settings, langParms, out hadExtension); + string[] splitUrl = cleanUrl.Split('/'); + + // initialise logic switches + bool reWritten = false; + bool finished = false; + + string newUrl = CheckIfPortalAlias(url, querystringCol, result, settings, tabDict); + if (newUrl != url) { - found = CheckSpecialCase(tabLookUpKey, tabDict); + finished = true; + reWritten = true; } - // Check for VanityUrl - var doNotRedirectRegex = RegexUtils.GetCachedRegex(settings.DoNotRedirectRegex); - if (!found && !Globals.ServicesFrameworkRegex.IsMatch(result.RawUrl) && !doNotRedirectRegex.IsMatch(result.RawUrl)) + // start looping through the url segments looking for a match in the tab dictionary + while (finished == false) { - string[] urlParams = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None); - if (urlParams.Length > 1) - { - // Extract the first Url parameter - string tabPath = urlParams[1]; - - var urlSegments = tabPath.Split('/'); - - string prefix = urlSegments[0]; + // first, try forming up a key based on alias/tabpath + int lastIndex = splitUrl.GetUpperBound(0); + int arraySize = lastIndex + 1; + int totalDepth = maxAliasPathDepth + 1 + maxTabPathDepth + 1; - if (prefix == settings.VanityUrlPrefix && urlSegments.Length > 1) + // the maximum depth of segments of a valid url + for (int i = lastIndex; i >= 0; i += -1) + { + // only start checking the url when it is in the range of the min->max number of segments + if (i > minAliasPathDepth & i <= totalDepth) { - string vanityUrl = urlSegments[1]; - - // check if its a vanityUrl - var user = GetUser(PortalController.GetEffectivePortalId(result.PortalId), vanityUrl); - if (user != null) + // join all the tab path sections together + // flag to remember if the incoming path had a .aspx or other pageAndExtension on it + int tabPathStart = curAliasPathDepth + 1; + int tabPathLength = i - curAliasPathDepth; + if ((tabPathStart + tabPathLength) <= arraySize) { - userParam = "UserId=" + user.UserID.ToString(); + string tabPath = string.Empty; + if (tabPathLength > -1) + { + tabPath = string.Join("/", splitUrl, tabPathStart, tabPathLength); + } - // Get the User profile Tab - var portal = PortalController.Instance.GetPortal(result.PortalId); - var profilePage = TabController.Instance.GetTab(portal.UserTabId, result.PortalId, false); + string aliasPath; + if (curAliasPathDepth <= lastIndex) + { + aliasPath = string.Join("/", splitUrl, 0, curAliasPathDepth + 1); + } + else + { + finished = true; + break; + } - FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); - string profilePagePath = TabPathHelper.GetFriendlyUrlTabPath(profilePage, options, Guid.NewGuid()); + int parmsSize = lastIndex - i; + int parmStart = i + 1; // determine if any parameters on this value - // modify lookup key; - tabLookUpKey = tabLookUpKey.Replace("::" + string.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), "::" + profilePagePath.TrimStart('/').ToLowerInvariant()); + // make up the index that is looked for in the Tab Dictionary + string urlPart = aliasPath + "::" + tabPath; - using (tabDict.GetReadLock()) + // the :: allows separation of pagename and portal alias + string tabKeyVal = urlPart.ToLowerInvariant(); // force lower case lookup, all keys are lower case + + // Try with querystring first If last Index + bool found = false; + if (querystringCol.Count > 0) { - found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary + found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue) + "?" + querystringCol.ToString().Split('&')[0].ToLowerInvariant(), result, settings, tabDict, ref newUrl); } - } - } - } - } - - if (found) - { - using (tabDict.GetReadLock()) - { - // determine what the rewritten URl will be - newUrl = tabDict[tabLookUpKey]; - } - // DNN-6747: if found match doesn't match current culture, then try to find correct match. - if (result.PortalId != Null.NullInteger && newUrl.Contains("language=")) - { - var currentLocale = result.CultureCode; - if (string.IsNullOrEmpty(currentLocale)) - { - currentLocale = Localization.GetPageLocale(new PortalSettings(result.PortalId)).Name; - } + if (!found) + { + found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue), result, settings, tabDict, ref newUrl); + } - if (!newUrl.Contains(currentLocale)) - { - var tabPath = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None)[1]; - using (tabDict.GetReadLock()) - { - foreach (var key in tabDict.Keys.Where(k => k.EndsWith("::" + tabPath))) + bool isSiteRootMatch = false; + if (!found && tabPathLength == 1) { - if (tabDict[key].Contains("language=" + currentLocale)) + // look for special case where the site root has a * value + string siteRootLookup = aliasPath + "::" + "*"; + using (tabDict.GetReadLock()) { - newUrl = tabDict[key]; - tabKeyVal = key; - break; + found = tabDict.ContainsKey(siteRootLookup); + if (found) + { + isSiteRootMatch = true; + newUrl = tabDict[siteRootLookup]; + parmsSize++; // re-increase the parameter size + parmStart--; // shift the point of the parms starting back one + } } } - } - } - } - if (!string.IsNullOrEmpty(userParam)) - { - newUrl = newUrl + "&" + userParam; - } - - // if this is a match on the trigger dictionary rebuild, - // then temporarily store this value in case it's a page name change - // 677 : only match if is on actual tabKeyVal match, to prevent site root redirects - // statements were moved into this 'if' statement - result.dictVal = newUrl; - result.dictKey = tabKeyVal; - } - - return found; - } + if (found) + { + if (settings.ProcessRequestList != null) + { + newUrl = ReplaceDefaultPage(newUrl, url, settings.ProcessRequestList); + } - private static string ReplaceDefaultPage(string newUrl, string requestUrl, IEnumerable list) - { - string url = newUrl; // fall back case: we don't change anything - - // iterate the list and replace in the url is a match is found - foreach (string requestPage in list) - { - if (requestUrl.ToLowerInvariant().Contains(requestPage)) - { - url = newUrl.Replace(Globals.glbDefaultPage, requestPage); - break; - } - } - - return url; - } + // look for a plain match on the default.aspx page which indicates no more rewriting needs to be done + if (!isSiteRootMatch && (newUrl == Globals.glbDefaultPage || newUrl == Globals.glbDefaultPage + "[UseBase]")) + { + // the [UseBase] moniker is a shortcut hack. It's used to recognise pages which have been excluded + // from using Friendly Urls. The request will go on to be processed by the dnn siteurls.config processing. + // this stops the loop and exits the function + newUrl = newUrl.Replace("[UseBase]", string.Empty); // get rid of usebase hack pattern + SetRewriteParameters(ref result, newUrl); // set result + finished = true; + } + else + { + // 708 : move result rewrite set so that downstream functions know the tabid + SetRewriteParameters(ref result, newUrl); - private static string RewriteParametersFromModuleProvider( - string newUrl, - string tabKeyVal, - string[] urlParms, - bool isSiteRootMatch, - UrlAction result, - FriendlyUrlSettings settings, - out bool rewriteParms, - out bool newAction, - ref List messages, - Guid parentTraceId) - { - string rewrittenUrl; - rewriteParms = ExtensionUrlProviderController.TransformFriendlyUrlPath( - newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - ref result, - settings, - out rewrittenUrl, - out newAction, - ref messages, - parentTraceId); - if (rewriteParms) - { - result.CustomParmRewrite = true; - } - - return rewrittenUrl; - } + // found the correct rewrite page, now investigate whether there + // is part of the url path that needs to be converted to tab id's + // Multi Language Urls not being rewritten + if (parmsSize > 0) + { + bool rewriteParms = false; - private static void SetRewriteParameters(ref UrlAction result, string rewritePath) - { - // split out found replaced and store tabid, rulePortalId and do301 if found - result.RewritePath = rewritePath; - MatchCollection qsItems = RewriteParamsRegex.Matches(rewritePath); - foreach (Match itemMatch in qsItems) - { - string val = itemMatch.Groups["val"].Value; - string key = itemMatch.Groups["key"].Value; - switch (key.ToLowerInvariant()) - { - case "tabid": - int tabidtemp; - if (int.TryParse(val, out tabidtemp)) - { - result.TabId = tabidtemp; - } - - break; - case "portalid": - int pid; - if (int.TryParse(val, out pid)) - { - result.PortalId = pid; - } - - break; - case "language": - result.CultureCode = val; - break; - case "ctl": - // 786: force redirect for ctl/terms or ctl/privacy - RequestRedirectOnBuiltInUrl(val, rewritePath, result); - break; - } - } - - // remove the application path - result.RewritePath = result.RewritePath.Replace(result.ApplicationPath + "/", string.Empty); - } + // determine the url action and reason from embedded rewriting tokens + ActionType action; + RedirectReason reason; + string resultingUrl; + RedirectTokens.DetermineRedirectReasonAndAction( + newUrl, + result, + true, + settings, + out resultingUrl, + out reason, + out action); + newUrl = resultingUrl; + result.Action = action; + result.Reason = reason; - /// - /// Checks for exclusions on Rewriting the path, based on a regex pattern. - /// - /// - /// - /// - /// - internal static bool CanRewriteRequest(UrlAction result, string requestedPath, FriendlyUrlSettings settings) - { - 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; - } - - // } - } - catch (Exception ex) - { - retVal = true; // always rewrite if an error in the regex + // copy the parms into a separate array + var urlParms = new string[parmsSize]; + Array.ConstrainedCopy(splitUrl, parmStart, urlParms, 0, parmsSize); - UrlRewriterUtils.LogExceptionInRequest(ex, "NotSet", result); - result.Ex = ex; - } - - return retVal; - } + if (!isSiteRootMatch && result.Reason == RedirectReason.User_Profile_Url) + { + result.Reason = RedirectReason.Not_Redirected; + newUrl = RedirectTokens.RemoveAnyRedirectTokensAndReasons(newUrl); + } - internal static string CleanExtension(string value, string extension, out bool replaced) - { - return CleanExtension(value, extension, string.Empty, out replaced); - } + // 738 : check for custom module providers + // 894 : allow disable of custom url providers functionality + if (!rewriteParms && settings.EnableCustomProviders) + { + bool newAction; - internal static string CleanExtension(string value, FriendlyUrlSettings settings, string langParms, out bool replaced) - { - return CleanExtension(value, settings.PageExtension, langParms, out replaced); - } + // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. + // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. + List messages = result.DebugMessages; + newUrl = RewriteParametersFromModuleProvider( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + settings, + out rewriteParms, + out newAction, + ref messages, + parentTraceId); + result.DebugMessages = messages; + if (newAction) + { + finished = true; + } + } - internal static string CleanExtension(string value, FriendlyUrlSettings settings, out bool replaced) - { - return CleanExtension(value, settings.PageExtension, string.Empty, out replaced); - } + // do a rewrite on the parameters from the stored parameter regex rewrites + if (!rewriteParms) + { + newUrl = RewriteParameters( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + out rewriteParms, + parentTraceId); + } - internal static string CleanExtension(string value, string extension, string langParms, out bool replaced) - { - string result = value; - string ext = extension.ToLowerInvariant(); - replaced = false; - if (result.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase) && ext != string.Empty) - { - result = result.Substring(0, result.Length - ext.Length); - replaced = true; - } - else - { - if (result.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase)) - { - result = result.Substring(0, result.Length - 5); - replaced = true; + if (rewriteParms && isSiteRootMatch) + { + // set rewrite parameters to take tabid for site root matches + SetRewriteParameters(ref result, newUrl); + } + + // if the parms weren't rewritten by means of a regex, then process them normally + if (!rewriteParms && !isSiteRootMatch) + + // can only try other matches if it wasn't a site root match + { + // put those parms on the back of the url as a query string + string cultureCode; + newUrl = RewriteParameters( + newUrl, + tabKeyVal, + urlParms, + result, + langParms, + settings, + out cultureCode); + if (cultureCode != null) // set culture code if not already set + { + result.CultureCode = cultureCode; + } + } + + // now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have + if (!finished) + { + // 944 : don't switch to 301 redirect if action already set to 404 + if ((settings.PageExtensionUsageType == PageExtensionUsageType.Never + || settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) & + hadExtension) + { + // 948 : use new 'no downgrade' method + result.SetActionWithNoDowngrade(ActionType.CheckFor301); + } + else + + // 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); + } + } + + if (isSiteRootMatch && !finished) + + // when it was a site root match, this must be matched with a custom parameter regex + { + // only finished if the parms were rewritten by means of a regex rewrite + reWritten = rewriteParms; + finished = rewriteParms; + } + else + { + // rewriting done + reWritten = true; + finished = true; + } + } + else + { + // determine the url action and redirect reason from embedded tokens in the url rewrite path + string resultUrl; + RedirectReason reason; + ActionType action; + + // add back language parameters if they were there + if (string.IsNullOrEmpty(langParms) == false) + { + string[] parms = langParms.Split('/'); + if (parms.GetUpperBound(0) >= 1) + { + if (parms[0] == string.Empty && parms.GetUpperBound(0) > 1) + { + newUrl += "&" + parms[1] + "=" + parms[2]; + } + else + { + newUrl += "&" + parms[0] + "=" + parms[1]; + } + } + } + + RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, false, settings, + out resultUrl, out reason, + out action); + newUrl = resultUrl; + result.Reason = reason; + result.Action = action; + + if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders( + result.PortalId, + result.TabId, + settings, + parentTraceId)) + { + bool newAction; + + // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. + // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. + string[] urlParms = new List().ToArray(); // empty parm array + if (string.IsNullOrEmpty(langParms) == false) + { + urlParms = langParms.Split('/'); + + // split the lang parms into the url Parms + } + + bool rewriteParms; + List messages = result.DebugMessages; + newUrl = RewriteParametersFromModuleProvider( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + result, + settings, + out rewriteParms, + out newAction, + ref messages, + parentTraceId); + result.DebugMessages = messages; + } + + // this is a page only, no parameters to deal with + // 944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944) + if (settings.PageExtensionUsageType == PageExtensionUsageType.Never & hadExtension) + { + // potentially a 301 replaced because shouldn't be using page extensions + // 948 : check to prevent action downgrade, in case already set to redirect + result.SetActionWithNoDowngrade(ActionType.CheckFor301); + } + else + { + // 866 : redirect back from no extension to extension if it didn't have one + if (settings.PageExtensionUsageType != PageExtensionUsageType.Never && + hadExtension == false) + { + result.SetActionWithNoDowngrade(ActionType.CheckFor301); + } + } + + // rewriting done + reWritten = true; + finished = true; + } + } + + if (finished) + { + break; + } + } + } + } } - else + + // next, try forming up a key based on alias1/alias2/tabpath + if (!finished) { - // object not set errors when language parameters used - if (string.IsNullOrEmpty(langParms) == false) + curAliasPathDepth += 1; + + // gone too deep + if ((curAliasPathDepth > maxAliasPathDepth) && !reWritten) { - // safely remove .aspx from the language path without doing a full .aspx -> "" replace on the entire path - if (string.IsNullOrEmpty(result) == false && - result.EndsWith(".aspx" + langParms, StringComparison.InvariantCultureIgnoreCase)) + // no hope of finding it then + if (!Globals.ServicesFrameworkRegex.IsMatch(url) && result.RedirectAllowed) { - result = result.Substring(0, result.Length - (5 + langParms.Length)) + langParms; - replaced = true; + // nothing left to try + result.Action = (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error) + ? ActionType.Output404 + : ActionType.Redirect301; + if (result.Action == ActionType.Redirect301) + { + result.Reason = RedirectReason.Deleted_Page; + result.DoRewrite = true; + result.FinalUrl = Globals.AddHTTP(result.PortalAlias.HTTPAlias + "/"); + reWritten = true; + } } - } - else if (result.EndsWith("/")) - { - result = result.Substring(0, result.Length - 1); - replaced = true; + + break; } } } - - return result; + + result.FriendlyRewrite = reWritten; + result.DoRewrite = reWritten; + return newUrl; } - /// - /// Returns either the rewritten path (if a rewrite used) or the requested path (if no rewrite used). - /// - /// - /// - /// Url suitable for input into friendly url generation routine. - internal static string GetRewriteOrRequestedPath(UrlAction result, Uri requestUri) + internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, out string fullUrl, out string querystring) { - var pathOnly = result.RewritePath; - if (result.DoRewrite == false) + // 699: incorrect encoding in absoluteUri.ToString() + string urlWoutQuery = requestUri.AbsoluteUri; + if (requestUri.Query != string.Empty) { - // if no rewrite, then the path should have been a non-friendly path, and therefore can be passed in to get the friendly Url - pathOnly = requestUri.Authority + requestUri.PathAndQuery; - int aliasEnd = - pathOnly.IndexOf(result.PortalAlias.HTTPAlias, StringComparison.InvariantCultureIgnoreCase) + - result.PortalAlias.HTTPAlias.Length; - if (aliasEnd > -1) - { - pathOnly = pathOnly.Substring(aliasEnd); - } - - pathOnly = HttpUtility.UrlDecode(pathOnly, Encoding.UTF8); + urlWoutQuery = urlWoutQuery.Replace(requestUri.Query, string.Empty); + + // replace the querystring on the reuqest absolute Uri } - - return pathOnly; - } - internal static string GetTabFromDictionary(string url, NameValueCollection querystringCol, FriendlyUrlSettings settings, UrlAction result, Guid parentTraceId) - { - // retrive the tab dictionary from the cache and get the path depth values - int maxAliasPathDepth; - int maxTabPathDepth; - int minAliasPathDepth; - int minTabPathDepth; - int curAliasPathDepth = 0; + // 926 : do not use querystring.toString() because of encoding errors that restul, + // the encoding type is changed from utf-8 to latin-1 + querystring = requestUri.Query; - var tabDict = TabIndexController.FetchTabDictionary( - result.PortalId, - out minTabPathDepth, - out maxTabPathDepth, - out minAliasPathDepth, - out maxAliasPathDepth, - settings, - false, - result.BypassCachedDictionary, - parentTraceId); - - // clean up and prepare the url for scanning - if (url.EndsWith("/")) + // get results + fullUrl = urlWoutQuery; + if (fullUrl.EndsWith("/_noext.aspx", StringComparison.InvariantCultureIgnoreCase)) { - url = url.TrimEnd('/'); - } - - // ok now scan for the language modifier - string langParms = CheckLanguageMatch(ref url, result); - - // clean off the extension before checking the url matches, but - // remember if an extension existed - bool hadExtension; - string cleanUrl = CleanExtension(url, settings, langParms, out hadExtension); - string[] splitUrl = cleanUrl.Split('/'); + fullUrl = fullUrl.Replace("_noext.aspx", string.Empty); - // initialise logic switches - bool reWritten = false; - bool finished = false; + // replace this marker pattern so it looks as though it isn't there *(leave on trailing slash) + } - string newUrl = CheckIfPortalAlias(url, querystringCol, result, settings, tabDict); - if (newUrl != url) + if (querystring != string.Empty) { - finished = true; - reWritten = true; + // set up the querystring and the fullUrl to include the querystring + if (querystring.StartsWith("?") == false) + { + querystring = "?" + querystring; + } + + fullUrl += querystring; } + } - // start looping through the url segments looking for a match in the tab dictionary - while (finished == false) + /// + /// Identifies a request for a physical file on the system. + /// + /// The Physical Path propery of the request. + /// + /// + /// + /// + /// + /// + /// + /// + internal static void IdentifyByPhysicalResource( + string physicalPath, + string fullUrl, + NameValueCollection queryStringCol, + ref UrlAction result, + bool useFriendlyUrls, + FriendlyUrlSettings settings, + out bool isPhysicalResource, + out bool checkFurtherForRewrite, + Guid parentTraceId) + { + isPhysicalResource = false; + checkFurtherForRewrite = true; + if (File.Exists(physicalPath) && physicalPath.EndsWith("\\_noext.aspx") == false) { - // first, try forming up a key based on alias/tabpath - int lastIndex = splitUrl.GetUpperBound(0); - int arraySize = lastIndex + 1; - int totalDepth = maxAliasPathDepth + 1 + maxTabPathDepth + 1; + // resource found + string appPath = Globals.ApplicationMapPath + "\\default.aspx"; + bool isDefaultAspxPath = false; + if (string.Compare(physicalPath, appPath, StringComparison.OrdinalIgnoreCase) != 0) + { + string aliasQs; + if (AdvancedUrlRewriter.CheckForChildPortalRootUrl(fullUrl, result, out aliasQs)) + { + result.DebugMessages.Add("Child Portal Alias Root Identified"); + } + else + { + // it's not the default.aspx path or a child alias request, so we haven't identifed the resource + isPhysicalResource = true; + checkFurtherForRewrite = false; + result.DebugMessages.Add("Resource Identified No Rewrite Used"); + } + } + else + { + isDefaultAspxPath = true; + } - // the maximum depth of segments of a valid url - for (int i = lastIndex; i >= 0; i += -1) + if (isDefaultAspxPath) // it is the default aspx path { - // only start checking the url when it is in the range of the min->max number of segments - if (i > minAliasPathDepth & i <= totalDepth) + // check to see if it is a /default.aspx?key=value url (not just default.aspx, nor a child alias) + if (queryStringCol != null && queryStringCol.Count > 0) { - // join all the tab path sections together - // flag to remember if the incoming path had a .aspx or other pageAndExtension on it - int tabPathStart = curAliasPathDepth + 1; - int tabPathLength = i - curAliasPathDepth; - if ((tabPathStart + tabPathLength) <= arraySize) + // when there is a query string supplied, we don't need to rewrite + if (useFriendlyUrls) { - string tabPath = string.Empty; - if (tabPathLength > -1) - { - tabPath = string.Join("/", splitUrl, tabPathStart, tabPathLength); - } - - string aliasPath; - if (curAliasPathDepth <= lastIndex) - { - aliasPath = string.Join("/", splitUrl, 0, curAliasPathDepth + 1); - } - else + // using friendly URls, so just nab the Tab id from the querystring + if (queryStringCol["tabId"] != null) { - finished = true; - break; + if (result.RedirectAllowed) + { + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Unfriendly_Url_TabId; + } } - - int parmsSize = lastIndex - i; - int parmStart = i + 1; // determine if any parameters on this value + } - // make up the index that is looked for in the Tab Dictionary - string urlPart = aliasPath + "::" + tabPath; - - // the :: allows separation of pagename and portal alias - string tabKeyVal = urlPart.ToLowerInvariant(); // force lower case lookup, all keys are lower case + result.DoRewrite = false; + checkFurtherForRewrite = false; - // Try with querystring first If last Index - bool found = false; - if (querystringCol.Count > 0) - { - found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue) + "?" + querystringCol.ToString().Split('&')[0].ToLowerInvariant(), result, settings, tabDict, ref newUrl); - } - - if (!found) - { - found = CheckTabPath(tabKeyVal.Replace(" ", settings.SpaceEncodingValue), result, settings, tabDict, ref newUrl); - } + // no more checking for rewrites, we have our physical file and our query string + // the default.aspx is still a physical resource, but we want to do the rest of the processing + } + else + { + // could be either default.aspx with no querystring, or a child portal alias root + // if 301 redirects are on, then we want to rewrite and replace this Url to include information like language modifiers + // so return false to indicate that the physical resource couldn't be identified + isPhysicalResource = !useFriendlyUrls; + } + } + } - bool isSiteRootMatch = false; - if (!found && tabPathLength == 1) + // mark as physical request + result.IsPhysicalResource = isPhysicalResource; + } + + internal static bool IdentifyByRegEx( + string absoluteUri, + string queryString, + string applicationPath, + ref UrlAction result, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + var doRewrite = false; + + var rewriterConfig = RewriterConfiguration.GetConfig(); + + if (rewriterConfig != null) + { + var url = absoluteUri; // get local copy because it gets hacked around + + // Remove querystring if exists.. + if (queryString != string.Empty) + { + url = url.Replace(queryString, string.Empty); + } + + var rules = rewriterConfig.Rules; + if (rules == null) + { + throw new NullReferenceException("DotNetNuke.HttpModules.Config.RewriterRuleCollection is null"); + } + + for (var i = 0; i <= rules.Count - 1; i++) + { + // iterate the Config Rules looking for a match + var re = rules[i].GetRuleRegex(applicationPath); + if (re.IsMatch(url)) + { + var sendTo = rules[i].SendTo; + + // get a new rewritePath location + var rewritePath = RewriterUtils.ResolveUrl(applicationPath, re.Replace(url, sendTo)); // no rewrite path unless we match by regex the intended tab + var sesMatch = re.Match(url); + var sesUrlParams = sesMatch.Groups[2].Value; + + // a match by regex means it's probably not a 'friendly' Url, so assume at this stage that this request will end up a 301 + if (settings.UrlFormat == "advanced" && settings.RedirectUnfriendly) + { + result.Action = ActionType.CheckFor301; + } + + // if a match is found here, there is the potential for a 'friendlier' url + if (sesUrlParams.Trim().Length > 0) + { + sesUrlParams = sesUrlParams.Replace("\\", "/"); + var urlParams = sesUrlParams.Split('/'); + for (var x = 1; x <= urlParams.Length - 1; x++) { - // look for special case where the site root has a * value - string siteRootLookup = aliasPath + "::" + "*"; - using (tabDict.GetReadLock()) + if (urlParams[x].Trim().Length > 0 && + !urlParams[x].Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) { - found = tabDict.ContainsKey(siteRootLookup); - if (found) + rewritePath = rewritePath + "&" + urlParams[x].Replace(".aspx", string.Empty).Trim() + "="; + if (x < (urlParams.Length - 1)) { - isSiteRootMatch = true; - newUrl = tabDict[siteRootLookup]; - parmsSize++; // re-increase the parameter size - parmStart--; // shift the point of the parms starting back one + x += 1; + if (urlParams[x].Trim() != string.Empty) + { + rewritePath = rewritePath + urlParams[x].Replace(".aspx", string.Empty); + } } } } + } - if (found) - { - if (settings.ProcessRequestList != null) - { - newUrl = ReplaceDefaultPage(newUrl, url, settings.ProcessRequestList); - } + // add back the query string if it was there + rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); - // look for a plain match on the default.aspx page which indicates no more rewriting needs to be done - if (!isSiteRootMatch && (newUrl == Globals.glbDefaultPage || newUrl == Globals.glbDefaultPage + "[UseBase]")) - { - // the [UseBase] moniker is a shortcut hack. It's used to recognise pages which have been excluded - // from using Friendly Urls. The request will go on to be processed by the dnn siteurls.config processing. - // this stops the loop and exits the function - newUrl = newUrl.Replace("[UseBase]", string.Empty); // get rid of usebase hack pattern - SetRewriteParameters(ref result, newUrl); // set result - finished = true; - } - else - { - // 708 : move result rewrite set so that downstream functions know the tabid - SetRewriteParameters(ref result, newUrl); - - // found the correct rewrite page, now investigate whether there - // is part of the url path that needs to be converted to tab id's - // Multi Language Urls not being rewritten - if (parmsSize > 0) - { - bool rewriteParms = false; + // 832 : check for leading ~ - if not there, then redirect + if (sendTo.StartsWith("~")) + { + doRewrite = true; + SetRewriteParameters(ref result, rewritePath); + RedirectTokens.SetRedirectReasonAndAction(ref result, settings); + result.DoRewrite = true; + } + else + { + // we'll assume it's a 301 instead of a 302 + result.Action = ActionType.Redirect301; + result.DoRewrite = false; + result.Reason = RedirectReason.SiteUrls_Config_Rule; + result.FinalUrl = rewritePath; + } - // determine the url action and reason from embedded rewriting tokens - ActionType action; - RedirectReason reason; - string resultingUrl; - RedirectTokens.DetermineRedirectReasonAndAction( - newUrl, - result, - true, - settings, - out resultingUrl, - out reason, - out action); - newUrl = resultingUrl; - result.Action = action; - result.Reason = reason; + break; // exit loop, match found + } + } + } - // copy the parms into a separate array - var urlParms = new string[parmsSize]; - Array.ConstrainedCopy(splitUrl, parmStart, urlParms, 0, parmsSize); + return doRewrite; + } - if (!isSiteRootMatch && result.Reason == RedirectReason.User_Profile_Url) - { - result.Reason = RedirectReason.Not_Redirected; - newUrl = RedirectTokens.RemoveAnyRedirectTokensAndReasons(newUrl); - } + internal static bool IdentifyByTabPathEx( + string absoluteUri, + string queryString, + UrlAction result, + NameValueCollection queryStringCol, + FriendlyUrlSettings settings, + Guid parentTraceId) + { + string scheme = result.Scheme; + if (absoluteUri.StartsWith(scheme, StringComparison.InvariantCultureIgnoreCase)) + { + absoluteUri = absoluteUri.Substring(scheme.Length); + } - // 738 : check for custom module providers - // 894 : allow disable of custom url providers functionality - if (!rewriteParms && settings.EnableCustomProviders) - { - bool newAction; - - // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. - // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. - List messages = result.DebugMessages; - newUrl = RewriteParametersFromModuleProvider( - newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - settings, - out rewriteParms, - out newAction, - ref messages, - parentTraceId); - result.DebugMessages = messages; - if (newAction) - { - finished = true; - } - } - - // do a rewrite on the parameters from the stored parameter regex rewrites - if (!rewriteParms) - { - newUrl = RewriteParameters( - newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - out rewriteParms, - parentTraceId); - } - - if (rewriteParms && isSiteRootMatch) - { - // set rewrite parameters to take tabid for site root matches - SetRewriteParameters(ref result, newUrl); - } + // Remove QueryString if it exists in the Url value + if (queryString != string.Empty) + { + absoluteUri = absoluteUri.Replace(queryString, string.Empty); + } - // if the parms weren't rewritten by means of a regex, then process them normally - if (!rewriteParms && !isSiteRootMatch) - - // can only try other matches if it wasn't a site root match - { - // put those parms on the back of the url as a query string - string cultureCode; - newUrl = RewriteParameters( - newUrl, - tabKeyVal, - urlParms, - result, - langParms, - settings, - out cultureCode); - if (cultureCode != null) // set culture code if not already set - { - result.CultureCode = cultureCode; - } - } - - // now check if the request involved a page pageAndExtension, (.aspx) and shouldn't have - if (!finished) - { - // 944 : don't switch to 301 redirect if action already set to 404 - if ((settings.PageExtensionUsageType == PageExtensionUsageType.Never - || settings.PageExtensionUsageType == PageExtensionUsageType.PageOnly) & - hadExtension) - { - // 948 : use new 'no downgrade' method - result.SetActionWithNoDowngrade(ActionType.CheckFor301); - } - else - - // 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); - } - } + absoluteUri = HttpUtility.UrlDecode(absoluteUri); // decode the incoming request + string rewritePath = GetTabFromDictionary(absoluteUri, queryStringCol, settings, result, parentTraceId); - if (isSiteRootMatch && !finished) - - // when it was a site root match, this must be matched with a custom parameter regex - { - // only finished if the parms were rewritten by means of a regex rewrite - reWritten = rewriteParms; - finished = rewriteParms; - } - else - { - // rewriting done - reWritten = true; - finished = true; - } - } - else - { - // determine the url action and redirect reason from embedded tokens in the url rewrite path - string resultUrl; - RedirectReason reason; - ActionType action; - - // add back language parameters if they were there - if (string.IsNullOrEmpty(langParms) == false) - { - string[] parms = langParms.Split('/'); - if (parms.GetUpperBound(0) >= 1) - { - if (parms[0] == string.Empty && parms.GetUpperBound(0) > 1) - { - newUrl += "&" + parms[1] + "=" + parms[2]; - } - else - { - newUrl += "&" + parms[0] + "=" + parms[1]; - } - } - } - - RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, false, settings, - out resultUrl, out reason, - out action); - newUrl = resultUrl; - result.Reason = reason; - result.Action = action; + // put the query string back on the end + rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); + + // 810 : if a culture code is not specified in the rewrite path + if (result.DoRewrite && settings.ForcePortalDefaultLanguage && result.PortalId >= 0 && + rewritePath.Contains("language=") == false) + { + // add the portal default language to the rewrite path + PortalInfo portal = CacheController.GetPortal(result.PortalId, false); + + // DNN-3789 - culture is defined by GetPageLocale + string currentLocale = Localization.GetPageLocale(new PortalSettings(result.TabId, result.PortalAlias)).Name; + if (portal != null && !string.IsNullOrEmpty(currentLocale)) + { + AddLanguageCodeToRewritePath(ref rewritePath, currentLocale); + result.CultureCode = currentLocale; + result.DebugMessages.Add("Current Language code " + currentLocale + " added"); + } + } + + // set the rewrite path + result.RewritePath = rewritePath; + return result.DoRewrite; + } + + internal static bool IdentifyByTabQueryString(Uri requestUri, NameValueCollection queryStringCol, bool useFriendlyUrls, UrlAction result) + { + const bool doRewrite = false; + string requestedPath = requestUri.LocalPath; + + if (useFriendlyUrls) + { + // using friendly URls, so just nab the Tab id from the querystring + if (result.RedirectAllowed && requestedPath.EndsWith(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) + && (queryStringCol["tabId"] != null)) + { + result.Action = ActionType.CheckFor301; + result.Reason = RedirectReason.Unfriendly_Url_TabId; + } + } + + result.DoRewrite = doRewrite; + return doRewrite; + } + + /// + /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. + /// + /// + /// The path of the tab //admin//someothername. + /// + /// /// Duplicated in UrlMasterController.cs. + /// + internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) + { + var portal = PortalController.Instance.GetPortal(portalId); + var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portalId); + + // return false if AdminTabId is -1, it could happen when a portal is in the middle of importing + if (adminTab == null) + { + return false; + } + + string adminPageName = adminTab.TabName; + + // we should be checking that the tab path matches //Admin//pagename or //admin + // in this way we should avoid partial matches (ie //Administrators + if (tabPath.StartsWith("//" + adminPageName + "//", StringComparison.CurrentCultureIgnoreCase) + || string.Compare(tabPath, "//" + adminPageName, StringComparison.OrdinalIgnoreCase) == 0) + { + return true; + } + + return false; + } + + /// + /// Determines if the tab is excluded from FriendlyUrl Processing. + /// + /// + /// + /// If true, we are checking for rewriting purposes, if false, we are checking for friendly Url Generating. + /// + internal static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings settings, bool rewriting) + { + bool exclude = false; + string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLowerInvariant(); + + // 553 change for dnn 5.0 isAdminTab no longer returns true in any case, so + // check custom admin tab path header + // 811: allow for admin tabs to be friendly + if (settings.FriendlyAdminHostUrls == false && IsAdminTab(tab.PortalID, tab.TabPath, settings)) + { + exclude = true; + } + + if (!exclude && settings.UseBaseFriendlyUrls != null) + { + exclude = settings.UseBaseFriendlyUrls.ToLowerInvariant().Contains(tabPath); + } + + return exclude; + } + + /// + /// Checks for a current parameter belonging to one of the built in 'ctl' values. + /// + /// + /// + /// + /// Sets the Action parameter of the Result to 'CheckFor301' if suspected. Actual redirect taken care of by friendly url redirection logic. + internal static void RequestRedirectOnBuiltInUrl(string urlParm, string rewritePath, UrlAction result) + { + // on the lookout for items to potentially redirect + if ("terms|privacy|login|register".Contains(urlParm.ToLowerInvariant())) + { + // likely that this should be redirected, because we don't want ctl/terms, ctl/register, etc + result.Reason = RedirectReason.Built_In_Url; + result.Action = ActionType.CheckFor301; + result.DebugMessages.Add("Built-in Url found: " + rewritePath); + } + } + + /// + /// converts an array of Url path sections into the rewritten string of parameters for the requested Url. + /// + /// The current candidate for the rewritten tab path, as found in the tab dictionary. + /// The tabKey value which was used to find the current newUrl value. + /// The Url path (after the tab name) converted to an array. + /// The UrlAction parameter keeping track of the values. + /// The raw language/xx-XX values from the requested Url. + /// The current friendly url settings. + /// an out parameter identifying if a culture code was determined during the process. + /// + internal static string RewriteParameters( + string newUrl, + string tabKeyVal, + string[] urlParms, + UrlAction result, + string langParms, + FriendlyUrlSettings settings, + out string cultureCode) + { + cultureCode = null; // culture code is assigned from the langParms value, if it exists + if (urlParms != null) + { + // determine page extension value and usage + string pageExtension = settings.PageExtension; + + var parmString = new StringBuilder(); + bool valueField = false; + bool stripLoneParm = false; + int lastParmToProcessTo; + + string userIdParm = null; + var thisPortal = PortalController.Instance.GetPortal(result.PortalId); + + // check if there is more than one parm, and keep the value of the primary (first) parm + if (thisPortal.UserTabId == result.TabId || thisPortal.UserTabId == -1) + { + // 719 : shift to only remove last parm on pages with 'all' match + stripLoneParm = true; // 710 : don't put in username into rewritten parameters + userIdParm = "UserId"; + } + + // recheck firstParmLast - just because it is set to be that way in the config doesn't + // mean that the url will come in that way. + // first strip out any language parameters + if (langParms != null) + { + string[] langValues = langParms.TrimStart('/').Split('/'); + if (langValues.GetUpperBound(0) == 1) + { + int pos1 = -1, pos2 = -1; + for (int i = 0; i < urlParms.GetUpperBound(0); i++) + { + // match this part of the urlParms with the language parms + if (urlParms[i] == langValues[0] && urlParms[i + 1] == langValues[1]) + { + pos1 = i; + pos2 = i + 1; + break; + } + } + + if (pos1 > -1 && pos2 > -1) + { + // this hacky operation removes the language urls from the array + var temp = new List(urlParms); + temp.RemoveAt(pos2); + temp.RemoveAt(pos1); + urlParms = temp.ToArray(); + + // 656 : don't allow forced lower case of the culture identifier - always convert the case to aa-AA to match the standard + string cultureId = langValues[1]; + Match cultureMatch = CultureMatchRegex.Match(cultureId); + if (cultureMatch.Success) + { + cultureId = cultureMatch.Groups[1].Value + "-" + + cultureMatch.Groups[2].ToString().ToUpper(); + } + + // set procedure level culture code, which indicates a language was found in the path + cultureCode = cultureId; + } + } + } + + lastParmToProcessTo = urlParms.GetUpperBound(0); + + // build up the parameters rewrite string by iterating through the key/value pairs in the Url + // and turn them into &key=value pairs. + string keyName = null; + bool skip = false; + bool isUserParm = false; + for (int i = 0; i <= lastParmToProcessTo; i++) + { + string thisParm = urlParms[i]; + + // here's the thing - we either take the last one and put it at the start, or just go two-by-two + if (!thisParm.Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + { + if (thisParm.Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) + { + skip = true; + + // discovering the tabid in the list of parameters means that + // it was likely a request for an old-style tab url that + // found a retVal due to match in the tab path. + // while this may mean a 301, we definitely don't want to force a 301, + // just investigate it and let the 301 redirect logic work it out + // we also want to skip the next parameter, because it is the tabid value + if (result.Reason != RedirectReason.Custom_Redirect) + { + // only reason not to let this one through and count on the + // friendly url checking code is if it was a custom redirect set up + result.Reason = RedirectReason.Not_Redirected; + result.Action = ActionType.CheckFor301; + + // set the value field back to false, because, even if the parameter handling is + // first parm last, this was an old style URl desitned to be redirected. + // and we would expect old-style urls to have the correct parameter order + // note this assumes tabid is the first parm in the list. + valueField = false; + } + } + else if (!skip) + { + bool extReplaced; + string urlParm = CleanExtension(thisParm, pageExtension, out extReplaced); - if (settings.EnableCustomProviders && ExtensionUrlProviderController.CheckForAlwaysCallProviders( - result.PortalId, - result.TabId, - settings, - parentTraceId)) - { - bool newAction; - - // newAction tracks whether or not a new 'action' (ie 301, 404, etc) has been requested. - // call the module friendly url providers. Note that the rewriteParms value will be changed if there is a rewrite. - string[] urlParms = new List().ToArray(); // empty parm array - if (string.IsNullOrEmpty(langParms) == false) - { - urlParms = langParms.Split('/'); - - // split the lang parms into the url Parms - } - - bool rewriteParms; - List messages = result.DebugMessages; - newUrl = RewriteParametersFromModuleProvider( - newUrl, - tabKeyVal, - urlParms, - isSiteRootMatch, - result, - settings, - out rewriteParms, - out newAction, - ref messages, - parentTraceId); - result.DebugMessages = messages; - } + if (extReplaced && pageExtension == string.Empty) // replacing a .aspx extension + { + result.Action = ActionType.CheckFor301; + } - // this is a page only, no parameters to deal with - // 944 : don't downgrade to redirect if the current action is a 404 (see 948 for new solution to 944) - if (settings.PageExtensionUsageType == PageExtensionUsageType.Never & hadExtension) - { - // potentially a 301 replaced because shouldn't be using page extensions - // 948 : check to prevent action downgrade, in case already set to redirect - result.SetActionWithNoDowngrade(ActionType.CheckFor301); - } - else - { - // 866 : redirect back from no extension to extension if it didn't have one - if (settings.PageExtensionUsageType != PageExtensionUsageType.Never && - hadExtension == false) - { - result.SetActionWithNoDowngrade(ActionType.CheckFor301); - } - } - - // rewriting done - reWritten = true; - finished = true; - } + if (valueField) + { + // this parameter is going into the value half of a &key=value pair + parmString.Append("="); + parmString.Append(urlParm); + valueField = false; + if (isUserParm) + { + int userIdVal; + int.TryParse(urlParm, out userIdVal); + isUserParm = false; } - - if (finished) + + // 786 : redirect ctl/terms etc + if (keyName != null && keyName.ToLowerInvariant() == "ctl") { - break; + RequestRedirectOnBuiltInUrl(urlParm, parmString.ToString(), result); + } + } + else + { + // this parameter is going into the key half of a &key=value pair + keyName = urlParm; + parmString.Append("&"); + parmString.Append(urlParm); + valueField = true; + + // if we are looking for a userid parameter in this querystring, check for a match + if (userIdParm != null) + { + if (string.Compare(keyName, userIdParm, StringComparison.OrdinalIgnoreCase) == 0) + { + isUserParm = true; + } } } } + else if (skip) + { + skip = false; + } } } - // next, try forming up a key based on alias1/alias2/tabpath - if (!finished) + // add back language parameters if they were found + AddLanguageCodeToRewritePath(ref newUrl, cultureCode); + + // add on the parameter string + newUrl += parmString.ToString(); + + if (stripLoneParm) { - curAliasPathDepth += 1; - - // gone too deep - if ((curAliasPathDepth > maxAliasPathDepth) && !reWritten) + newUrl = UrlParamsRegex.Replace(newUrl, "&"); + if (newUrl.EndsWith("&")) { - // no hope of finding it then - if (!Globals.ServicesFrameworkRegex.IsMatch(url) && result.RedirectAllowed) + newUrl = newUrl.Substring(0, newUrl.Length - 1); + } + } + + // chop the last char off if it is an empty parameter + if (newUrl[newUrl.Length - 1] == '&') + { + newUrl = newUrl.Substring(0, newUrl.Length - 1); + } + } + + return newUrl; + } + + /// + /// Scans the collection of Rewrite Parameter rules, and rewrites the parameters if a match is found. + /// + /// + /// + /// + /// + /// + /// + /// + /// The new Url with the parameters rewritten onto the end of hte old Url. + internal static string RewriteParameters( + string newUrl, + string tabKeyVal, + string[] urlParms, + bool isSiteRoot, + UrlAction urlAction, + out bool rewriteParms, + Guid parentTraceId) + { + string result = newUrl; + rewriteParms = false; + + // get the actions from the cache + var messages = new List(); + Dictionary> rewriteActions = CacheController.GetParameterRewrites( + urlAction.PortalId, + ref messages, parentTraceId); + if (messages == null) + { + messages = new List(); + } + + try + { + if (rewriteActions != null && rewriteActions.Count > 0) + { + SharedList tabRewrites = null; + Match tabMatch = TabIdRegex.Match(newUrl); + if (tabMatch.Success) + { + string rawTabId = tabMatch.Groups["tabid"].Value; + int tabId; + if (int.TryParse(rawTabId, out tabId)) { - // nothing left to try - result.Action = (settings.DeletedTabHandlingType == DeletedTabHandlingType.Do404Error) - ? ActionType.Output404 - : ActionType.Redirect301; - if (result.Action == ActionType.Redirect301) + if (rewriteActions.ContainsKey(tabId)) { - result.Reason = RedirectReason.Deleted_Page; - result.DoRewrite = true; - result.FinalUrl = Globals.AddHTTP(result.PortalAlias.HTTPAlias + "/"); - reWritten = true; + // find the right set of rewrite actions for this tab + tabRewrites = rewriteActions[tabId]; + } + } + } + + if (rewriteActions.ContainsKey(AllTabsRewrite)) // -1 means 'all tabs' - rewriting across all tabs + { + // initialise to empty collection if there are no specific tab rewrites + if (tabRewrites == null) + { + tabRewrites = new SharedList(); + } + + // add in the all rewrites + SharedList allRewrites = rewriteActions[AllTabsRewrite]; + foreach (ParameterRewriteAction rewrite in allRewrites) + { + tabRewrites.Add(rewrite); // add the 'all' range to the tab range + } + } + + if (isSiteRoot && rewriteActions.ContainsKey(SiteRootRewrite)) + { + // initialise to empty collection if there are no specific tab rewrites + if (tabRewrites == null) + { + tabRewrites = new SharedList(); + } + + SharedList siteRootRewrites = rewriteActions[SiteRootRewrite]; + foreach (ParameterRewriteAction rewrite in siteRootRewrites) + { + tabRewrites.Add(rewrite); // add the site root rewrites to the collection + } + } + + // get the parms as a string + string parms = string.Join("/", urlParms); + + if (tabRewrites != null && tabRewrites.Count > 0) + { + // process each one until a match is found + foreach (ParameterRewriteAction rewrite in tabRewrites) + { + var parmRegex = RegexUtils.GetCachedRegex(rewrite.LookFor, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + // check the match, if a match found, do the replacement + if (parmRegex.IsMatch(parms)) + { + // rewrite the parameter + string sendTo = rewrite.RewriteTo; + string parmsOriginal = parms; + + // replace hte parameter with the rewrite string + parms = parmRegex.Replace(parms, sendTo); + messages.Add(rewrite.Name + " rewrite match (" + parmsOriginal + "), replaced to : " + parms); + + // makes sure the newUrl has got a trailing ampersand or a ? to start the query string + if (newUrl.Contains("?")) + { + if (newUrl.EndsWith("&") == false) + { + newUrl += "&"; + } + } + else // need to start the querystring off (592: allow for custom rewrites on site root) + { + newUrl += "?"; + } + + // makes sure the new parms string hasn't got a starting ampersand + if (parms.StartsWith("&")) + { + parms = parms.Substring(1); + } + + // parameters are added to the back fo the newUrl + newUrl += parms; + + // it's a rewrite, all right + rewriteParms = true; + result = newUrl; + urlAction.CustomParmRewrite = true; + break; } - } - break; + messages.Add(rewrite.Name + " rewrite not matched (" + parms + ")"); + } } } } - - result.FriendlyRewrite = reWritten; - result.DoRewrite = reWritten; - return newUrl; - } - - internal static void GetUrlWithQuerystring(HttpRequest request, Uri requestUri, out string fullUrl, out string querystring) - { - // 699: incorrect encoding in absoluteUri.ToString() - string urlWoutQuery = requestUri.AbsoluteUri; - if (requestUri.Query != string.Empty) - { - urlWoutQuery = urlWoutQuery.Replace(requestUri.Query, string.Empty); - - // replace the querystring on the reuqest absolute Uri - } - - // 926 : do not use querystring.toString() because of encoding errors that restul, - // the encoding type is changed from utf-8 to latin-1 - querystring = requestUri.Query; - - // get results - fullUrl = urlWoutQuery; - if (fullUrl.EndsWith("/_noext.aspx", StringComparison.InvariantCultureIgnoreCase)) + catch (Exception ex) { - fullUrl = fullUrl.Replace("_noext.aspx", string.Empty); - - // replace this marker pattern so it looks as though it isn't there *(leave on trailing slash) + Services.Exceptions.Exceptions.LogException(ex); + string error = "Exception: " + ex.Message + "\n" + ex.StackTrace; + messages.Add(error); } - - if (querystring != string.Empty) + finally { - // set up the querystring and the fullUrl to include the querystring - if (querystring.StartsWith("?") == false) - { - querystring = "?" + querystring; - } - - fullUrl += querystring; + // post messages to debug output + urlAction.DebugMessages.AddRange(messages); } + + return result; } - /// - /// Identifies a request for a physical file on the system. - /// - /// The Physical Path propery of the request. - /// - /// - /// - /// - /// - /// - /// - /// - internal static void IdentifyByPhysicalResource( - string physicalPath, - string fullUrl, - NameValueCollection queryStringCol, - ref UrlAction result, - bool useFriendlyUrls, - FriendlyUrlSettings settings, - out bool isPhysicalResource, - out bool checkFurtherForRewrite, - Guid parentTraceId) + private static string AddQueryStringToRewritePath(string rewritePath, string queryString) { - isPhysicalResource = false; - checkFurtherForRewrite = true; - if (File.Exists(physicalPath) && physicalPath.EndsWith("\\_noext.aspx") == false) + // now add back querystring if they existed + if (queryString != string.Empty) { - // resource found - string appPath = Globals.ApplicationMapPath + "\\default.aspx"; - bool isDefaultAspxPath = false; - if (string.Compare(physicalPath, appPath, StringComparison.OrdinalIgnoreCase) != 0) + bool rewritePathHasQuery = rewritePath.IndexOf("?", StringComparison.Ordinal) != -1; + if (queryString.StartsWith("?")) { - string aliasQs; - if (AdvancedUrlRewriter.CheckForChildPortalRootUrl(fullUrl, result, out aliasQs)) + queryString = queryString.Substring(1); + } + + string[] parms = queryString.Split('&'); + + // iterate through the array of parameters + for (int i = 0; i < parms.Length; i++) + { + bool hasValue = false; + + // get parameter name + string parmName = parms[i]; + + // check if parm name contains a value as well + if (parmName.IndexOf("=", StringComparison.Ordinal) != -1) { - result.DebugMessages.Add("Child Portal Alias Root Identified"); + // snip off the =value part of the parm + parmName = parmName.Substring(0, parmName.IndexOf("=", StringComparison.Ordinal)); + hasValue = true; } - else + + // 597 : do a compare with the '=' on the end to only + // compare the entire parmname, not just the start + string comparePath1 = "?" + parmName.ToLowerInvariant(); + string comparePath2 = "&" + parmName.ToLowerInvariant(); + if (hasValue) { - // it's not the default.aspx path or a child alias request, so we haven't identifed the resource - isPhysicalResource = true; - checkFurtherForRewrite = false; - result.DebugMessages.Add("Resource Identified No Rewrite Used"); + comparePath1 += "="; + comparePath2 += "="; } - } - else - { - isDefaultAspxPath = true; - } - if (isDefaultAspxPath) // it is the default aspx path - { - // check to see if it is a /default.aspx?key=value url (not just default.aspx, nor a child alias) - if (queryStringCol != null && queryStringCol.Count > 0) + // check if parameter already exists in the rewrite path + // we only want to add the querystring back on if the + // query string keys were not already shown in the friendly + // url path + if (!rewritePath.ToLowerInvariant().Contains(comparePath1) + && !rewritePath.ToLowerInvariant().Contains(comparePath2)) { - // when there is a query string supplied, we don't need to rewrite - if (useFriendlyUrls) + // 622 : remove encoding from querystring paths + // 699 : reverses 622 because works from Request.QUeryString instead of Request.Url.Query + // string queryStringPiece = System.Web.HttpUtility.UrlDecode(parms[i]); + string queryStringPiece = parms[i]; + + // no decoding - querystring passes through rewriting process untouched + // add parameter to SendTo value + if (rewritePathHasQuery) { - // using friendly URls, so just nab the Tab id from the querystring - if (queryStringCol["tabId"] != null) - { - if (result.RedirectAllowed) - { - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Unfriendly_Url_TabId; - } - } + rewritePath = rewritePath + "&" + queryStringPiece; + } + else + { + rewritePath = rewritePath + "?" + queryStringPiece; + rewritePathHasQuery = true; } - - result.DoRewrite = false; - checkFurtherForRewrite = false; - - // no more checking for rewrites, we have our physical file and our query string - // the default.aspx is still a physical resource, but we want to do the rest of the processing - } - else - { - // could be either default.aspx with no querystring, or a child portal alias root - // if 301 redirects are on, then we want to rewrite and replace this Url to include information like language modifiers - // so return false to indicate that the physical resource couldn't be identified - isPhysicalResource = !useFriendlyUrls; } } } - // mark as physical request - result.IsPhysicalResource = isPhysicalResource; + return rewritePath; } - internal static bool IdentifyByRegEx( - string absoluteUri, - string queryString, - string applicationPath, - ref UrlAction result, - FriendlyUrlSettings settings, - Guid parentTraceId) + private static string CheckIfPortalAlias(string url, NameValueCollection querystringCol, UrlAction result, FriendlyUrlSettings settings, SharedDictionary tabDict) { - var doRewrite = false; + string newUrl = url; + bool reWritten = false; - var rewriterConfig = RewriterConfiguration.GetConfig(); + string defaultPage = Globals.glbDefaultPage.ToLowerInvariant(); + string portalAliasUrl = url.ToLowerInvariant().Replace("/" + defaultPage, string.Empty); - if (rewriterConfig != null) + // if there is a straight match on a portal alias, it's the home page for that portal requested + var portalAlias = PortalAliasController.Instance.GetPortalAlias(portalAliasUrl); + if (portalAlias != null) { - var url = absoluteUri; // get local copy because it gets hacked around - - // Remove querystring if exists.. - if (queryString != string.Empty) + // special case : sometimes, some servers issue root/default.aspx when root/ was requested, sometimes not. It depends + // on other server software installed (apparently) + // so check the raw Url and the url, and see if they are the same except for the /default.aspx + string rawUrl = result.RawUrl; + if (url.ToLowerInvariant().EndsWith(rawUrl + defaultPage.ToLowerInvariant())) { - url = url.Replace(queryString, string.Empty); + // special case - change the url to be equal to the raw Url + url = url.Substring(0, url.Length - defaultPage.Length); } - var rules = rewriterConfig.Rules; - if (rules == null) + if (settings.RedirectDefaultPage + && url.EndsWith("/" + defaultPage, StringComparison.InvariantCultureIgnoreCase) + && result.RedirectAllowed) { - throw new NullReferenceException("DotNetNuke.HttpModules.Config.RewriterRuleCollection is null"); + result.Reason = RedirectReason.Site_Root_Home; + result.FinalUrl = Globals.AddHTTP(portalAliasUrl + "/"); + result.Action = ActionType.Redirect301; } - - for (var i = 0; i <= rules.Count - 1; i++) + else { - // iterate the Config Rules looking for a match - var re = rules[i].GetRuleRegex(applicationPath); - if (re.IsMatch(url)) + // special case -> look in the tabdict for a blank intercept + // 735 : switch to custom method for getting portal + PortalInfo portal = CacheController.GetPortal(portalAlias.PortalID, true); + if (portal.HomeTabId == -1) + { + string tabKey = url; + if (tabKey.EndsWith("/")) + { + tabKey = tabKey.TrimEnd('/'); + } + + tabKey += "::"; + using (tabDict.GetReadLock()) + { + if (tabDict.ContainsKey(tabKey)) + { + newUrl = tabDict[tabKey]; + reWritten = true; + } + } + + // if no home tab, but matched a portal alias, and no trailing /default.aspx + // and no 'newUrl' value because not rewritten, then append the /default.aspx + // and ask for a rewrite on that one. + // DNNDEV-27291 + if (reWritten == false) + { + // Need to determine if this is a child alias + newUrl = "/" + Globals.glbDefaultPage; + reWritten = true; + } + } + else { - var sendTo = rules[i].SendTo; - - // get a new rewritePath location - var rewritePath = RewriterUtils.ResolveUrl(applicationPath, re.Replace(url, sendTo)); // no rewrite path unless we match by regex the intended tab - var sesMatch = re.Match(url); - var sesUrlParams = sesMatch.Groups[2].Value; - - // a match by regex means it's probably not a 'friendly' Url, so assume at this stage that this request will end up a 301 - if (settings.UrlFormat == "advanced" && settings.RedirectUnfriendly) + // set rewrite to home page of site + // 760: check for portal alias specific culture before choosing home tabid + bool checkForCustomAlias = false; + bool customTabAlias = false; + + // check for culture-specific aliases + string culture = null; + var portalAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).ToList(); + + // if there are chosen portal aliases, check to see if the found alias is one of them + // if not, then will check for a custom alias per tab + if (!portalAliases.ContainsAlias(portal.PortalID, portalAlias.HTTPAlias)) { - result.Action = ActionType.CheckFor301; + checkForCustomAlias = true; } - - // if a match is found here, there is the potential for a 'friendlier' url - if (sesUrlParams.Trim().Length > 0) + else { - sesUrlParams = sesUrlParams.Replace("\\", "/"); - var urlParams = sesUrlParams.Split('/'); - for (var x = 1; x <= urlParams.Length - 1; x++) + // check for a specific culture for the alias + culture = portalAliases.GetCultureByPortalIdAndAlias(portal.PortalID, portalAlias.HTTPAlias); + } + + if (checkForCustomAlias) + { + // ok, this isnt' a chosen portal alias, check the list of custom aliases + List customAliasesForTabs = TabIndexController.GetCustomPortalAliases(settings); + if (customAliasesForTabs != null && customAliasesForTabs.Contains(portalAlias.HTTPAlias.ToLowerInvariant())) { - if (urlParams[x].Trim().Length > 0 && - !urlParams[x].Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) + // ok, the alias is used as a custom tab, so now look in the dictionary to see if it's used a 'root' context + string tabKey = url.ToLowerInvariant(); + if (tabKey.EndsWith("/")) { - rewritePath = rewritePath + "&" + urlParams[x].Replace(".aspx", string.Empty).Trim() + "="; - if (x < (urlParams.Length - 1)) + tabKey = tabKey.TrimEnd('/'); + } + + if (tabKey.EndsWith("/default.aspx")) + { + tabKey = tabKey.Substring(0, tabKey.Length - 13); // 13 = "/default.aspx".length + } + + tabKey += "::"; + using (tabDict.GetReadLock()) + { + if (tabDict.ContainsKey(tabKey)) { - x += 1; - if (urlParams[x].Trim() != string.Empty) - { - rewritePath = rewritePath + urlParams[x].Replace(".aspx", string.Empty); - } + newUrl = tabDict[tabKey]; + reWritten = true; + customTabAlias = true; // this alias is used as the alias for a custom tab } } } } - - // add back the query string if it was there - rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); - // 832 : check for leading ~ - if not there, then redirect - if (sendTo.StartsWith("~")) - { - doRewrite = true; - SetRewriteParameters(ref result, rewritePath); - RedirectTokens.SetRedirectReasonAndAction(ref result, settings); - result.DoRewrite = true; - } - else + if (customTabAlias == false) { - // we'll assume it's a 301 instead of a 302 - result.Action = ActionType.Redirect301; - result.DoRewrite = false; - result.Reason = RedirectReason.SiteUrls_Config_Rule; - result.FinalUrl = rewritePath; + int tabId; + if (!string.IsNullOrEmpty(querystringCol["TabId"])) + { + tabId = Convert.ToInt32(querystringCol["TabId"]); + result.Action = ActionType.CheckFor301; + } + else + { + // not a custom alias for a specific tab, so it must be the home page for the portal we identified, + // if its first request and splash page defined, then redirec to splash page. + if (portal.SplashTabId > Null.NullInteger && HttpContext.Current != null && + !HttpContext.Current.Request.Cookies.AllKeys.Contains("SplashPageView")) + { + tabId = portal.SplashTabId; + HttpContext.Current.Response.Cookies.Add( + new HttpCookie("SplashPageView", "true") { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); + result.Action = ActionType.Redirect302; + result.Reason = RedirectReason.Requested_SplashPage; + } + else + { + tabId = portal.HomeTabId; + } + + if (culture == null) + { + culture = portal.DefaultLanguage; // set culture to default if not found specifically + } + else + { + // if there is a specific culture for this alias, and it's different to the default language, then + // go check for a specific culture home page (5.5 and later) + tabId = TabPathHelper.GetHomePageTabIdForCulture( + portal.DefaultLanguage, + portal.PortalID, + culture, + tabId); + } + } + + // see if there is a skin for the alias/culture combination + string skin = TabPathHelper.GetTabAliasSkinForTabAndAlias( + portalAlias.PortalID, + portalAlias.HTTPAlias, culture); + if (string.IsNullOrEmpty(skin) == false) + { + newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty, "skinSrc=" + skin); + } + else + { + newUrl = Globals.glbDefaultPage + TabIndexController.CreateRewritePath(tabId, string.Empty); + } + + // DNN-3789 always call this method as culture is defined by GetPageLocale + AddLanguageCodeToRewritePath(ref newUrl, culture); + + // add on language specified by current portal alias + reWritten = true; } - - break; // exit loop, match found } } + + if (reWritten) + { + // check for replaced to site root from /default.aspx + // 838 set redirect reason and action from result + SetRewriteParameters(ref result, newUrl); + ActionType action; + RedirectReason reason; + string resultingUrl; + RedirectTokens.DetermineRedirectReasonAndAction(newUrl, result, true, settings, out resultingUrl, out reason, out action); + newUrl = resultingUrl; + result.Action = action; + result.Reason = reason; + } } - return doRewrite; + return newUrl; } - internal static bool IdentifyByTabPathEx( - string absoluteUri, - string queryString, - UrlAction result, - NameValueCollection queryStringCol, - FriendlyUrlSettings settings, - Guid parentTraceId) + private static bool CheckSpecialCase(string tabKeyVal, SharedDictionary tabDict) { - string scheme = result.Scheme; - if (absoluteUri.StartsWith(scheme, StringComparison.InvariantCultureIgnoreCase)) - { - absoluteUri = absoluteUri.Substring(scheme.Length); - } - - // Remove QueryString if it exists in the Url value - if (queryString != string.Empty) + bool found = false; + int pathStart = tabKeyVal.LastIndexOf("::", StringComparison.Ordinal); // look for portal alias separator + int lastPath = tabKeyVal.LastIndexOf('/'); + + // get any path separator in the tab path portion + if (pathStart > lastPath) { - absoluteUri = absoluteUri.Replace(queryString, string.Empty); + lastPath = pathStart; } - - absoluteUri = HttpUtility.UrlDecode(absoluteUri); // decode the incoming request - string rewritePath = GetTabFromDictionary(absoluteUri, queryStringCol, settings, result, parentTraceId); - - // put the query string back on the end - rewritePath = AddQueryStringToRewritePath(rewritePath, queryString); - - // 810 : if a culture code is not specified in the rewrite path - if (result.DoRewrite && settings.ForcePortalDefaultLanguage && result.PortalId >= 0 && - rewritePath.Contains("language=") == false) - { - // add the portal default language to the rewrite path - PortalInfo portal = CacheController.GetPortal(result.PortalId, false); - // DNN-3789 - culture is defined by GetPageLocale - string currentLocale = Localization.GetPageLocale(new PortalSettings(result.TabId, result.PortalAlias)).Name; - if (portal != null && !string.IsNullOrEmpty(currentLocale)) - { - AddLanguageCodeToRewritePath(ref rewritePath, currentLocale); - result.CultureCode = currentLocale; - result.DebugMessages.Add("Current Language code " + currentLocale + " added"); - } - } - - // set the rewrite path - result.RewritePath = rewritePath; - return result.DoRewrite; - } + if (lastPath >= 0) + { + int defaultStart = tabKeyVal.IndexOf("default", lastPath, StringComparison.OrdinalIgnoreCase); - internal static bool IdentifyByTabQueryString(Uri requestUri, NameValueCollection queryStringCol, bool useFriendlyUrls, UrlAction result) - { - const bool doRewrite = false; - string requestedPath = requestUri.LocalPath; + // no .aspx on the end anymore + if (defaultStart > 0 && defaultStart > lastPath) - if (useFriendlyUrls) - { - // using friendly URls, so just nab the Tab id from the querystring - if (result.RedirectAllowed && requestedPath.EndsWith(Globals.glbDefaultPage, StringComparison.OrdinalIgnoreCase) - && (queryStringCol["tabId"] != null)) + // there is a default in the path, and it's not the entire path (ie pagnamedefault and not default) { - result.Action = ActionType.CheckFor301; - result.Reason = RedirectReason.Unfriendly_Url_TabId; - } - } - - result.DoRewrite = doRewrite; - return doRewrite; - } + tabKeyVal = tabKeyVal.Substring(0, defaultStart); - /// - /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. - /// - /// - /// The path of the tab //admin//someothername. - /// - /// /// Duplicated in UrlMasterController.cs. - /// - internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) - { - var portal = PortalController.Instance.GetPortal(portalId); - var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portalId); + // get rid of the default.aspx part + using (tabDict.GetReadLock()) + { + found = tabDict.ContainsKey(tabKeyVal); - // return false if AdminTabId is -1, it could happen when a portal is in the middle of importing - if (adminTab == null) - { - return false; + // lookup the tabpath in the tab dictionary again + } + } } - string adminPageName = adminTab.TabName; - - // we should be checking that the tab path matches //Admin//pagename or //admin - // in this way we should avoid partial matches (ie //Administrators - if (tabPath.StartsWith("//" + adminPageName + "//", StringComparison.CurrentCultureIgnoreCase) - || string.Compare(tabPath, "//" + adminPageName, StringComparison.OrdinalIgnoreCase) == 0) - { - return true; - } - - return false; + return found; } - /// - /// Determines if the tab is excluded from FriendlyUrl Processing. - /// - /// - /// - /// If true, we are checking for rewriting purposes, if false, we are checking for friendly Url Generating. - /// - internal static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings settings, bool rewriting) + private static UserInfo GetUser(int portalId, string vanityUrl) { - bool exclude = false; - string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLowerInvariant(); - - // 553 change for dnn 5.0 isAdminTab no longer returns true in any case, so - // check custom admin tab path header - // 811: allow for admin tabs to be friendly - if (settings.FriendlyAdminHostUrls == false && IsAdminTab(tab.PortalID, tab.TabPath, settings)) - { - exclude = true; - } + string cacheKey = string.Format(CacheController.VanityUrlLookupKey, portalId); + var vanityUrlLookupDictionary = CBO.GetCachedObject>( + new CacheItemArgs(cacheKey, 20, CacheItemPriority.High, portalId), + c => new Dictionary()); - if (!exclude && settings.UseBaseFriendlyUrls != null) + if (!vanityUrlLookupDictionary.ContainsKey(vanityUrl)) { - exclude = settings.UseBaseFriendlyUrls.ToLowerInvariant().Contains(tabPath); + vanityUrlLookupDictionary[vanityUrl] = UserController.GetUserByVanityUrl(portalId, vanityUrl); } - return exclude; + return vanityUrlLookupDictionary[vanityUrl]; } - /// - /// Checks for a current parameter belonging to one of the built in 'ctl' values. - /// - /// - /// - /// - /// Sets the Action parameter of the Result to 'CheckFor301' if suspected. Actual redirect taken care of by friendly url redirection logic. - internal static void RequestRedirectOnBuiltInUrl(string urlParm, string rewritePath, UrlAction result) + private static bool CheckTabPath(string tabKeyVal, UrlAction result, FriendlyUrlSettings settings, SharedDictionary tabDict, ref string newUrl) { - // on the lookout for items to potentially redirect - if ("terms|privacy|login|register".Contains(urlParm.ToLowerInvariant())) + bool found; + string userParam = string.Empty; + string tabLookUpKey = tabKeyVal; + using (tabDict.GetReadLock()) { - // likely that this should be redirected, because we don't want ctl/terms, ctl/register, etc - result.Reason = RedirectReason.Built_In_Url; - result.Action = ActionType.CheckFor301; - result.DebugMessages.Add("Built-in Url found: " + rewritePath); + found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary } - } - /// - /// converts an array of Url path sections into the rewritten string of parameters for the requested Url. - /// - /// The current candidate for the rewritten tab path, as found in the tab dictionary. - /// The tabKey value which was used to find the current newUrl value. - /// The Url path (after the tab name) converted to an array. - /// The UrlAction parameter keeping track of the values. - /// The raw language/xx-XX values from the requested Url. - /// The current friendly url settings. - /// an out parameter identifying if a culture code was determined during the process. - /// - internal static string RewriteParameters( - string newUrl, - string tabKeyVal, - string[] urlParms, - UrlAction result, - string langParms, - FriendlyUrlSettings settings, - out string cultureCode) - { - cultureCode = null; // culture code is assigned from the langParms value, if it exists - if (urlParms != null) + // special case, if no extensions and the last part of the tabKeyVal contains default.aspx, then + // split off the default.aspx part and try again - compensating for gemini issue http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=8651&PROJID=39 + if (!found && settings.PageExtensionUsageType != PageExtensionUsageType.AlwaysUse) { - // determine page extension value and usage - string pageExtension = settings.PageExtension; + found = CheckSpecialCase(tabLookUpKey, tabDict); + } - var parmString = new StringBuilder(); - bool valueField = false; - bool stripLoneParm = false; - int lastParmToProcessTo; + // Check for VanityUrl + var doNotRedirectRegex = RegexUtils.GetCachedRegex(settings.DoNotRedirectRegex); + if (!found && !Globals.ServicesFrameworkRegex.IsMatch(result.RawUrl) && !doNotRedirectRegex.IsMatch(result.RawUrl)) + { + string[] urlParams = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None); + if (urlParams.Length > 1) + { + // Extract the first Url parameter + string tabPath = urlParams[1]; - string userIdParm = null; - var thisPortal = PortalController.Instance.GetPortal(result.PortalId); + var urlSegments = tabPath.Split('/'); - // check if there is more than one parm, and keep the value of the primary (first) parm - if (thisPortal.UserTabId == result.TabId || thisPortal.UserTabId == -1) - { - // 719 : shift to only remove last parm on pages with 'all' match - stripLoneParm = true; // 710 : don't put in username into rewritten parameters - userIdParm = "UserId"; - } + string prefix = urlSegments[0]; - // recheck firstParmLast - just because it is set to be that way in the config doesn't - // mean that the url will come in that way. - // first strip out any language parameters - if (langParms != null) - { - string[] langValues = langParms.TrimStart('/').Split('/'); - if (langValues.GetUpperBound(0) == 1) + if (prefix == settings.VanityUrlPrefix && urlSegments.Length > 1) { - int pos1 = -1, pos2 = -1; - for (int i = 0; i < urlParms.GetUpperBound(0); i++) - { - // match this part of the urlParms with the language parms - if (urlParms[i] == langValues[0] && urlParms[i + 1] == langValues[1]) - { - pos1 = i; - pos2 = i + 1; - break; - } - } - - if (pos1 > -1 && pos2 > -1) + string vanityUrl = urlSegments[1]; + + // check if its a vanityUrl + var user = GetUser(PortalController.GetEffectivePortalId(result.PortalId), vanityUrl); + if (user != null) { - // this hacky operation removes the language urls from the array - var temp = new List(urlParms); - temp.RemoveAt(pos2); - temp.RemoveAt(pos1); - urlParms = temp.ToArray(); - - // 656 : don't allow forced lower case of the culture identifier - always convert the case to aa-AA to match the standard - string cultureId = langValues[1]; - Match cultureMatch = CultureMatchRegex.Match(cultureId); - if (cultureMatch.Success) + userParam = "UserId=" + user.UserID.ToString(); + + // Get the User profile Tab + var portal = PortalController.Instance.GetPortal(result.PortalId); + var profilePage = TabController.Instance.GetTab(portal.UserTabId, result.PortalId, false); + + FriendlyUrlOptions options = UrlRewriterUtils.GetOptionsFromSettings(settings); + string profilePagePath = TabPathHelper.GetFriendlyUrlTabPath(profilePage, options, Guid.NewGuid()); + + // modify lookup key; + tabLookUpKey = tabLookUpKey.Replace("::" + string.Format("{0}/{1}", settings.VanityUrlPrefix, vanityUrl), "::" + profilePagePath.TrimStart('/').ToLowerInvariant()); + + using (tabDict.GetReadLock()) { - cultureId = cultureMatch.Groups[1].Value + "-" + - cultureMatch.Groups[2].ToString().ToUpper(); + found = tabDict.ContainsKey(tabLookUpKey); // lookup the tabpath in the tab dictionary } - - // set procedure level culture code, which indicates a language was found in the path - cultureCode = cultureId; } } } + } - lastParmToProcessTo = urlParms.GetUpperBound(0); - - // build up the parameters rewrite string by iterating through the key/value pairs in the Url - // and turn them into &key=value pairs. - string keyName = null; - bool skip = false; - bool isUserParm = false; - for (int i = 0; i <= lastParmToProcessTo; i++) + if (found) + { + using (tabDict.GetReadLock()) { - string thisParm = urlParms[i]; - - // here's the thing - we either take the last one and put it at the start, or just go two-by-two - if (!thisParm.Equals(Globals.glbDefaultPage, StringComparison.InvariantCultureIgnoreCase)) - { - if (thisParm.Equals("tabid", StringComparison.InvariantCultureIgnoreCase)) - { - skip = true; - - // discovering the tabid in the list of parameters means that - // it was likely a request for an old-style tab url that - // found a retVal due to match in the tab path. - // while this may mean a 301, we definitely don't want to force a 301, - // just investigate it and let the 301 redirect logic work it out - // we also want to skip the next parameter, because it is the tabid value - if (result.Reason != RedirectReason.Custom_Redirect) - { - // only reason not to let this one through and count on the - // friendly url checking code is if it was a custom redirect set up - result.Reason = RedirectReason.Not_Redirected; - result.Action = ActionType.CheckFor301; - - // set the value field back to false, because, even if the parameter handling is - // first parm last, this was an old style URl desitned to be redirected. - // and we would expect old-style urls to have the correct parameter order - // note this assumes tabid is the first parm in the list. - valueField = false; - } - } - else if (!skip) - { - bool extReplaced; - string urlParm = CleanExtension(thisParm, pageExtension, out extReplaced); + // determine what the rewritten URl will be + newUrl = tabDict[tabLookUpKey]; + } - if (extReplaced && pageExtension == string.Empty) // replacing a .aspx extension - { - result.Action = ActionType.CheckFor301; - } - - if (valueField) - { - // this parameter is going into the value half of a &key=value pair - parmString.Append("="); - parmString.Append(urlParm); - valueField = false; - if (isUserParm) - { - int userIdVal; - int.TryParse(urlParm, out userIdVal); - isUserParm = false; - } - - // 786 : redirect ctl/terms etc - if (keyName != null && keyName.ToLowerInvariant() == "ctl") - { - RequestRedirectOnBuiltInUrl(urlParm, parmString.ToString(), result); - } - } - else + // DNN-6747: if found match doesn't match current culture, then try to find correct match. + if (result.PortalId != Null.NullInteger && newUrl.Contains("language=")) + { + var currentLocale = result.CultureCode; + if (string.IsNullOrEmpty(currentLocale)) + { + currentLocale = Localization.GetPageLocale(new PortalSettings(result.PortalId)).Name; + } + + if (!newUrl.Contains(currentLocale)) + { + var tabPath = tabLookUpKey.Split(new[] { "::" }, StringSplitOptions.None)[1]; + using (tabDict.GetReadLock()) + { + foreach (var key in tabDict.Keys.Where(k => k.EndsWith("::" + tabPath))) { - // this parameter is going into the key half of a &key=value pair - keyName = urlParm; - parmString.Append("&"); - parmString.Append(urlParm); - valueField = true; - - // if we are looking for a userid parameter in this querystring, check for a match - if (userIdParm != null) + if (tabDict[key].Contains("language=" + currentLocale)) { - if (string.Compare(keyName, userIdParm, StringComparison.OrdinalIgnoreCase) == 0) - { - isUserParm = true; - } + newUrl = tabDict[key]; + tabKeyVal = key; + break; } } } - else if (skip) - { - skip = false; - } } } - // add back language parameters if they were found - AddLanguageCodeToRewritePath(ref newUrl, cultureCode); - - // add on the parameter string - newUrl += parmString.ToString(); - - if (stripLoneParm) + if (!string.IsNullOrEmpty(userParam)) { - newUrl = UrlParamsRegex.Replace(newUrl, "&"); - if (newUrl.EndsWith("&")) - { - newUrl = newUrl.Substring(0, newUrl.Length - 1); - } + newUrl = newUrl + "&" + userParam; } - - // chop the last char off if it is an empty parameter - if (newUrl[newUrl.Length - 1] == '&') + + // if this is a match on the trigger dictionary rebuild, + // then temporarily store this value in case it's a page name change + // 677 : only match if is on actual tabKeyVal match, to prevent site root redirects + // statements were moved into this 'if' statement + result.dictVal = newUrl; + result.dictKey = tabKeyVal; + } + + return found; + } + + private static string ReplaceDefaultPage(string newUrl, string requestUrl, IEnumerable list) + { + string url = newUrl; // fall back case: we don't change anything + + // iterate the list and replace in the url is a match is found + foreach (string requestPage in list) + { + if (requestUrl.ToLowerInvariant().Contains(requestPage)) { - newUrl = newUrl.Substring(0, newUrl.Length - 1); + url = newUrl.Replace(Globals.glbDefaultPage, requestPage); + break; } } - - return newUrl; + + return url; } - /// - /// Scans the collection of Rewrite Parameter rules, and rewrites the parameters if a match is found. - /// - /// - /// - /// - /// - /// - /// - /// - /// The new Url with the parameters rewritten onto the end of hte old Url. - internal static string RewriteParameters( + private static string RewriteParametersFromModuleProvider( string newUrl, string tabKeyVal, string[] urlParms, - bool isSiteRoot, - UrlAction urlAction, + bool isSiteRootMatch, + UrlAction result, + FriendlyUrlSettings settings, out bool rewriteParms, + out bool newAction, + ref List messages, Guid parentTraceId) { - string result = newUrl; - rewriteParms = false; - - // get the actions from the cache - var messages = new List(); - Dictionary> rewriteActions = CacheController.GetParameterRewrites( - urlAction.PortalId, - ref messages, parentTraceId); - if (messages == null) + string rewrittenUrl; + rewriteParms = ExtensionUrlProviderController.TransformFriendlyUrlPath( + newUrl, + tabKeyVal, + urlParms, + isSiteRootMatch, + ref result, + settings, + out rewrittenUrl, + out newAction, + ref messages, + parentTraceId); + if (rewriteParms) { - messages = new List(); + result.CustomParmRewrite = true; } - - try + + return rewrittenUrl; + } + + private static void SetRewriteParameters(ref UrlAction result, string rewritePath) + { + // split out found replaced and store tabid, rulePortalId and do301 if found + result.RewritePath = rewritePath; + MatchCollection qsItems = RewriteParamsRegex.Matches(rewritePath); + foreach (Match itemMatch in qsItems) { - if (rewriteActions != null && rewriteActions.Count > 0) + string val = itemMatch.Groups["val"].Value; + string key = itemMatch.Groups["key"].Value; + switch (key.ToLowerInvariant()) { - SharedList tabRewrites = null; - Match tabMatch = TabIdRegex.Match(newUrl); - if (tabMatch.Success) - { - string rawTabId = tabMatch.Groups["tabid"].Value; - int tabId; - if (int.TryParse(rawTabId, out tabId)) + case "tabid": + int tabidtemp; + if (int.TryParse(val, out tabidtemp)) { - if (rewriteActions.ContainsKey(tabId)) - { - // find the right set of rewrite actions for this tab - tabRewrites = rewriteActions[tabId]; - } + result.TabId = tabidtemp; } - } - if (rewriteActions.ContainsKey(AllTabsRewrite)) // -1 means 'all tabs' - rewriting across all tabs - { - // initialise to empty collection if there are no specific tab rewrites - if (tabRewrites == null) - { - tabRewrites = new SharedList(); - } - - // add in the all rewrites - SharedList allRewrites = rewriteActions[AllTabsRewrite]; - foreach (ParameterRewriteAction rewrite in allRewrites) - { - tabRewrites.Add(rewrite); // add the 'all' range to the tab range - } - } - - if (isSiteRoot && rewriteActions.ContainsKey(SiteRootRewrite)) - { - // initialise to empty collection if there are no specific tab rewrites - if (tabRewrites == null) - { - tabRewrites = new SharedList(); - } - - SharedList siteRootRewrites = rewriteActions[SiteRootRewrite]; - foreach (ParameterRewriteAction rewrite in siteRootRewrites) + break; + case "portalid": + int pid; + if (int.TryParse(val, out pid)) { - tabRewrites.Add(rewrite); // add the site root rewrites to the collection + result.PortalId = pid; } - } - - // get the parms as a string - string parms = string.Join("/", urlParms); - - if (tabRewrites != null && tabRewrites.Count > 0) - { - // process each one until a match is found - foreach (ParameterRewriteAction rewrite in tabRewrites) - { - var parmRegex = RegexUtils.GetCachedRegex(rewrite.LookFor, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - - // check the match, if a match found, do the replacement - if (parmRegex.IsMatch(parms)) - { - // rewrite the parameter - string sendTo = rewrite.RewriteTo; - string parmsOriginal = parms; - - // replace hte parameter with the rewrite string - parms = parmRegex.Replace(parms, sendTo); - messages.Add(rewrite.Name + " rewrite match (" + parmsOriginal + "), replaced to : " + parms); - - // makes sure the newUrl has got a trailing ampersand or a ? to start the query string - if (newUrl.Contains("?")) - { - if (newUrl.EndsWith("&") == false) - { - newUrl += "&"; - } - } - else // need to start the querystring off (592: allow for custom rewrites on site root) - { - newUrl += "?"; - } - // makes sure the new parms string hasn't got a starting ampersand - if (parms.StartsWith("&")) - { - parms = parms.Substring(1); - } - - // parameters are added to the back fo the newUrl - newUrl += parms; - - // it's a rewrite, all right - rewriteParms = true; - result = newUrl; - urlAction.CustomParmRewrite = true; - break; - } - - messages.Add(rewrite.Name + " rewrite not matched (" + parms + ")"); - } - } + break; + case "language": + result.CultureCode = val; + break; + case "ctl": + // 786: force redirect for ctl/terms or ctl/privacy + RequestRedirectOnBuiltInUrl(val, rewritePath, result); + break; } } - catch (Exception ex) - { - Services.Exceptions.Exceptions.LogException(ex); - string error = "Exception: " + ex.Message + "\n" + ex.StackTrace; - messages.Add(error); - } - finally - { - // post messages to debug output - urlAction.DebugMessages.AddRange(messages); - } - return result; - } + // remove the application path + result.RewritePath = result.RewritePath.Replace(result.ApplicationPath + "/", string.Empty); + } } } diff --git a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs index 33240793322..769b7729e88 100644 --- a/DNN Platform/Library/Entities/Urls/RewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/RewriterUtils.cs @@ -39,13 +39,13 @@ internal static void RewriteUrl(HttpContext context, string sendToUrl) parameters.Add(parameter); } } - + queryString = string.Join("&", parameters); } // rewrite the path.. context.RewritePath(sendToUrlLessQString, string.Empty, queryString); - + // NOTE! The above RewritePath() overload is only supported in the .NET Framework 1.1 // If you are using .NET Framework 1.0, use the below form instead: // context.RewritePath(sendToUrl); @@ -70,7 +70,7 @@ internal static string ResolveUrl(string appPath, string url) { return appPath; } - + var seperatorChar = url.ToCharArray()[1]; if (seperatorChar == '/' || seperatorChar == '\\') { @@ -79,16 +79,16 @@ internal static string ResolveUrl(string appPath, string url) { return appPath + "/" + url.Substring(2); } - + return "/" + url.Substring(2); } - + // Url look like ~something if (appPath.Length > 1) { return appPath + "/" + url.Substring(1); } - + return appPath + url.Substring(1); } @@ -100,11 +100,11 @@ internal static bool OmitFromRewriteProcessing(string localPath) omitSettings = HostController.Instance.GetString("OmitFromRewriteProcessing"); } - if (string.IsNullOrEmpty(omitSettings)) + if (string.IsNullOrEmpty(omitSettings)) { omitSettings = "scriptresource.axd|webresource.axd|gif|ico|jpg|jpeg|png|css|js"; } - + omitSettings = omitSettings.ToLowerInvariant(); localPath = localPath.ToLowerInvariant(); diff --git a/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs b/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs index e2cad7dc230..0668cd1de19 100644 --- a/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs +++ b/DNN Platform/Library/Entities/Urls/SaveUrlDto.cs @@ -9,19 +9,19 @@ namespace DotNetNuke.Entities.Urls public class SaveUrlDto { public int Id { get; set; } - + public int SiteAliasKey { get; set; } - + public string Path { get; set; } - + public string QueryString { get; set; } - + public int LocaleKey { get; set; } - + public int StatusCodeKey { get; set; } - + public int SiteAliasUsage { get; set; } - + public bool IsSystem { get; set; } } } diff --git a/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs b/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs index d7cf44ef4a3..44fca8e8c2c 100644 --- a/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs +++ b/DNN Platform/Library/Entities/Urls/StringLengthComparer.cs @@ -18,32 +18,32 @@ public override int Compare(string x, string y) { return 0; } - + if (x == null) { return -1; } - + if (y == null) { return 1; } - + if (x.Length < y.Length) { return -1; } - + if (x.Length > y.Length) { return 1; } - + if (x.Length == y.Length) { return 0; } - + return -1; // should never reach here } } diff --git a/DNN Platform/Library/Entities/Urls/TabIndexController.cs b/DNN Platform/Library/Entities/Urls/TabIndexController.cs index cdb5fc9b2a8..34bea6e1b4f 100644 --- a/DNN Platform/Library/Entities/Urls/TabIndexController.cs +++ b/DNN Platform/Library/Entities/Urls/TabIndexController.cs @@ -21,8 +21,8 @@ namespace DotNetNuke.Entities.Urls internal static class TabIndexController { - private static readonly object tabPathDictBuildLock = new object(); - + 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 @@ -48,12 +48,12 @@ public static void InvalidateDictionary(string reason, PageIndexData rebuildData 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)); @@ -65,139 +65,415 @@ internal static string CreateRewritePath(int tabId, string cultureCode, ActionTy rewritePath = RedirectTokens.AddRedirectReasonToRewritePath(rewritePath, action, reason); return rewritePath; } - - private static void AddCustomRedirectsToDictionary( - SharedDictionary tabIndex, - Dictionary dupCheck, - string httpAlias, - TabInfo tab, + + /// + /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one. + /// + /// + /// ByRef parameter to return the minimum tab path depth (the number of '/' in the tab path). + /// ByRef parameter to return the maximum tab path depth (the number of '/' in the tab path). + /// ByRef parameter to return the minimum alias path depth (the number of '/' in the alias path. + /// ByRef parameter to return the maximum alias path depth (the number of '/' in the alias path). + /// + /// + /// + /// + /// Dictionary (string, string) of Tab paths in tab key, with the rewrite path as the value. + /// + /// Changes + /// Task 608 : Incrementally build tab dictionary instead of building entire dicitionary all at once + /// Task 609 : If usePortalAlias is specified, only build dictionary with specific portal alias : ignore others + /// Task 791 : allow for specification of true/false for using thread locking to prevent multiple rebuilds on threads. + /// + internal static SharedDictionary FetchTabDictionary( + int portalId, + out int minTabPathDepth, + out int maxTabPathDepth, + out int minAliasPathDepth, + out int maxAliasPathDepth, FriendlyUrlSettings settings, - FriendlyUrlOptions options, - ref string rewritePath, - out int tabPathDepth, - ref List customHttpAliasesUsed, - bool isDeleted, + bool forceRebuild, + bool bypassCache, Guid parentTraceId) { - tabPathDepth = 1; - var duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected; - bool checkForDupUrls = settings.CheckForDuplicateUrls; - - // 697 : custom url rewrites with large number of path depths fail because of incorrect path depth calculation - int maxTabPathDepth = 1; - string origRewritePath = rewritePath; - string newRewritePath = rewritePath; - string aliasCulture = null; - - // get the culture for this alias - var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID).ToList(); + PathSizes depthInfo; + SharedDictionary portalDepths = null; + SharedDictionary dict = null; + SharedDictionary portalTabPathDictionary = null; + string reason = string.Empty; - if (primaryAliases.Count > 0) + var cc = new CacheController(); + if (bypassCache == false) { - aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(tab.PortalID, httpAlias); + cc.GetPageIndexFromCache(out dict, out portalDepths, settings); + portalTabPathDictionary = FetchTabPathDictionary(portalId); } - - foreach (var redirect in tab.TabUrls) + + if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) { - rewritePath = origRewritePath; - - // allow for additional qs parameters - if (!string.IsNullOrEmpty(redirect.QueryString)) + // place threadlock to prevent two threads getting a null object. Use the same lock object that is used to + lock (tabPathDictBuildLock) { - rewritePath += redirect.QueryString.StartsWith("&") ? redirect.QueryString : "&" + redirect.QueryString; - } - - string redirectTabPath = redirect.Url; - string redirectedRewritePath = rewritePath; + // check for the tab dictionary in the DataCache again as it could have been cached by another thread + // while waiting for the lock to become available. + if (bypassCache == false) + { + cc.GetPageIndexFromCache(out dict, out portalDepths, settings); + portalTabPathDictionary = FetchTabPathDictionary(portalId); + } - // 770 : allow for custom portal aliases - string redirectAlias = httpAlias; - if (redirect.PortalAliasId > 0) - { - // has a custom portal alias - PortalAliasInfo customAlias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId); - if (customAlias != null) + if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) { - // this will be used to add the Url to the dictionary - redirectAlias = customAlias.HTTPAlias; - - // add to the list of custom aliases used by the portal - if (customHttpAliasesUsed == null) + Hashtable homePageSkins; // keeps a list of skins set per home page and culture + + if (!bypassCache && dict == null) { - customHttpAliasesUsed = new List(); + reason += "No Page index in cache;"; } - - if (!customHttpAliasesUsed.Contains(redirectAlias)) + + if (forceRebuild) { - customHttpAliasesUsed.Add(redirectAlias); + reason += "Force Rebuild;"; + } + + if (bypassCache) + { + reason += "Bypass Cache;"; + } + + // PathSizes depthInfo; + // the cached dictionary was null or forceRebuild = true or bypassCache = true, so go get a new dictionary + dict = BuildTabDictionary( + out depthInfo, + settings, + portalId, + dict, + out homePageSkins, + out portalTabPathDictionary, + parentTraceId); + + if (portalDepths == null || forceRebuild) + { + portalDepths = new SharedDictionary(); + } + + // store the fact that this portal has been built + using (portalDepths.GetWriteLock()) + { + // depthInfo may already exist in index so use indexer to Add/Update rather than using Add method which + // would throw an exception if the portal already existed in the dictionary. + portalDepths[portalId] = depthInfo; + } + + if (bypassCache == false) // only cache if bypass not switched on + { + reason += "Portal " + portalId + " added to index;"; + using (dict.GetReadLock()) + { + reason += "Existing Page Index=" + dict.Count + " items;"; + } + + cc.StorePageIndexInCache(dict, portalDepths, settings, reason); + cc.StoreTabPathsInCache(portalId, portalTabPathDictionary, settings); + CacheController.StoreHomePageSkinsInCache(portalId, homePageSkins); } } } - - // set the redirect status using the httpStatus - switch (redirect.HttpStatus) + } + + if (PortalExistsInIndex(portalDepths, portalId)) + { + using (portalDepths.GetReadLock()) { - case "301": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( - rewritePath, - ActionType.Redirect301, - RedirectReason.Custom_Redirect); - break; - case "302": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( - rewritePath, - ActionType.Redirect302, - RedirectReason.Custom_Redirect); - break; - case "404": - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( - rewritePath, - ActionType.Output404, - RedirectReason.Custom_Redirect); - break; - case "200": - // when there is a 200, then replace the 'standard' path - newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( - newRewritePath, - ActionType.CheckFor301, - RedirectReason.Custom_Redirect); - - // 672 : replacement urls have preference over all redirects, deleted tabs and standard urls - duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabOK; - break; + depthInfo = portalDepths[portalId]; + minTabPathDepth = depthInfo.MinTabPathDepth; + maxTabPathDepth = depthInfo.MaxTabPathDepth; + minAliasPathDepth = depthInfo.MinAliasDepth; + maxAliasPathDepth = depthInfo.MaxAliasDepth; } - - // check the culture of the redirect to see if it either doesn't match the alias or needs to specify - // the language when requested - if (!string.IsNullOrEmpty(redirect.CultureCode) && redirect.CultureCode != "Default") + } + else + { + // fallback values, should never get here: mainly for compiler wranings + minTabPathDepth = 1; + maxTabPathDepth = 10; + minAliasPathDepth = 1; + maxAliasPathDepth = 4; + } + + return dict; + } + + /// + /// Returns a list of aliases that are used in custom tab/alias association. + /// + /// + /// + internal static List GetCustomPortalAliases(FriendlyUrlSettings settings) + { + List aliases = CacheController.GetCustomAliasesFromCache(); + if (aliases == null) + { + aliases = FriendlyUrlController.GetCustomAliasesForTabs(); + CacheController.StoreCustomAliasesInCache(aliases, settings); + } + + return aliases; + } + + /// + /// Gets the portal alias by portal. + /// + /// The portal id. + /// The portal alias. + /// Portal alias. + internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string portalAlias) + { + PortalAliasInfo retValue = null; + + // get the portal alias collection from the cache + var portalAliasCollection = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); + + bool foundAlias = false; + + // Do a specified PortalAlias check first + PortalAliasInfo portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == portalAlias.ToLowerInvariant()); + if (portalAliasInfo != null) + { + if (portalAliasInfo.PortalID == portalId) { - // 806 : specify duplicates where the alias culture doesn't match the redirect culture - // so that redirect to the best match between alias culture and redirect culture - // compare the supplied alias culture with the redirect culture - // 856 : if alias culture == "" and a custom 301 redirect then redirects are forced - if (!string.IsNullOrEmpty(aliasCulture) && aliasCulture != redirect.CultureCode) - { - // the culture code and the specific culture alias don't match - // set 301 check status and set to delete if a duplicate is found - redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( - redirectedRewritePath, - ActionType.CheckFor301, + // set the alias + retValue = portalAliasInfo; + foundAlias = true; + } + } + + if (!foundAlias) + { + // collection to hold aliases sorted by length, longest first + var aliases = (from p in portalAliasCollection + select p.HTTPAlias).ToList(); + + // get aliases sorted by length of alias + aliases.Sort(new StringLengthComparer()); + + // 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 + // IEnumerable aliases = portalAliasCollection.Keys.Cast().OrderByDescending(k => k.Length); + foreach (string currentAlias in aliases) + { + // 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 ) + portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == currentAlias); + if (portalAliasInfo != null) + { + string httpAlias = portalAliasInfo.HTTPAlias.ToLowerInvariant(); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && portalAliasInfo.PortalID == portalId) + { + retValue = portalAliasInfo; + break; + } + + httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); + if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && portalAliasInfo.PortalID == portalId) + { + retValue = portalAliasInfo; + break; + } + } + } + } + + return retValue; + } + + /// + /// Returns an ordered dictionary of alias regex patterns. These patterns are used to identify a portal alias by getting a match. + /// + /// + internal static OrderedDictionary GetPortalAliases(FriendlyUrlSettings settings) + { + // object to return + OrderedDictionary aliasList = CacheController.GetPortalAliasesFromCache(); + if (aliasList == null) + { + aliasList = BuildPortalAliasesDictionary(); + CacheController.StorePortalAliasesInCache(aliasList, settings); + } + + return aliasList; + } + + /// + /// Returns the tab path of the base DNN tab. Ie /Home or /Somepage/SomeOtherPage. + /// + /// + /// + /// + /// Will remove // from the tabPath as stored in the Tabs object/table. + /// + internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) + { + string tabPath = null; + if (options.CanGenerateNonStandardPath) + { + var tpd = FetchTabPathDictionary(tab.PortalID); + + if (tpd != null) + { + using (tpd.GetReadLock()) + { + if (tpd.Count > 0) + { + // get the path from the dictionary + string tabKey = tab.TabID.ToString(); + if (tpd.ContainsKey(tabKey)) + { + tabPath = tpd[tabKey]; + } + } + } + } + } + + return tabPath ?? TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); + } + + private static void AddCustomRedirectsToDictionary( + SharedDictionary tabIndex, + Dictionary dupCheck, + string httpAlias, + TabInfo tab, + FriendlyUrlSettings settings, + FriendlyUrlOptions options, + ref string rewritePath, + out int tabPathDepth, + ref List customHttpAliasesUsed, + bool isDeleted, + Guid parentTraceId) + { + tabPathDepth = 1; + var duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected; + bool checkForDupUrls = settings.CheckForDuplicateUrls; + + // 697 : custom url rewrites with large number of path depths fail because of incorrect path depth calculation + int maxTabPathDepth = 1; + string origRewritePath = rewritePath; + string newRewritePath = rewritePath; + string aliasCulture = null; + + // get the culture for this alias + var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(tab.PortalID).ToList(); + + if (primaryAliases.Count > 0) + { + aliasCulture = primaryAliases.GetCultureByPortalIdAndAlias(tab.PortalID, httpAlias); + } + + foreach (var redirect in tab.TabUrls) + { + rewritePath = origRewritePath; + + // allow for additional qs parameters + if (!string.IsNullOrEmpty(redirect.QueryString)) + { + rewritePath += redirect.QueryString.StartsWith("&") ? redirect.QueryString : "&" + redirect.QueryString; + } + + string redirectTabPath = redirect.Url; + string redirectedRewritePath = rewritePath; + + // 770 : allow for custom portal aliases + string redirectAlias = httpAlias; + if (redirect.PortalAliasId > 0) + { + // has a custom portal alias + PortalAliasInfo customAlias = PortalAliasController.Instance.GetPortalAliasByPortalAliasID(redirect.PortalAliasId); + if (customAlias != null) + { + // this will be used to add the Url to the dictionary + redirectAlias = customAlias.HTTPAlias; + + // add to the list of custom aliases used by the portal + if (customHttpAliasesUsed == null) + { + customHttpAliasesUsed = new List(); + } + + if (!customHttpAliasesUsed.Contains(redirectAlias)) + { + customHttpAliasesUsed.Add(redirectAlias); + } + } + } + + // set the redirect status using the httpStatus + switch (redirect.HttpStatus) + { + case "301": + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect301, + RedirectReason.Custom_Redirect); + break; + case "302": + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Redirect302, + RedirectReason.Custom_Redirect); + break; + case "404": + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath, + ActionType.Output404, + RedirectReason.Custom_Redirect); + break; + case "200": + // when there is a 200, then replace the 'standard' path + newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + newRewritePath, + ActionType.CheckFor301, + RedirectReason.Custom_Redirect); + + // 672 : replacement urls have preference over all redirects, deleted tabs and standard urls + duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabOK; + break; + } + + // check the culture of the redirect to see if it either doesn't match the alias or needs to specify + // the language when requested + if (!string.IsNullOrEmpty(redirect.CultureCode) && redirect.CultureCode != "Default") + { + // 806 : specify duplicates where the alias culture doesn't match the redirect culture + // so that redirect to the best match between alias culture and redirect culture + // compare the supplied alias culture with the redirect culture + // 856 : if alias culture == "" and a custom 301 redirect then redirects are forced + if (!string.IsNullOrEmpty(aliasCulture) && aliasCulture != redirect.CultureCode) + { + // the culture code and the specific culture alias don't match + // set 301 check status and set to delete if a duplicate is found + redirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + redirectedRewritePath, + ActionType.CheckFor301, RedirectReason.Custom_Redirect); - newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + newRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( newRewritePath, ActionType.CheckFor301, RedirectReason.Custom_Redirect); duplicateHandlingPreference = UrlEnums.TabKeyPreference.TabRedirected; } - + // add on the culture code for the redirect, so that the rewrite silently sets the culture for the page RewriteController.AddLanguageCodeToRewritePath(ref redirectedRewritePath, redirect.CultureCode); } - + // now add the custom redirect to the tab dictionary if (string.Compare(httpAlias, redirectAlias, StringComparison.OrdinalIgnoreCase) == 0) { - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -213,21 +489,21 @@ private static void AddCustomRedirectsToDictionary( { // 770 : there is a specific alias for this tab // if not a redirect already, make it a redirect for the wrong (original) rewrite path - string wrongAliasRedirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + string wrongAliasRedirectedRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( redirectedRewritePath, ActionType.Redirect301, RedirectReason.Custom_Tab_Alias); - + // add in the entry with the specific redirectAlias if (redirectTabPath == string.Empty) { // when adding a blank custom Url, also add in a standard tab path url, because any url that also includes querystring data will use the standard tab path string tabPath = GetTabPath(tab, options, parentTraceId); - string stdDictRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + string stdDictRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.CheckFor301, RedirectReason.Custom_Tab_Alias); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, redirectAlias, @@ -238,9 +514,9 @@ private static void AddCustomRedirectsToDictionary( ref tabPathDepth, checkForDupUrls, isDeleted); - + // then add in the portal alias with no tabpath (ie like a site root url) - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, redirectAlias, @@ -251,7 +527,7 @@ private static void AddCustomRedirectsToDictionary( ref tabPathDepth, checkForDupUrls, isDeleted); - + // 838 : disabled tabs with custom aliases - still load the settings page without redirect // disabled / not active by date / external url pages cannot navigate to settings page if (tab.DisableLink || !string.IsNullOrEmpty(tab.Url) || @@ -260,10 +536,10 @@ private static void AddCustomRedirectsToDictionary( { string settingsUrl = tabPath + "/ctl/Tab"; string settingsRewritePath = CreateRewritePath(tab.TabID, redirect.CultureCode, "ctl=Tab"); - + // no redirect on the ctl/Tab url // add in the ctl/tab Url for the custom alias, with no redirect so that the page settings can be loaded - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, redirectAlias, @@ -279,7 +555,7 @@ private static void AddCustomRedirectsToDictionary( else { // add in custom entry with different alias - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, redirectAlias, @@ -290,9 +566,9 @@ private static void AddCustomRedirectsToDictionary( ref tabPathDepth, checkForDupUrls, isDeleted); - + // add in the entry with the original alias, plus an instruction to redirect if it's used - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -305,20 +581,20 @@ private static void AddCustomRedirectsToDictionary( isDeleted); } } - + if (tabPathDepth > maxTabPathDepth) { maxTabPathDepth = tabPathDepth; } } - + // return the highest tabpath depth found tabPathDepth = maxTabPathDepth; - + // return any changes to the rewritePath rewritePath = newRewritePath; } - + private static void AddInternalAliases(FriendlyUrlSettings settings, List usingHttpAliases) { if (settings.InternalAliasList != null && settings.InternalAliasList.Count > 0) @@ -333,7 +609,7 @@ private static void AddInternalAliases(FriendlyUrlSettings settings, List tabIndex, Dictionary dupCheck, string httpAlias, @@ -345,7 +621,7 @@ private static void AddPermanentRedirectToDictionary( bool isDeleted) { // because we have to catch all versions of this in the dictionary, then we have to add the 'base' url - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -356,9 +632,9 @@ private static void AddPermanentRedirectToDictionary( ref tabPathDepth, checkForDupUrls, isDeleted); - + // and put in the name-less one as well, just in case a prior version of the site was runnign without the tabnames (urlformat=sefriendly) - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -369,9 +645,9 @@ private static void AddPermanentRedirectToDictionary( ref tabPathDepth, checkForDupUrls, isDeleted); - + // finally, put one in for the ctl/tab combination, so that you can actually get to the page settings - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -384,7 +660,7 @@ private static void AddPermanentRedirectToDictionary( isDeleted); } - private static void AddSiteRootRedirects( + private static void AddSiteRootRedirects( PathSizes pathSizes, SharedDictionary tabIndex, IEnumerable chosenAliases, @@ -400,7 +676,7 @@ private static void AddSiteRootRedirects( if (hasSiteRootRedirect) { int tempPathDepth = 0; - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -420,7 +696,7 @@ private static void AddSiteRootRedirects( } } - private static void AddStandardPagesToDict( + private static void AddStandardPagesToDict( SharedDictionary tabIndex, Dictionary dupCheck, string httpAlias, @@ -428,7 +704,7 @@ private static void AddStandardPagesToDict( string cultureCode) { int tabDepth = 0; // we ignore tab depth as it is only one for these in-built urls - + // 850 : add in the culture code to the redirect if supplied string portalRewritePath = "?PortalId=" + portalId.ToString(); string cultureRewritePath = string.Empty; @@ -436,7 +712,7 @@ private static void AddStandardPagesToDict( { cultureRewritePath += "&language=" + cultureCode; } - + // hard coded page paths - using 'tabDeleted' in case there is a clash with an existing page (ie, someone has created a page that takes place of the standard page, created page has preference) // need check custom login/register page set in portal and redirect to the specific page. @@ -450,8 +726,8 @@ private static void AddStandardPagesToDict( loginPreference = UrlEnums.TabKeyPreference.TabOK; loginRewritePath = CreateRewritePath(loginTabId, cultureCode); } - - AddToTabDict( + + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -472,8 +748,8 @@ private static void AddStandardPagesToDict( registerPreference = UrlEnums.TabKeyPreference.TabOK; registerRewritePath = CreateRewritePath(registerTabId, cultureCode); } - - AddToTabDict( + + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -484,7 +760,7 @@ private static void AddStandardPagesToDict( ref tabDepth, false, false); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -495,7 +771,7 @@ private static void AddStandardPagesToDict( ref tabDepth, false, false); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -506,7 +782,7 @@ private static void AddStandardPagesToDict( ref tabDepth, false, false); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -519,7 +795,7 @@ private static void AddStandardPagesToDict( false); } - private static int AddTabToTabDict( + private static int AddTabToTabDict( SharedDictionary tabIndex, Dictionary dupCheck, string httpAlias, @@ -546,16 +822,16 @@ private static int AddTabToTabDict( { cultureCode = aliasCulture; } - + bool permanentRedirect = tab.PermanentRedirect; - + // determine the rewrite parameter // for deleted or pages not enabled yet, direct to the home page if the setting is enabled // 534 : tab is disabled, mark as deleted (don't want to cause duplicate tab warnings) // DNN-6186: add expired pages in dictionary as admin/host user should able to visit/edit them. bool isDeleted = tab.IsDeleted || tab.DisableLink; if (isDeleted) - + // don't care what setting is, redirect code will decide whether to redirect or 404 - just mark as page deleted && // settings.DeletedTabHandlingValue == DeletedTabHandlingTypes.Do301RedirectToPortalHome) { @@ -574,7 +850,7 @@ private static int AddTabToTabDict( // 592 : new permanentRedirect value if (permanentRedirect) { - rewritePath = CreateRewritePath( + rewritePath = CreateRewritePath( tab.TabID, cultureCode, ActionType.Redirect301, @@ -604,7 +880,7 @@ private static int AddTabToTabDict( { homePageSkins.Add(key, skinSrc); } - + if (homePageSkins.ContainsKey(key2) == false) { homePageSkins.Add(key2, skinSrc); @@ -622,7 +898,7 @@ private static int AddTabToTabDict( { // user profile action specified. If tabid match for this tab, add a do301 check because we want to make // sure that the trimmed Url is used when appropriate - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.CheckFor301, RedirectReason.User_Profile_Url); @@ -636,7 +912,7 @@ private static int AddTabToTabDict( // this entry is the 'original' (spaces removed) version ie mypage string substituteRewritePath = rewritePath; if (!isDeleted) - + // if it is deleted, we don't care if the spaces were replaced, or anything else, just take care in deleted handling { string replaceSpaceWith = string.Empty; @@ -644,15 +920,15 @@ private static int AddTabToTabDict( { replaceSpaceWith = settings.ReplaceSpaceWith; } - - substituteRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + + substituteRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( substituteRewritePath, ActionType.Redirect301, tabPath.Contains(replaceSpaceWith) ? RedirectReason.Spaces_Replaced : RedirectReason.Custom_Redirect); } - + // the preference variable determines what to do if a duplicate tab is found already in the dictionary var preference = UrlEnums.TabKeyPreference.TabRedirected; if (isDeleted) @@ -661,9 +937,9 @@ private static int AddTabToTabDict( // are redirected but not deleted should take preference preference = UrlEnums.TabKeyPreference.TabDeleted; } - + // Note ; if anything else is wrong with this url, (ie, wrong alias) then that will be corrected in a redirect - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -679,7 +955,7 @@ private static int AddTabToTabDict( // check for permanent redirects as specified in the core dnn permanent redirect property if (permanentRedirect) { - AddPermanentRedirectToDictionary( + AddPermanentRedirectToDictionary( tabIndex, dupCheck, httpAlias, @@ -698,7 +974,7 @@ private static int AddTabToTabDict( { string settingsUrl = tabPath.Replace("//", "/") + "/ctl/Tab"; string settingsRewritePath = CreateRewritePath(tab.TabID, string.Empty, "ctl=tab"); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -715,7 +991,7 @@ private static int AddTabToTabDict( // inspect the optional tab redirects and add them as well, keeping track if any are '200' status, meaning the standard Url will be 301, if replaced unfriendly is switched on // 589 : tab with custom 200 redirects not changing base url to 301 statusa - AddCustomRedirectsToDictionary( + AddCustomRedirectsToDictionary( tabIndex, dupCheck, httpAlias, @@ -740,11 +1016,11 @@ private static int AddTabToTabDict( if (settings.RedirectUnfriendly && existingAction != ActionType.Redirect301) { // add in a tab path, with 301, for the version with the diacritics in - string diacriticRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + string diacriticRewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.Redirect301, RedirectReason.Diacritic_Characters); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -759,7 +1035,7 @@ private static int AddTabToTabDict( else { // add in the standard version so that the page responds to both the diacritic version - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -772,7 +1048,7 @@ private static int AddTabToTabDict( isDeleted); } } - + tabPath = asciiTabPath; // switch tabpath to new, ascii-converted version for rest of processing } @@ -781,11 +1057,11 @@ private static int AddTabToTabDict( { // home page shoudl be redirected back to the site root // 899: check for redirect on home page - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.CheckFor301, RedirectReason.Site_Root_Home); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -802,11 +1078,11 @@ private static int AddTabToTabDict( if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly) { // add in the standard page, but it's a redirect to the customAlias - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.Redirect301, RedirectReason.Custom_Tab_Alias); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -823,11 +1099,11 @@ private static int AddTabToTabDict( if (customAliasUsedAndNotCurrent && settings.RedirectUnfriendly) { // add in the standard page, but it's a redirect to the customAlias - rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( + rewritePath = RedirectTokens.AddRedirectReasonToRewritePath( rewritePath, ActionType.Redirect301, RedirectReason.Custom_Tab_Alias); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -850,8 +1126,8 @@ private static int AddTabToTabDict( { dupCheckPreference = UrlEnums.TabKeyPreference.TabRedirected; } - - AddToTabDict( + + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -865,11 +1141,11 @@ private static int AddTabToTabDict( } } } - + return tabPathDepth; } - private static void AddToTabDict( + private static void AddToTabDict( SharedDictionary tabIndex, Dictionary dupCheckDict, string httpAlias, @@ -883,14 +1159,14 @@ private static void AddToTabDict( { // remove leading '/' and convert to lower for all keys string tabPathSimple = tabPath.Replace("//", "/").ToLowerInvariant(); - + // the tabpath depth is only set if it's higher than the running highest tab path depth int thisTabPathDepth = tabPathSimple.Length - tabPathSimple.Replace("/", string.Empty).Length; if (thisTabPathDepth > tabPathDepth) { tabPathDepth = thisTabPathDepth; } - + if (tabPathSimple.Length > 0 && tabPathSimple[0] == '/') { tabPathSimple = tabPathSimple.Substring(1); @@ -926,25 +1202,25 @@ private static void AddToTabDict( if (dupCheckDict.ContainsKey(dupKey)) { DupKeyCheck foundTab = dupCheckDict[dupKey]; - + // a redirected tab will replace a deleted tab if (foundTab.IsDeleted && keyDupAction == UrlEnums.TabKeyPreference.TabRedirected) { replaceTab = true; } - + if (foundTab.TabIdOriginal == "-1") { replaceTab = true; } } } - + if (replaceTab && !isDeleted) // don't replace if the incoming tab is deleted { // remove the previous one tabIndex.Remove(tabKey); - + // add the new one tabIndex.Add(tabKey, Globals.glbDefaultPage + rewrittenPath); } @@ -963,12 +1239,12 @@ private static void AddToTabDict( if ((foundTAb.IsDeleted == false && isDeleted == false) // found is not deleted, this tab is not deleted && keyDupAction == UrlEnums.TabKeyPreference.TabOK && foundTAb.TabIdOriginal != "-1") - + // -1 tabs are login, register, privacy etc { // check whether to log for this or not if (checkForDupUrls && foundTAb.TabIdOriginal != tabId.ToString()) - + // dont' show message for where same tab is being added twice) { // there is a naming conflict where this alias/tab path could be mistaken @@ -990,7 +1266,7 @@ private static void AddToTabDict( { tab1Name = tab1.TabName + " [" + tab1.TabPath + "]"; } - + if (tab2 != null) { tab2Name = tab2.TabName + " [" + tab2.TabPath + "]"; @@ -1002,7 +1278,7 @@ private static void AddToTabDict( || tab1.CultureCode == tab2.CultureCode; } } - + if (dupInSameCulture) { string msg = "Page naming conflict. Url of (" + foundTAb.TabPath + @@ -1019,7 +1295,7 @@ private static void AddToTabDict( log.AddProperty("Duplicate Page Details", msg); log.AddProperty("Warning Information", msg2); log.AddProperty("Suggested Action", "Rename one or both of the pages to ensure a unique URL"); - log.AddProperty( + log.AddProperty( "Hide this message", "To stop this message from appearing in the log, uncheck the option for 'Produce an Exception in the Site Log if two pages have the same name/path?' in the Advanced Url Rewriting settings."); log.AddProperty("Thread Id", Thread.CurrentThread.ManagedThreadId.ToString()); @@ -1030,7 +1306,7 @@ private static void AddToTabDict( else { dupCheckDict.Remove(dupKey); - + // add this tab to the duplicate key dictionary dupCheckDict.Add(dupKey, new DupKeyCheck(dupKey, tabId.ToString(), dupKey, isDeleted)); } @@ -1044,24 +1320,24 @@ 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(); + { + 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]; - + // regex escape the portal alias for inclusion into a regex pattern string plainAlias = alias.HTTPAlias; var aliasesToAdd = new List { plainAlias }; - + // check for existence of www. version of domain, if it doesn't have a www. if (plainAlias.StartsWith("www.", StringComparison.InvariantCultureIgnoreCase)) { @@ -1083,7 +1359,7 @@ private static OrderedDictionary BuildPortalAliasesDictionary() aliasesToAdd.Add(wwwVersion); } } - + int count = 0; foreach (string aliasToAdd in aliasesToAdd) { @@ -1093,12 +1369,12 @@ private static OrderedDictionary BuildPortalAliasesDictionary() // work out how many path separators there are in the portalAlias (ie myalias/mychild = 1 path) int pathLength = plainAlias.Split('/').GetUpperBound(0); - + // now work out where in the list we should put this portalAlias regex pattern // the list is to be sorted so that those aliases with the most paths // are at the front of the list : ie, they are tested first int insertPoint = pathLengths.Count - 1; - + // walk through the existing list of path lengths, // and ascertain where in the list this one falls // if they are all the same path length, then place them in portal alias order @@ -1110,10 +1386,10 @@ private static OrderedDictionary BuildPortalAliasesDictionary() // larger than this position, insert at this value break; } - + insertPoint++; // next one along (if at end, means add) } - + if (pathLengths.Count > 0 && insertPoint <= pathLengths.Count - 1) { // put the new regex pattern into the correct position @@ -1127,12 +1403,12 @@ private static OrderedDictionary BuildPortalAliasesDictionary() pathLengths.Add(pathLength); } } - } - + } + return aliasList; } - private static SharedDictionary BuildTabDictionary( + private static SharedDictionary BuildTabDictionary( out PathSizes pathSizes, FriendlyUrlSettings settings, int buildPortalId, @@ -1166,7 +1442,7 @@ private static SharedDictionary BuildTabDictionary( const bool hasSiteRootRedirect = true; /* for the requested build portal, add in the standard urls and special rules */ - + // 735 : switch to custom method for getting portal PortalInfo thisPortal = CacheController.GetPortal(buildPortalId, true); List chosenAliases; @@ -1220,7 +1496,7 @@ private static SharedDictionary BuildTabDictionary( // 770 : custom alias per tab (and culture) bool customAliasUsed; - var customHttpAlias = ManageCustomAliases( + var customHttpAlias = ManageCustomAliases( tabCulture, thisPortal, tab, @@ -1240,31 +1516,31 @@ private static SharedDictionary BuildTabDictionary( { aliasCulture = chosenAliasesCultures[httpAlias.ToLowerInvariant()]; } - + bool ignoreTabWrongCulture = false; - + // the tab is the wrong culture, so don't add it to the dictionary if (aliasCulture != string.Empty) { - if (tabCulture != aliasCulture - - // this is a language-specific alias that's different to the culture for this alias + if (tabCulture != aliasCulture + + // 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)) - + // and there is a specific alias for this tab culture { ignoreTabWrongCulture = true; } } - + if (!ignoreTabWrongCulture) { if (!isExcluded) { // Add this tab to the dictionary // 750 : user profile action not returned as buildPortalId not used - tabPathDepth = AddTabToTabDict( + tabPathDepth = AddTabToTabDict( tabIndex, dupCheck, httpAlias, @@ -1284,7 +1560,7 @@ private static SharedDictionary BuildTabDictionary( { // 589 : custom redirects added as 200 status not causing base urls to redirect bool excludeFriendlyUrls = true; - + // 549 : detect excluded friendly urls by putting a known pattern into the dictionary // add this tab to the dictionary, but with the hack pattern [UseBase] to capture the fact it's a base Url // then, if there's redirects for it, add those as well. It's possible to exclude a tab from friendly urls, but @@ -1294,7 +1570,7 @@ private static SharedDictionary BuildTabDictionary( { rewritePath = CreateRewritePath(tab.TabID, string.Empty); string rewritePathKeep = rewritePath; // remember this value to compare - AddCustomRedirectsToDictionary( + AddCustomRedirectsToDictionary( tabIndex, dupCheck, httpAlias, @@ -1307,7 +1583,7 @@ private static SharedDictionary BuildTabDictionary( tab.IsDeleted, parentTraceId); if (rewritePath != rewritePathKeep) - + // check to see the rewrite path is still the same, or did it get changed? { // OK, the rewrite path was modifed by the custom redirects dictionary add @@ -1318,11 +1594,11 @@ private static SharedDictionary BuildTabDictionary( if (excludeFriendlyUrls) { rewritePath = "[UseBase]"; - + // use hack pattern to indicate not to rewrite on this Url } - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -1340,7 +1616,7 @@ private static SharedDictionary BuildTabDictionary( // ignoring this tab because the alias culture doesn't match to the tab culture // however, we need to add it to the dictionary in case there's an old link (pre-translation/pre-friendly url/pre-alias&culture linked) string rewritePath = CreateRewritePath(tab.TabID, tabCulture); - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -1352,10 +1628,10 @@ private static SharedDictionary BuildTabDictionary( true, tab.IsDeleted); } - + pathSizes.SetTabPathDepth(tabPathDepth); } - + if (customHttpAlias != string.Empty && customAliasUsed == false && usingHttpAliases.Contains(customHttpAlias)) { @@ -1364,7 +1640,7 @@ private static SharedDictionary BuildTabDictionary( } } } - + // now build the standard Urls for all of the aliases that are used foreach (string httpAlias in usingHttpAliases) { @@ -1376,10 +1652,10 @@ private static SharedDictionary BuildTabDictionary( { cultureCode = chosenAliasesCultures[httpAlias]; } - + AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode); } - + // and for any custom urls being used foreach (string httpAlias in customHttpAliasesUsed) { @@ -1390,15 +1666,15 @@ private static SharedDictionary BuildTabDictionary( { cultureCode = chosenAliasesCultures[httpAlias]; } - + AddStandardPagesToDict(tabIndex, dupCheck, httpAlias, buildPortalId, cultureCode); - + // if any site root, add those as well. So if any module providers or rules work // on the custom http aliases, they will work as well. if (hasSiteRootRedirect) { int tempPathDepth = 0; - AddToTabDict( + AddToTabDict( tabIndex, dupCheck, httpAlias, @@ -1425,12 +1701,12 @@ private static SharedDictionary BuildTabDictionary( tabIndex.Add(rebuildData.LastPageKey, rebuildData.LastPageValue); } } - + // now clear out the rebuildData object, because we've checked and used it DataCache.RemoveCache("rebuildData"); } } - + return tabIndex; } @@ -1441,21 +1717,21 @@ private static SharedDictionary FetchTabPathDictionary(int porta { tabPathDict = CacheController.GetTabPathsFromCache(portalId); } - + return tabPathDict; } - private static void GetAliasFromSettings( + private static void GetAliasFromSettings( int portalId, out List useAliases, out Dictionary aliasCultures) { useAliases = new List(); aliasCultures = new Dictionary(); - + // 761 : return list of chosen aliases as well, so that Urls can be d var aliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - + // list of portal aliases for this portal List chosenAliases = null; var primaryAliases = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); @@ -1464,7 +1740,7 @@ private static void GetAliasFromSettings( chosenAliases = primaryAliases.GetAliasesForPortalId(portalId); aliasCultures = primaryAliases.GetAliasesAndCulturesForPortalId(portalId); } - + if (chosenAliases != null && chosenAliases.Count > 0) { // add the chosen alias in based on the usePortalAlias setting @@ -1479,7 +1755,7 @@ private static void GetAliasFromSettings( } } - private static string ManageCustomAliases( + private static string ManageCustomAliases( string tabCulture, PortalInfo thisPortal, TabInfo tab, @@ -1498,9 +1774,9 @@ private static string ManageCustomAliases( { customHttpAlias = tab.CustomAliases[currentCulture].ToLowerInvariant(); } - + customAliasUsed = httpAliases.Contains(customHttpAlias); - + // if there is a custom alias for this tab, and it's not one of the ones in the alias list, put it in // so that this tab will be put into the dictionary with not only the standard alias(es) but also // the custom alias. Other logic will decide if to redirect the 'wrong' alias if requested with this tab. @@ -1512,163 +1788,8 @@ private static string ManageCustomAliases( customHttpAliasesUsed.Add(customHttpAlias); } } - - return customHttpAlias; - } - - /// - /// Gets the Tab Dictionary from the DataCache memory location, if it's empty or missing, builds a new one. - /// - /// - /// ByRef parameter to return the minimum tab path depth (the number of '/' in the tab path). - /// ByRef parameter to return the maximum tab path depth (the number of '/' in the tab path). - /// ByRef parameter to return the minimum alias path depth (the number of '/' in the alias path. - /// ByRef parameter to return the maximum alias path depth (the number of '/' in the alias path). - /// - /// - /// - /// - /// Dictionary (string, string) of Tab paths in tab key, with the rewrite path as the value. - /// - /// Changes - /// Task 608 : Incrementally build tab dictionary instead of building entire dicitionary all at once - /// Task 609 : If usePortalAlias is specified, only build dictionary with specific portal alias : ignore others - /// Task 791 : allow for specification of true/false for using thread locking to prevent multiple rebuilds on threads. - /// - internal static SharedDictionary FetchTabDictionary( - int portalId, - out int minTabPathDepth, - out int maxTabPathDepth, - out int minAliasPathDepth, - out int maxAliasPathDepth, - FriendlyUrlSettings settings, - bool forceRebuild, - bool bypassCache, - Guid parentTraceId) - { - PathSizes depthInfo; - SharedDictionary portalDepths = null; - SharedDictionary dict = null; - SharedDictionary portalTabPathDictionary = null; - string reason = string.Empty; - var cc = new CacheController(); - if (bypassCache == false) - { - cc.GetPageIndexFromCache(out dict, out portalDepths, settings); - portalTabPathDictionary = FetchTabPathDictionary(portalId); - } - - if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) - { - // place threadlock to prevent two threads getting a null object. Use the same lock object that is used to - lock (tabPathDictBuildLock) - { - // check for the tab dictionary in the DataCache again as it could have been cached by another thread - // while waiting for the lock to become available. - if (bypassCache == false) - { - cc.GetPageIndexFromCache(out dict, out portalDepths, settings); - portalTabPathDictionary = FetchTabPathDictionary(portalId); - } - - if (dict == null || portalDepths == null || portalTabPathDictionary == null || !PortalExistsInIndex(portalDepths, portalId) || forceRebuild) - { - Hashtable homePageSkins; // keeps a list of skins set per home page and culture - - if (!bypassCache && dict == null) - { - reason += "No Page index in cache;"; - } - - if (forceRebuild) - { - reason += "Force Rebuild;"; - } - - if (bypassCache) - { - reason += "Bypass Cache;"; - } - - // PathSizes depthInfo; - // the cached dictionary was null or forceRebuild = true or bypassCache = true, so go get a new dictionary - dict = BuildTabDictionary( - out depthInfo, - settings, - portalId, - dict, - out homePageSkins, - out portalTabPathDictionary, - parentTraceId); - - if (portalDepths == null || forceRebuild) - { - portalDepths = new SharedDictionary(); - } - - // store the fact that this portal has been built - using (portalDepths.GetWriteLock()) - { - // depthInfo may already exist in index so use indexer to Add/Update rather than using Add method which - // would throw an exception if the portal already existed in the dictionary. - portalDepths[portalId] = depthInfo; - } - - if (bypassCache == false) // only cache if bypass not switched on - { - reason += "Portal " + portalId + " added to index;"; - using (dict.GetReadLock()) - { - reason += "Existing Page Index=" + dict.Count + " items;"; - } - - cc.StorePageIndexInCache(dict, portalDepths, settings, reason); - cc.StoreTabPathsInCache(portalId, portalTabPathDictionary, settings); - CacheController.StoreHomePageSkinsInCache(portalId, homePageSkins); - } - } - } - } - - if (PortalExistsInIndex(portalDepths, portalId)) - { - using (portalDepths.GetReadLock()) - { - depthInfo = portalDepths[portalId]; - minTabPathDepth = depthInfo.MinTabPathDepth; - maxTabPathDepth = depthInfo.MaxTabPathDepth; - minAliasPathDepth = depthInfo.MinAliasDepth; - maxAliasPathDepth = depthInfo.MaxAliasDepth; - } - } - else - { - // fallback values, should never get here: mainly for compiler wranings - minTabPathDepth = 1; - maxTabPathDepth = 10; - minAliasPathDepth = 1; - maxAliasPathDepth = 4; - } - - return dict; - } - - /// - /// Returns a list of aliases that are used in custom tab/alias association. - /// - /// - /// - internal static List GetCustomPortalAliases(FriendlyUrlSettings settings) - { - List aliases = CacheController.GetCustomAliasesFromCache(); - if (aliases == null) - { - aliases = FriendlyUrlController.GetCustomAliasesForTabs(); - CacheController.StoreCustomAliasesInCache(aliases, settings); - } - - return aliases; + return customHttpAlias; } /// @@ -1688,129 +1809,8 @@ private static bool PortalExistsInIndex(SharedDictionary portalD result = portalDepths.ContainsKey(portalId); } } - - return result; - } - /// - /// Gets the portal alias by portal. - /// - /// The portal id. - /// The portal alias. - /// Portal alias. - internal static PortalAliasInfo GetPortalAliasByPortal(int portalId, string portalAlias) - { - PortalAliasInfo retValue = null; - - // get the portal alias collection from the cache - var portalAliasCollection = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId).ToList(); - - bool foundAlias = false; - - // Do a specified PortalAlias check first - PortalAliasInfo portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == portalAlias.ToLowerInvariant()); - if (portalAliasInfo != null) - { - if (portalAliasInfo.PortalID == portalId) - { - // set the alias - retValue = portalAliasInfo; - foundAlias = true; - } - } - - if (!foundAlias) - { - // collection to hold aliases sorted by length, longest first - var aliases = (from p in portalAliasCollection - select p.HTTPAlias).ToList(); - - // get aliases sorted by length of alias - aliases.Sort(new StringLengthComparer()); - - // 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 - // IEnumerable aliases = portalAliasCollection.Keys.Cast().OrderByDescending(k => k.Length); - foreach (string currentAlias in aliases) - { - // 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 ) - portalAliasInfo = portalAliasCollection.SingleOrDefault(a => a.HTTPAlias == currentAlias); - if (portalAliasInfo != null) - { - string httpAlias = portalAliasInfo.HTTPAlias.ToLowerInvariant(); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && portalAliasInfo.PortalID == portalId) - { - retValue = portalAliasInfo; - break; - } - - httpAlias = httpAlias.StartsWith("www.") ? httpAlias.Replace("www.", string.Empty) : string.Concat("www.", httpAlias); - if (httpAlias.StartsWith(portalAlias.ToLowerInvariant()) && portalAliasInfo.PortalID == portalId) - { - retValue = portalAliasInfo; - break; - } - } - } - } - - return retValue; - } - - /// - /// Returns an ordered dictionary of alias regex patterns. These patterns are used to identify a portal alias by getting a match. - /// - /// - internal static OrderedDictionary GetPortalAliases(FriendlyUrlSettings settings) - { - // object to return - OrderedDictionary aliasList = CacheController.GetPortalAliasesFromCache(); - if (aliasList == null) - { - aliasList = BuildPortalAliasesDictionary(); - CacheController.StorePortalAliasesInCache(aliasList, settings); - } - - return aliasList; + return result; } - - /// - /// Returns the tab path of the base DNN tab. Ie /Home or /Somepage/SomeOtherPage. - /// - /// - /// - /// - /// Will remove // from the tabPath as stored in the Tabs object/table. - /// - internal static string GetTabPath(TabInfo tab, FriendlyUrlOptions options, Guid parentTraceId) - { - string tabPath = null; - if (options.CanGenerateNonStandardPath) - { - var tpd = FetchTabPathDictionary(tab.PortalID); - - if (tpd != null) - { - using (tpd.GetReadLock()) - { - if (tpd.Count > 0) - { - // get the path from the dictionary - string tabKey = tab.TabID.ToString(); - if (tpd.ContainsKey(tabKey)) - { - tabPath = tpd[tabKey]; - } - } - } - } - } - - return tabPath ?? TabPathHelper.GetFriendlyUrlTabPath(tab, options, parentTraceId); - } } } diff --git a/DNN Platform/Library/Entities/Urls/TabPathController.cs b/DNN Platform/Library/Entities/Urls/TabPathController.cs index 16d21f1d567..5c153ffaf77 100644 --- a/DNN Platform/Library/Entities/Urls/TabPathController.cs +++ b/DNN Platform/Library/Entities/Urls/TabPathController.cs @@ -19,14 +19,14 @@ namespace DotNetNuke.Entities.Urls /// The TabPathHelper class provides helper methods for working with tab urls. /// public class TabPathHelper - { + { 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) @@ -34,7 +34,7 @@ public static string BuildTabPathWithReplacement(TabInfo tab, FriendlyUrlOptions path = BuildTabPathWithReplacement(parentTab, options, parentTraceId); } } - + bool modified; path = AppendToTabPath(path, tab, options, out modified); @@ -59,12 +59,12 @@ public static string ReplaceDiacritics(string tabPath, out bool replacedDiacriti sb.Append(c); } } - + string result = sb.ToString(); replacedDiacritic = string.CompareOrdinal(tabPath, result) != 0; return sb.ToString(); - } - + } + /// /// Get the tab path for the supplied Tab. /// @@ -88,7 +88,7 @@ internal static string GetFriendlyUrlTabPath(TabInfo tab, FriendlyUrlOptions opt baseTabPath = ReplaceDiacritics(baseTabPath, out diacriticsChanged); } } - + return baseTabPath; } @@ -116,32 +116,9 @@ internal static int GetHomePageTabIdForCulture(string defaultCulture, int portal homeTabId = tab.TabID; } } - + 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) { @@ -160,7 +137,7 @@ internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAl skin = (string)homePageSkins[key2]; } } - + return skin; } @@ -185,7 +162,7 @@ internal static string GetTabAliasSkinForTabAndAlias(int portalId, string httpAl /// : include new out parameter 'isCustomPath' to return whether the Url was generated from Url-Master custom url. /// /// The tab path as specified. - internal static string GetTabPath( + internal static string GetTabPath( TabInfo tab, FriendlyUrlSettings settings, FriendlyUrlOptions options, @@ -205,7 +182,7 @@ internal static string GetTabPath( customHttpAlias = null; isCustomPath = false; if (homePageSiteRoot && isHomeTab && !hasPath) - + // && !isDefaultCultureCode - not working for non-language specifc custom root urls { newTabPath = "/"; // site root for home page @@ -217,7 +194,7 @@ internal static string GetTabPath( // this is the new tab path newTabPath = baseTabPath; - + // 871 : case insensitive compare for culture code, all lookups done on lower case string cultureCodeKey = string.Empty; if (cultureCode != null) @@ -226,11 +203,11 @@ internal static string GetTabPath( } bool checkForCustomHttpAlias = false; - + // get a custom tab name if redirects are being used SharedDictionary customAliasForTabs = null; SharedDictionary> urlDict; - + // 886 : don't fetch custom urls for host tabs (host tabs can't have redirects or custom Urls) if (tab.PortalID > -1) { @@ -239,7 +216,7 @@ internal static string GetTabPath( else { urlDict = new SharedDictionary>(); - + // create dummy dictionary for this tab } @@ -261,7 +238,7 @@ internal static string GetTabPath( { customTabPath = tabpaths[cultureCodeKey]; dropLangParms = true; - + // the url is based on a custom value which has embedded language parms, therefore don't need them in the url } else @@ -269,12 +246,12 @@ internal static string GetTabPath( if (isDefaultCultureCode && tabpaths.ContainsKey(string.Empty)) { customTabPath = tabpaths[string.Empty]; - + // dropLangParms = true;//drop the language parms if they exist, because this is the default language } } } - + if (customTabPath != null) { // 770 : pull out custom http alias if in string @@ -289,7 +266,7 @@ internal static string GetTabPath( newTabPath = customTabPath; } } - + if (newTabPath == string.Empty && hasPath) { // can't pass back a custom path which is blank if there are path segments to the requested final Url @@ -309,7 +286,7 @@ internal static string GetTabPath( else { checkForCustomHttpAlias = true; - + // always want to check for custom alias, even when we don't want to see any custom redirects } @@ -334,15 +311,15 @@ internal static string GetTabPath( if (!string.IsNullOrEmpty(tabCultureCode)) { dropLangParms = true; - + // if the tab has a specified culture code, then drop the language parameters from the friendly Url } } - + // make lower case if necessary newTabPath = AdvancedFriendlyUrlProvider.ForceLowerCaseIfAllowed(tab, newTabPath, settings); } - + return newTabPath; } @@ -390,8 +367,31 @@ internal static bool IsTabHomePage(TabInfo tab, PortalSettings portalSettings) } } } - + return isTabHomePage; - } + } + + 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(); + } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlAction.cs b/DNN Platform/Library/Entities/Urls/UrlAction.cs index 9ddc42cd9a0..40e79ad898c 100644 --- a/DNN Platform/Library/Entities/Urls/UrlAction.cs +++ b/DNN Platform/Library/Entities/Urls/UrlAction.cs @@ -17,8 +17,8 @@ namespace DotNetNuke.Entities.Urls public class UrlAction { private List _licensedProviders; - private PortalAliasInfo _portalAlias; - + private PortalAliasInfo _portalAlias; + // 829 add in constructor that works around physical path length restriction public UrlAction(HttpRequest request) { @@ -55,73 +55,46 @@ 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) - { - if (scheme.EndsWith("://") == false) - { - this.Scheme = scheme + "://"; - } - else - { - this.Scheme = scheme; - } - - this.ApplicationPath = applicationPath; - string domainPath = applicationPath.Replace(scheme, string.Empty); - this.DomainName = domainPath.Contains("/") ? domainPath.Substring(0, domainPath.IndexOf('/')) : domainPath; - this.PhysicalPath = physicalPath; - this.PortalId = -1; - this.TabId = -1; - this.Reason = RedirectReason.Not_Redirected; - this.FriendlyRewrite = false; - this.BypassCachedDictionary = false; - this.VirtualPath = StateBoolean.NotSet; - this.IsSecureConnection = false; - this.IsSSLOffloaded = false; - this.DebugMessages = new List(); - this.CultureCode = null; - } - public bool DoRewrite { get; set; } - + public bool FriendlyRewrite { get; set; } - + // friendlyRewrite means it was rewritten without looking up the tabid in the url public bool BypassCachedDictionary { get; set; } - + public string RewritePath { get; set; } - + public string RawUrl { get; set; } - + public string DebugData { get; set; } - + public string PhysicalPath { get; set; } - + public StateBoolean VirtualPath { get; set; } - + public string ApplicationPath { get; set; } - + public bool RebuildRequested { get; set; } - + public string FinalUrl { get; set; } - + public string Scheme { get; set; } - + public bool IsSecureConnection { get; set; } - + public bool IsSSLOffloaded { get; set; } - + public string DomainName { get; set; } - + public Exception Ex { get; set; } - + public string dictKey { get; set; } - + public string dictVal { get; set; } - + public List DebugMessages { get; set; } public int TabId { get; set; } @@ -148,7 +121,7 @@ private void Constructor(string scheme, string applicationPath, string physicalP public PortalAliasInfo PortalAlias { get { return this._portalAlias; } - + set { if (value != null) @@ -156,23 +129,23 @@ public PortalAliasInfo PortalAlias this.PortalId = value.PortalID; this.HttpAlias = value.HTTPAlias; } - + this._portalAlias = value; } } - + // the primary alias, if different to the current alias public PortalAliasInfo PrimaryAlias { get; set; } - + public DotNetNuke.Entities.Portals.PortalSettings.PortalAliasMapping PortalAliasMapping { get; set; } - + public bool CustomParmRewrite { get; set; } // 737 : mobile browser identificatino public BrowserTypes BrowserType { get; private set; } - public bool IsPhysicalResource { get; set; } - + public bool IsPhysicalResource { get; set; } + public string UnlicensedProviderMessage { get; set; } public bool UnlicensedProviderCalled { get; set; } @@ -194,21 +167,21 @@ public void SetActionWithNoDowngrade(ActionType newAction) { this.Action = newAction; } - + break; default: this.Action = newAction; break; } } - + public void AddLicensedProviders(List licensedProviders) { if (this._licensedProviders == null) { this._licensedProviders = new List(); } - + foreach (string lp in licensedProviders) { if (this._licensedProviders.Contains(lp.ToLowerInvariant()) == false) @@ -224,7 +197,7 @@ public void AddLicensedProvider(string providerName) { this._licensedProviders = new List(); } - + if (this._licensedProviders.Contains(providerName.ToLowerInvariant()) == false) { this._licensedProviders.Add(providerName.ToLowerInvariant()); @@ -237,7 +210,7 @@ public bool IsProviderLicensed(string providerName) { return false; } - + return this._licensedProviders.Contains(providerName.ToLowerInvariant()); } @@ -283,11 +256,38 @@ public void SetRedirectAllowed(string path, FriendlyUrlSettings settings) catch (Exception ex) { this.RedirectAllowed = true; // default : true, unless regex allows it. So if regex causes an exception - + // then we should allow the redirect UrlRewriterUtils.LogExceptionInRequest(ex, "Not Set", this); this.Ex = ex; } - } + } + + private void Constructor(string scheme, string applicationPath, string physicalPath) + { + if (scheme.EndsWith("://") == false) + { + this.Scheme = scheme + "://"; + } + else + { + this.Scheme = scheme; + } + + this.ApplicationPath = applicationPath; + string domainPath = applicationPath.Replace(scheme, string.Empty); + this.DomainName = domainPath.Contains("/") ? domainPath.Substring(0, domainPath.IndexOf('/')) : domainPath; + this.PhysicalPath = physicalPath; + this.PortalId = -1; + this.TabId = -1; + this.Reason = RedirectReason.Not_Redirected; + this.FriendlyRewrite = false; + this.BypassCachedDictionary = false; + this.VirtualPath = StateBoolean.NotSet; + this.IsSecureConnection = false; + this.IsSSLOffloaded = false; + this.DebugMessages = new List(); + this.CultureCode = null; + } } } diff --git a/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs b/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs index 130d7ee3769..c94f43d5d26 100644 --- a/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs +++ b/DNN Platform/Library/Entities/Urls/UrlEnumHelpers.cs @@ -15,7 +15,7 @@ public static BrowserTypes FromString(string value) result = BrowserTypes.Mobile; break; } - + return result; } } diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs index a8caf77e05e..cf40bd87d72 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterBase.cs @@ -21,7 +21,7 @@ public abstract class UrlRewriterBase protected static void AutoAddAlias(HttpContext context) { var portalId = Host.Host.HostPortalID; - + // the domain name was not found so try using the host portal's first alias if (portalId > Null.NullInteger) { diff --git a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs index 464e17525a8..bb62791c1db 100644 --- a/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs +++ b/DNN Platform/Library/Entities/Urls/UrlRewriterUtils.cs @@ -26,22 +26,22 @@ public static class UrlRewriterUtils /// public static FriendlyUrlOptions GetOptionsFromSettings(FriendlyUrlSettings settings) { - var options = new FriendlyUrlOptions - { + 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, + : 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,10 +77,10 @@ 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)); @@ -99,7 +99,7 @@ public static void Log404(HttpRequest request, FriendlyUrlSettings settings, Url { log.LogProperties.Add(new LogDetailInfo("Referer", request.Headers["Referer"])); } - + log.LogProperties.Add(new LogDetailInfo("Url", request.Url.AbsoluteUri)); log.LogProperties.Add(new LogDetailInfo("UserAgent", request.UserAgent)); log.LogProperties.Add(new LogDetailInfo("HostAddress", request.UserHostAddress)); @@ -124,7 +124,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction // the exception will be logged once for the life of the cache / application restart or 1 hour, whichever is shorter. // create a cache key for this exception type string cacheKey = ex.GetType().ToString(); - + // see if there is an existing object logged for this exception type object existingEx = DataCache.GetCache(cacheKey); if (existingEx == null) @@ -132,7 +132,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction // if there was no existing object logged for this exception type, this is a new exception DateTime expire = DateTime.Now.AddHours(1); DataCache.SetCache(cacheKey, cacheKey, expire); - + // just store the cache key - it doesn't really matter // create a log event var log = new LogInfo { LogTypeKey = "GENERAL_EXCEPTION" }; @@ -172,7 +172,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction { log.AddProperty("Result", "Result value null"); } - + log.AddProperty("Exception Type", ex.GetType().ToString()); log.AddProperty("Message", ex.Message); log.AddProperty("Stack Trace", ex.StackTrace); @@ -181,7 +181,7 @@ public static void LogExceptionInRequest(Exception ex, string status, UrlAction log.AddProperty("Inner Exception Message", ex.InnerException.Message); log.AddProperty("Inner Exception Stacktrace", ex.InnerException.StackTrace); } - + log.BypassBuffering = true; LogController.Instance.AddLog(log); diff --git a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs index af4e292721e..7ea5df9ecbf 100644 --- a/DNN Platform/Library/Entities/Urls/XmlHelpers.cs +++ b/DNN Platform/Library/Entities/Urls/XmlHelpers.cs @@ -28,7 +28,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames { messages = new List(); } - + var tabIds = new List(); if (!string.IsNullOrEmpty(tabIdsRaw)) { @@ -42,7 +42,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames } } } - + if (tabNames != null) { // get the portal by name @@ -85,7 +85,7 @@ internal static List TabIdsFromAttributes(string tabIdsRaw, string tabNames } } } - + return tabIds; } } diff --git a/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs b/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs index ef7fc0eecb6..9f78c31a583 100644 --- a/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/IFollowerEventHandlers.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Users public interface IFollowerEventHandlers { void FollowRequested(object sender, RelationshipEventArgs args); - + void UnfollowRequested(object sender, RelationshipEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs b/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs index afdd6a034d4..fde0e125c14 100644 --- a/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/IFriendshipEventHandlers.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.Entities.Friends public interface IFriendshipEventHandlers { void FriendshipRequested(object sender, RelationshipEventArgs args); - + void FriendshipAccepted(object sender, RelationshipEventArgs args); - + void FriendshipDeleted(object sender, RelationshipEventArgs args); } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs index 701ae832ed0..29d5455be73 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordController.cs @@ -17,9 +17,9 @@ namespace DotNetNuke.Entities.Users.Membership using DotNetNuke.Entities.Portals; public class MembershipPasswordController - { - private readonly DataProvider _dataProvider = DataProvider.Instance(); - + { + private readonly DataProvider _dataProvider = DataProvider.Instance(); + /// /// returns the password history of the supplied user. /// @@ -41,32 +41,6 @@ public List GetPasswordHistory(int userId, int portalId) 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()) - { - byte[] newSalt = this.GetRandomSaltValue(); - byte[] bytePassword = Encoding.Unicode.GetBytes(password); - var inputBuffer = new byte[bytePassword.Length + 16]; - Buffer.BlockCopy(bytePassword, 0, inputBuffer, 0, bytePassword.Length); - Buffer.BlockCopy(newSalt, 0, inputBuffer, bytePassword.Length, 16); - byte[] bhashedPassword = ha.ComputeHash(inputBuffer); - string hashedPassword = Convert.ToBase64String(bhashedPassword); - - this._dataProvider.AddPasswordHistory(userId, hashedPassword, Convert.ToBase64String(newSalt), passwordsRetained, daysRetained); - } - } - - private byte[] GetRandomSaltValue() - { - using (var rcsp = new RNGCryptoServiceProvider()) - { - var bSalt = new byte[16]; - rcsp.GetBytes(bSalt); - return bSalt; - } - } /// /// checks to see if the password is in history and adds it if it is not. @@ -105,7 +79,7 @@ public bool IsPasswordInHistory(int userId, int portalId, string newPassword, bo isPreviouslyUsed = true; } } - + return isPreviouslyUsed; } @@ -117,7 +91,7 @@ public bool IsPasswordInHistory(int userId, int portalId, string newPassword, bo public bool IsPasswordPreviouslyUsed(int userId, string password) { bool foundMatch = false; - + // use default algorithm (SHA1CryptoServiceProvider ) using (HashAlgorithm ha = HashAlgorithm.Create()) { @@ -133,10 +107,10 @@ public bool IsPasswordPreviouslyUsed(int userId, string password) Buffer.BlockCopy(oldSalt, 0, inputBuffer, bytePassword.Length, 16); byte[] bhashedPassword = ha.ComputeHash(inputBuffer); string hashedPassword = Convert.ToBase64String(bhashedPassword); - if (hashedPassword == oldEncodedPassword) - { - foundMatch = true; - } + if (hashedPassword == oldEncodedPassword) + { + foundMatch = true; + } } } @@ -156,7 +130,7 @@ public bool IsValidToken(int userId, Guid resetToken) { return true; } - + return false; } @@ -188,5 +162,31 @@ public bool FoundBannedPassword(string inputString) return false; } + + private void AddPasswordHistory(int userId, string password, int passwordsRetained, int daysRetained) + { + using (HashAlgorithm ha = HashAlgorithm.Create()) + { + byte[] newSalt = this.GetRandomSaltValue(); + byte[] bytePassword = Encoding.Unicode.GetBytes(password); + var inputBuffer = new byte[bytePassword.Length + 16]; + Buffer.BlockCopy(bytePassword, 0, inputBuffer, 0, bytePassword.Length); + Buffer.BlockCopy(newSalt, 0, inputBuffer, bytePassword.Length, 16); + byte[] bhashedPassword = ha.ComputeHash(inputBuffer); + string hashedPassword = Convert.ToBase64String(bhashedPassword); + + this._dataProvider.AddPasswordHistory(userId, hashedPassword, Convert.ToBase64String(newSalt), passwordsRetained, daysRetained); + } + } + + private byte[] GetRandomSaltValue() + { + using (var rcsp = new RNGCryptoServiceProvider()) + { + var bSalt = new byte[16]; + rcsp.GetBytes(bSalt); + return bSalt; + } + } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs index e4b7928a62e..33c5f76a130 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPasswordSettings.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Entities.Users.Membership using DotNetNuke.Security.Membership; public class MembershipPasswordSettings - { - /// + { + /// /// Initializes a new instance of the class. /// Initialiser for MembershipPasswordSettings provider object. /// @@ -40,20 +40,6 @@ public MembershipPasswordSettings(int portalId) this.EnablePasswordHistory = true; } } - - public bool EnableBannedList { get; set; } - - public bool EnableStrengthMeter { get; set; } - - public bool EnableIPChecking { get; set; } - - public bool EnablePasswordHistory { get; set; } - - public int NumberOfPasswordsStored { get; set; } - - public int NumberOfDaysBeforePasswordReuse { get; set; } - - public int ResetLinkValidity { get; set; } /// /// Gets minimum number of non-alphanumeric characters setting for password strength indicator. @@ -102,16 +88,30 @@ public PasswordFormat PasswordFormat public string ValidationExpression { get { return System.Web.Security.Membership.PasswordStrengthRegularExpression; } - } + } + + public bool EnableBannedList { get; set; } + + public bool EnableStrengthMeter { get; set; } + + public bool EnableIPChecking { get; set; } + + public bool EnablePasswordHistory { get; set; } + + public int NumberOfPasswordsStored { get; set; } + + public int NumberOfDaysBeforePasswordReuse { get; set; } + + public int ResetLinkValidity { get; set; } + + public int PortalId { get; set; } - public int PortalId { get; set; } - private static bool IsInstallRequest(HttpRequest request) { var url = request.Url.LocalPath.ToLowerInvariant(); return url.EndsWith("/install.aspx") || url.Contains("/installwizard.aspx"); - } + } } } diff --git a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs index b936c44b878..a253390f362 100644 --- a/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Membership/MembershipPropertyAccess.cs @@ -15,7 +15,7 @@ public class MembershipPropertyAccess : IPropertyAccess public MembershipPropertyAccess(UserInfo User) { this.objUser = User; - } + } public CacheLevel Cacheability { @@ -23,8 +23,8 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope CurrentScope, ref bool PropertyNotFound) { UserMembership objMembership = this.objUser.Membership; @@ -36,13 +36,13 @@ public string GetProperty(string propertyName, string format, CultureInfo format PropertyNotFound = true; return PropertyAccess.ContentLocked; } - + string OutputFormat = string.Empty; if (format == string.Empty) { OutputFormat = "g"; } - + switch (propertyName.ToLowerInvariant()) { case "approved": @@ -80,7 +80,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "email": return PropertyAccess.FormatString(this.objUser.Email, format); } - + return PropertyAccess.GetObjectProperty(objMembership, propertyName, format, formatProvider, ref PropertyNotFound); } } diff --git a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs index b6c8a422a92..03d4e47274e 100644 --- a/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs +++ b/DNN Platform/Library/Entities/Users/Membership/PasswordHistory.cs @@ -13,11 +13,11 @@ namespace DotNetNuke.Entities.Users.Membership public class PasswordHistory : BaseEntityInfo { public int PasswordHistoryId { get; set; } - + public int UserId { get; set; } - + public string Password { get; set; } - + public string PasswordSalt { get; set; } /// diff --git a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs index 252a0dc7aae..1e33d5241b2 100644 --- a/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs +++ b/DNN Platform/Library/Entities/Users/Membership/UserMembership.cs @@ -26,7 +26,7 @@ public class UserMembership private readonly UserInfo _user; private bool _approved; - public UserMembership() + public UserMembership() : this(new UserInfo()) { } @@ -48,7 +48,7 @@ public bool Approved { return this._approved; } - + set { if (!this._approved && value) @@ -82,13 +82,6 @@ public bool Approved [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. @@ -158,5 +151,12 @@ internal void ConfirmApproved() /// /// ----------------------------------------------------------------------------- public bool UpdatePassword { get; set; } + + internal bool Approving { get; private set; } + + internal void ConfirmApproved() + { + this.Approving = false; + } } } diff --git a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs index f13eaf3482e..8d6de11dfc7 100644 --- a/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs +++ b/DNN Platform/Library/Entities/Users/Profile/ProfilePropertyAccess.cs @@ -168,6 +168,20 @@ public static string GetRichValue(ProfilePropertyDefinition property, string for return result; } + public static string DisplayDataType(ProfilePropertyDefinition definition) + { + string cacheKey = string.Format("DisplayDataType:{0}", definition.DataType); + string strDataType = Convert.ToString(DataCache.GetCache(cacheKey)) + string.Empty; + if (strDataType == string.Empty) + { + var objListController = new ListController(); + strDataType = objListController.GetListEntryInfo("DataType", definition.DataType).Value; + DataCache.SetCache(cacheKey, strDataType); + } + + return strDataType; + } + 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) @@ -236,19 +250,5 @@ 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); - string strDataType = Convert.ToString(DataCache.GetCache(cacheKey)) + string.Empty; - if (strDataType == string.Empty) - { - var objListController = new ListController(); - strDataType = objListController.GetListEntryInfo("DataType", definition.DataType).Value; - DataCache.SetCache(cacheKey, strDataType); - } - - return strDataType; - } } } diff --git a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs index 84b3a9a2fa3..79ecf14f703 100644 --- a/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs +++ b/DNN Platform/Library/Entities/Users/Profile/UserProfile.cs @@ -26,8 +26,8 @@ namespace DotNetNuke.Entities.Users /// [Serializable] public class UserProfile : IIndexable - { - // Name properties + { + // Name properties public const string USERPROFILE_FirstName = "FirstName"; public const string USERPROFILE_LastName = "LastName"; public const string USERPROFILE_Title = "Title"; @@ -54,14 +54,14 @@ public class UserProfile : IIndexable public const string USERPROFILE_TimeZone = "TimeZone"; public const string USERPROFILE_PreferredLocale = "PreferredLocale"; public const string USERPROFILE_PreferredTimeZone = "PreferredTimeZone"; - public const string USERPROFILE_Biography = "Biography"; + public const string USERPROFILE_Biography = "Biography"; private bool _IsDirty; private UserInfo _user; // collection to store all profile properties. - private ProfilePropertyDefinitionCollection _profileProperties; - + private ProfilePropertyDefinitionCollection _profileProperties; + public UserProfile() { } @@ -69,8 +69,132 @@ public UserProfile() public UserProfile(UserInfo user) { this._user = user; - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the Full Name. + /// + /// ----------------------------------------------------------------------------- + public string FullName + { + get + { + return this.FirstName + " " + this.LastName; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets or sets whether the property has been changed. + /// + /// ----------------------------------------------------------------------------- + public bool IsDirty + { + get + { + return this._IsDirty; + } + } + + /// + /// Gets property will return a URL for the photourl - if the path contains invalid url characters it will return a fileticket. + /// + public string PhotoURL + { + get + { + string photoURL = Globals.ApplicationPath + "/images/no_avatar.gif"; + ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); + if (photoProperty != null) + { + UserInfo user = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + + bool isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, this._user); + if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) + { + var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); + if (fileInfo != null) + { + photoURL = FileManager.Instance.GetUrl(fileInfo); + } + } + } + + return photoURL; + } + } + + /// + /// Gets property will return the file path of the photo url (designed to be used when files are loaded via the filesystem e.g for caching). + /// + [Obsolete("Obsolete in 7.2.2, Use PhotoUrl instead of it.. Scheduled removal in v10.0.0.")] + public string PhotoURLFile + { + get + { + string photoURLFile = Globals.ApplicationPath + "/images/no_avatar.gif"; + ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); + if (photoProperty != null) + { + UserInfo user = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + + bool isVisible = user.UserID == this._user.UserID; + if (!isVisible) + { + switch (photoProperty.ProfileVisibility.VisibilityMode) + { + case UserVisibilityMode.AllUsers: + isVisible = true; + break; + case UserVisibilityMode.MembersOnly: + isVisible = user.UserID > 0; + break; + case UserVisibilityMode.AdminOnly: + isVisible = user.IsInRole(settings.AdministratorRoleName); + break; + case UserVisibilityMode.FriendsAndGroups: + break; + } + } + + if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) + { + var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); + if (fileInfo != null) + { + string rootFolder = string.Empty; + if (fileInfo.PortalId == Null.NullInteger) + { + // Host + rootFolder = Globals.HostPath; + } + else + { + rootFolder = settings.HomeDirectory; + } + + photoURLFile = TestableGlobals.Instance.ResolveUrl(rootFolder + fileInfo.Folder + fileInfo.FileName); + } + } + } + + return photoURLFile; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the Collection of Profile Properties. + /// + /// ----------------------------------------------------------------------------- + public ProfilePropertyDefinitionCollection ProfileProperties + { + get { return this._profileProperties ?? (this._profileProperties = new ProfilePropertyDefinitionCollection()); } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Cell/Mobile Phone. @@ -82,7 +206,7 @@ public string Cell { return this.GetPropertyValue(USERPROFILE_Cell); } - + set { this.SetProfileProperty(USERPROFILE_Cell, value); @@ -100,7 +224,7 @@ public string City { return this.GetPropertyValue(USERPROFILE_City); } - + set { this.SetProfileProperty(USERPROFILE_City, value); @@ -118,7 +242,7 @@ public string Country { return this.GetPropertyValue(USERPROFILE_Country); } - + set { this.SetProfileProperty(USERPROFILE_Country, value); @@ -136,7 +260,7 @@ public string Fax { return this.GetPropertyValue(USERPROFILE_Fax); } - + set { this.SetProfileProperty(USERPROFILE_Fax, value); @@ -154,26 +278,13 @@ public string FirstName { return this.GetPropertyValue(USERPROFILE_FirstName); } - + set { this.SetProfileProperty(USERPROFILE_FirstName, value); } } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Full Name. - /// - /// ----------------------------------------------------------------------------- - public string FullName - { - get - { - return this.FirstName + " " + this.LastName; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Instant Messenger Handle. @@ -185,26 +296,13 @@ public string IM { return this.GetPropertyValue(USERPROFILE_IM); } - + set { this.SetProfileProperty(USERPROFILE_IM, value); } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets or sets whether the property has been changed. - /// - /// ----------------------------------------------------------------------------- - public bool IsDirty - { - get - { - return this._IsDirty; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Last Name. @@ -216,7 +314,7 @@ public string LastName { return this.GetPropertyValue(USERPROFILE_LastName); } - + set { this.SetProfileProperty(USERPROFILE_LastName, value); @@ -229,101 +327,13 @@ public string Photo { return this.GetPropertyValue(USERPROFILE_Photo); } - + set { this.SetProfileProperty(USERPROFILE_Photo, value); } } - /// - /// Gets property will return a URL for the photourl - if the path contains invalid url characters it will return a fileticket. - /// - public string PhotoURL - { - get - { - string photoURL = Globals.ApplicationPath + "/images/no_avatar.gif"; - ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); - if (photoProperty != null) - { - UserInfo user = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - - bool isVisible = ProfilePropertyAccess.CheckAccessLevel(settings, photoProperty, user, this._user); - if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) - { - var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); - if (fileInfo != null) - { - photoURL = FileManager.Instance.GetUrl(fileInfo); - } - } - } - - return photoURL; - } - } - - /// - /// Gets property will return the file path of the photo url (designed to be used when files are loaded via the filesystem e.g for caching). - /// - [Obsolete("Obsolete in 7.2.2, Use PhotoUrl instead of it.. Scheduled removal in v10.0.0.")] - public string PhotoURLFile - { - get - { - string photoURLFile = Globals.ApplicationPath + "/images/no_avatar.gif"; - ProfilePropertyDefinition photoProperty = this.GetProperty(USERPROFILE_Photo); - if (photoProperty != null) - { - UserInfo user = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - - bool isVisible = user.UserID == this._user.UserID; - if (!isVisible) - { - switch (photoProperty.ProfileVisibility.VisibilityMode) - { - case UserVisibilityMode.AllUsers: - isVisible = true; - break; - case UserVisibilityMode.MembersOnly: - isVisible = user.UserID > 0; - break; - case UserVisibilityMode.AdminOnly: - isVisible = user.IsInRole(settings.AdministratorRoleName); - break; - case UserVisibilityMode.FriendsAndGroups: - break; - } - } - - if (!string.IsNullOrEmpty(photoProperty.PropertyValue) && isVisible) - { - var fileInfo = FileManager.Instance.GetFile(int.Parse(photoProperty.PropertyValue)); - if (fileInfo != null) - { - string rootFolder = string.Empty; - if (fileInfo.PortalId == Null.NullInteger) - { - // Host - rootFolder = Globals.HostPath; - } - else - { - rootFolder = settings.HomeDirectory; - } - - photoURLFile = TestableGlobals.Instance.ResolveUrl(rootFolder + fileInfo.Folder + fileInfo.FileName); - } - } - } - - return photoURLFile; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the PostalCode part of the Address. @@ -335,7 +345,7 @@ public string PostalCode { return this.GetPropertyValue(USERPROFILE_PostalCode); } - + set { this.SetProfileProperty(USERPROFILE_PostalCode, value); @@ -353,7 +363,7 @@ public string PreferredLocale { return this.GetPropertyValue(USERPROFILE_PreferredLocale); } - + set { this.SetProfileProperty(USERPROFILE_PreferredLocale, value); @@ -374,7 +384,7 @@ public TimeZoneInfo PreferredTimeZone { _TimeZone = TimeZoneInfo.FindSystemTimeZoneById(_TimeZoneId); } - + // Next check if there is a Portal Setting else { @@ -388,7 +398,7 @@ public TimeZoneInfo PreferredTimeZone // still we can't find it or it's somehow set to null return _TimeZone ?? TimeZoneInfo.Local; } - + set { if (value != null) @@ -398,16 +408,6 @@ public TimeZoneInfo PreferredTimeZone } } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Collection of Profile Properties. - /// - /// ----------------------------------------------------------------------------- - public ProfilePropertyDefinitionCollection ProfileProperties - { - get { return this._profileProperties ?? (this._profileProperties = new ProfilePropertyDefinitionCollection()); } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Region part of the Address. @@ -419,7 +419,7 @@ public string Region { return this.GetPropertyValue(USERPROFILE_Region); } - + set { this.SetProfileProperty(USERPROFILE_Region, value); @@ -437,7 +437,7 @@ public string Street { return this.GetPropertyValue(USERPROFILE_Street); } - + set { this.SetProfileProperty(USERPROFILE_Street, value); @@ -455,7 +455,7 @@ public string Telephone { return this.GetPropertyValue(USERPROFILE_Telephone); } - + set { this.SetProfileProperty(USERPROFILE_Telephone, value); @@ -473,7 +473,7 @@ public string Title { return this.GetPropertyValue(USERPROFILE_Title); } - + set { this.SetProfileProperty(USERPROFILE_Title, value); @@ -491,7 +491,7 @@ public string Unit { return this.GetPropertyValue(USERPROFILE_Unit); } - + set { this.SetProfileProperty(USERPROFILE_Unit, value); @@ -509,33 +509,33 @@ public string Website { return this.GetPropertyValue(USERPROFILE_Website); } - + set { this.SetProfileProperty(USERPROFILE_Website, value); } - } - + } + 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; @@ -553,11 +553,11 @@ public object this[string name] { stringValue = Convert.ToString(value); } - + this.SetProfileProperty(name, stringValue); } - } - + } + /// ----------------------------------------------------------------------------- /// /// Clears the IsDirty Flag. @@ -577,7 +577,7 @@ public void ClearIsDirty() /// Gets a Profile Property from the Profile. /// /// - /// The name of the property to retrieve. + /// The name of the property to retrieve. /// /// ----------------------------------------------------------------------------- public ProfilePropertyDefinition GetProperty(string propName) @@ -590,7 +590,7 @@ public ProfilePropertyDefinition GetProperty(string propName) /// Gets a Profile Property Value from the Profile. /// /// - /// The name of the propoerty to retrieve. + /// The name of the propoerty to retrieve. /// /// ----------------------------------------------------------------------------- public string GetPropertyValue(string propName) @@ -611,7 +611,7 @@ public string GetPropertyValue(string propName) } } } - + return propValue; } @@ -648,22 +648,6 @@ 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. @@ -685,6 +669,22 @@ public void SetProfileProperty(string propName, string propValue) this._IsDirty = true; } } - } + } + + 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; + } } } diff --git a/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs b/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs index 0ed42e86d7e..6c7911655fd 100644 --- a/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs +++ b/DNN Platform/Library/Entities/Users/RelationshipEventArgs.cs @@ -18,7 +18,7 @@ internal RelationshipEventArgs(UserRelationship relationship, int portalId) } public UserRelationship Relationship { get; private set; } - + public int PortalID { get; private set; } } } diff --git a/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs b/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs index 1e0b2c3901a..3fbc13dd5a9 100644 --- a/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs +++ b/DNN Platform/Library/Entities/Users/Social/Data/DataService.cs @@ -13,8 +13,8 @@ namespace DotNetNuke.Entities.Users.Social.Data internal class DataService : ComponentBase, IDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - + private readonly DataProvider _provider = DataProvider.Instance(); + public IDataReader GetAllRelationshipTypes() { return this._provider.ExecuteReader("GetAllRelationshipTypes"); @@ -33,8 +33,8 @@ public void DeleteRelationshipType(int relationshipTypeId) public int SaveRelationshipType(RelationshipType relationshipType, int createUpdateUserId) { return this._provider.ExecuteScalar("SaveRelationshipType", relationshipType.RelationshipTypeId, relationshipType.Direction, relationshipType.Name, relationshipType.Description, createUpdateUserId); - } - + } + public void DeleteRelationship(int relationshipId) { this._provider.ExecuteNonQuery("DeleteRelationship", relationshipId); @@ -58,8 +58,8 @@ public IDataReader GetRelationshipsByPortalId(int portalId) public int SaveRelationship(Relationship relationship, int createUpdateUserId) { return this._provider.ExecuteScalar("SaveRelationship", relationship.RelationshipId, relationship.RelationshipTypeId, relationship.Name, relationship.Description, this._provider.GetNull(relationship.UserId), this._provider.GetNull(relationship.PortalId), relationship.DefaultResponse, createUpdateUserId); - } - + } + public void DeleteUserRelationship(int userRelationshipId) { this._provider.ExecuteNonQuery("DeleteUserRelationship", userRelationshipId); @@ -88,8 +88,8 @@ public IDataReader GetUserRelationshipsByRelationshipId(int relationshipId) public int SaveUserRelationship(UserRelationship userRelationship, int createUpdateUserId) { return this._provider.ExecuteScalar("SaveUserRelationship", userRelationship.UserRelationshipId, userRelationship.UserId, userRelationship.RelatedUserId, userRelationship.RelationshipId, userRelationship.Status, createUpdateUserId); - } - + } + public IDataReader GetUserRelationshipPreferenceById(int preferenceId) { return this._provider.ExecuteReader("GetUserRelationshipPreferenceByID", preferenceId); @@ -108,6 +108,6 @@ public void DeleteUserRelationshipPreference(int preferenceId) public int SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference, int createUpdateUserId) { return this._provider.ExecuteScalar("SaveUserRelationshipPreference", userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, userRelationshipPreference.RelationshipId, userRelationshipPreference.DefaultResponse, createUpdateUserId); - } + } } } diff --git a/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs b/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs index 3197fb6cd8f..2c92911bb65 100644 --- a/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs +++ b/DNN Platform/Library/Entities/Users/Social/Data/IDataService.cs @@ -9,41 +9,41 @@ namespace DotNetNuke.Entities.Users.Social.Data public interface IDataService { - void DeleteRelationshipType(int relationshipTypeId); + void DeleteRelationshipType(int relationshipTypeId); - IDataReader GetAllRelationshipTypes(); + IDataReader GetAllRelationshipTypes(); - IDataReader GetRelationshipType(int relationshipTypeId); + IDataReader GetRelationshipType(int relationshipTypeId); int SaveRelationshipType(RelationshipType relationshipType, int createUpdateUserId); - void DeleteRelationship(int relationshipId); + void DeleteRelationship(int relationshipId); - IDataReader GetRelationship(int relationshipId); + IDataReader GetRelationship(int relationshipId); - IDataReader GetRelationshipsByUserId(int userId); + IDataReader GetRelationshipsByUserId(int userId); - IDataReader GetRelationshipsByPortalId(int portalId); + IDataReader GetRelationshipsByPortalId(int portalId); int SaveRelationship(Relationship relationship, int createUpdateUserId); - void DeleteUserRelationship(int userRelationshipId); + void DeleteUserRelationship(int userRelationshipId); - IDataReader GetUserRelationship(int userRelationshipId); + IDataReader GetUserRelationship(int userRelationshipId); - IDataReader GetUserRelationship(int userId, int relatedUserId, int relationshipId, RelationshipDirection relationshipDirection); + IDataReader GetUserRelationship(int userId, int relatedUserId, int relationshipId, RelationshipDirection relationshipDirection); - IDataReader GetUserRelationships(int userId); + IDataReader GetUserRelationships(int userId); - IDataReader GetUserRelationshipsByRelationshipId(int relationshipId); + IDataReader GetUserRelationshipsByRelationshipId(int relationshipId); int SaveUserRelationship(UserRelationship userRelationship, int createUpdateUserId); - void DeleteUserRelationshipPreference(int preferenceId); + void DeleteUserRelationshipPreference(int preferenceId); - IDataReader GetUserRelationshipPreferenceById(int preferenceId); + IDataReader GetUserRelationshipPreferenceById(int preferenceId); - IDataReader GetUserRelationshipPreference(int userId, int relationshipId); + IDataReader GetUserRelationshipPreference(int userId, int relationshipId); int SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference, int createUpdateUserId); } diff --git a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs index 94bbedf7716..83fff2ad6b8 100644 --- a/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FollowersControllerImpl.cs @@ -74,11 +74,11 @@ public void UnFollowUser(UserInfo targetUser) private static void AddFollowerRequestNotification(UserInfo initiatingUser, UserInfo targetUser) { var notificationType = NotificationsController.Instance.GetNotificationType(IsFollowing(targetUser, initiatingUser) ? FollowerRequest : FollowBackRequest); - var subject = string.Format( + var subject = string.Format( Localization.GetString("AddFollowerRequestSubject", Localization.GlobalResourceFile), initiatingUser.DisplayName); - var body = string.Format( + var body = string.Format( Localization.GetString("AddFollowerRequestBody", Localization.GlobalResourceFile), initiatingUser.DisplayName); diff --git a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs index 889f0b05b96..6d9e351ebcf 100644 --- a/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/FriendsControllerImpl.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Entities.Users.Social.Internal internal class FriendsControllerImpl : IFriendsController { internal const string FriendRequest = "FriendRequest"; - + // static FriendsControllerImpl() // { // } @@ -71,7 +71,7 @@ public void AddFriend(UserInfo initiatingUser, UserInfo targetUser) Requires.NotNull("user1", initiatingUser); // Check if the friendship has been requested first by target user - var targetUserRelationship = RelationshipController.Instance.GetFriendRelationship( + var targetUserRelationship = RelationshipController.Instance.GetFriendRelationship( targetUser, initiatingUser); if (targetUserRelationship != null && targetUserRelationship.Status == RelationshipStatus.Pending) @@ -123,11 +123,11 @@ private static void AddFriendRequestNotification(UserInfo initiatingUser, UserIn { var notificationType = NotificationsController.Instance.GetNotificationType(FriendRequest); var language = GetUserPreferredLocale(targetUser)?.Name; - var subject = string.Format( + var subject = string.Format( Localization.GetString("AddFriendRequestSubject", Localization.GlobalResourceFile, language), initiatingUser.DisplayName); - var body = string.Format( + var body = string.Format( Localization.GetString("AddFriendRequestBody", Localization.GlobalResourceFile, language), initiatingUser.DisplayName); diff --git a/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs b/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs index 3863ab1f0e2..7d6866c689b 100644 --- a/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IFollowersController.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Users.Social public interface IFollowersController { void FollowUser(UserInfo targetUser); - + void FollowUser(UserInfo initiatingUser, UserInfo targetUser); void UnFollowUser(UserInfo targetUser); diff --git a/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs b/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs index cdcf8c0316f..62913e3e0e7 100644 --- a/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IFriendsController.cs @@ -9,11 +9,11 @@ public interface IFriendsController void AcceptFriend(UserInfo targetUser); void AddFriend(UserInfo targetUser); - + void AddFriend(UserInfo initiatingUser, UserInfo targetUser); void DeleteFriend(UserInfo targetUser); - + void DeleteFriend(UserInfo initiatingUser, UserInfo targetUser); } } diff --git a/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs b/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs index 9a6f96ddd8a..ebdfd39821c 100644 --- a/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs +++ b/DNN Platform/Library/Entities/Users/Social/IRelationshipController.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Entities.Users.Social using System.Collections.Generic; public interface IRelationshipController - { + { /// ----------------------------------------------------------------------------- /// /// Delete RelationshipType. @@ -19,7 +19,7 @@ public interface IRelationshipController /// ----------------------------------------------------------------------------- /// /// Get list of All RelationshipTypes defined in system. - /// + /// /// /// ----------------------------------------------------------------------------- IList GetAllRelationshipTypes(); @@ -28,7 +28,7 @@ public interface IRelationshipController /// /// Get RelationshipType By RelationshipTypeId. /// - /// RelationshipTypeId. + /// RelationshipTypeId. /// /// ----------------------------------------------------------------------------- RelationshipType GetRelationshipType(int relationshipTypeId); @@ -43,8 +43,8 @@ public interface IRelationshipController /// else existing RelationshipType is updated. /// /// ----------------------------------------------------------------------------- - void SaveRelationshipType(RelationshipType relationshipType); - + void SaveRelationshipType(RelationshipType relationshipType); + /// ----------------------------------------------------------------------------- /// /// Delete Relationship. @@ -57,7 +57,7 @@ public interface IRelationshipController /// /// Get Relationship By RelationshipId. /// - /// RelationshipId. + /// RelationshipId. /// /// ----------------------------------------------------------------------------- Relationship GetRelationship(int relationshipId); @@ -66,7 +66,7 @@ public interface IRelationshipController /// /// Get Relationships By UserId. /// - /// UserId. + /// UserId. /// /// ----------------------------------------------------------------------------- IList GetRelationshipsByUserId(int userId); @@ -75,7 +75,7 @@ public interface IRelationshipController /// /// Get Relationships By PortalId. /// - /// PortalId. + /// PortalId. /// /// ----------------------------------------------------------------------------- IList GetRelationshipsByPortalId(int portalId); @@ -90,8 +90,8 @@ public interface IRelationshipController /// else existing Relationship is updated. /// /// ----------------------------------------------------------------------------- - void SaveRelationship(Relationship relationship); - + void SaveRelationship(Relationship relationship); + /// ----------------------------------------------------------------------------- /// /// Delete UserRelationship. @@ -104,7 +104,7 @@ public interface IRelationshipController /// /// Get UserRelationship By UserRelationshipId. /// - /// UserRelationshipId. + /// UserRelationshipId. /// /// ----------------------------------------------------------------------------- UserRelationship GetUserRelationship(int userRelationshipId); @@ -115,7 +115,7 @@ public interface IRelationshipController /// /// User. /// Related User. - /// Relationship Object. + /// Relationship Object. /// /// ----------------------------------------------------------------------------- UserRelationship GetUserRelationship(UserInfo user, UserInfo relatedUser, Relationship relationship); @@ -137,8 +137,8 @@ public interface IRelationshipController /// else existing UserRelationship is updated. /// /// ----------------------------------------------------------------------------- - void SaveUserRelationship(UserRelationship userRelationship); - + void SaveUserRelationship(UserRelationship userRelationship); + /// ----------------------------------------------------------------------------- /// /// Delete UserRelationshipPreference. @@ -151,7 +151,7 @@ public interface IRelationshipController /// /// Get UserRelationshipPreference By RelationshipTypeId. /// - /// PreferenceId. + /// PreferenceId. /// /// ----------------------------------------------------------------------------- UserRelationshipPreference GetUserRelationshipPreference(int preferenceId); @@ -161,7 +161,7 @@ public interface IRelationshipController /// Get UserRelationshipPreference By UserId and RelationshipId. /// /// UserId. - /// RelationshipId. + /// RelationshipId. /// /// ----------------------------------------------------------------------------- UserRelationshipPreference GetUserRelationshipPreference(int userId, int relationshipId); @@ -176,26 +176,26 @@ public interface IRelationshipController /// else existing UserRelationshipPreference is updated. /// /// ----------------------------------------------------------------------------- - void SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference); - + void SaveUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference); + UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserInfo targetUser, Relationship relationship); void AcceptUserRelationship(int userRelationshipId); - void RemoveUserRelationship(int userRelationshipId); - + void RemoveUserRelationship(int userRelationshipId); + UserRelationship GetFollowerRelationship(UserInfo targetUser); - + UserRelationship GetFollowerRelationship(UserInfo initiatingUser, UserInfo targetUser); UserRelationship GetFollowingRelationship(UserInfo targetUser); - + UserRelationship GetFollowingRelationship(UserInfo initiatingUser, UserInfo targetUser); UserRelationship GetFriendRelationship(UserInfo targetUser); - - UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo targetUser); - + + UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo targetUser); + void CreateDefaultRelationshipsForPortal(int portalId); Relationship GetFriendsRelationshipByPortal(int portalId); diff --git a/DNN Platform/Library/Entities/Users/Social/Relationship.cs b/DNN Platform/Library/Entities/Users/Social/Relationship.cs index acef3597512..442d18de447 100644 --- a/DNN Platform/Library/Entities/Users/Social/Relationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/Relationship.cs @@ -33,6 +33,42 @@ public Relationship() this.RelationshipId = -1; } + /// + /// Gets a value indicating whether is this a Portal-Level Relationship. + /// + [XmlIgnore] + public bool IsPortalList + { + get + { + return this.UserId == Null.NullInteger && this.PortalId >= 0; + } + } + + /// + /// Gets a value indicating whether is this a Host-Level Relationship (very uncommon). + /// + [XmlIgnore] + public bool IsHostList + { + get + { + return this.UserId == Null.NullInteger && this.PortalId == Null.NullInteger; + } + } + + /// + /// Gets a value indicating whether is this a USer-Level Relationship. + /// + [XmlIgnore] + public bool IsUserList + { + get + { + return this.UserId > 0 && this.PortalId >= 0; + } + } + /// /// Gets or sets relationshipId - The primary key. /// @@ -75,42 +111,6 @@ public Relationship() [XmlAttribute] public RelationshipStatus DefaultResponse { get; set; } - /// - /// Gets a value indicating whether is this a Portal-Level Relationship. - /// - [XmlIgnore] - public bool IsPortalList - { - get - { - return this.UserId == Null.NullInteger && this.PortalId >= 0; - } - } - - /// - /// Gets a value indicating whether is this a Host-Level Relationship (very uncommon). - /// - [XmlIgnore] - public bool IsHostList - { - get - { - return this.UserId == Null.NullInteger && this.PortalId == Null.NullInteger; - } - } - - /// - /// Gets a value indicating whether is this a USer-Level Relationship. - /// - [XmlIgnore] - public bool IsUserList - { - get - { - return this.UserId > 0 && this.PortalId >= 0; - } - } - /// /// Gets or sets iHydratable.KeyID. /// @@ -121,7 +121,7 @@ public int KeyID { return this.RelationshipId; } - + set { this.RelationshipId = value; diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs index 9e33f985a39..96b9a15f161 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipControllerImpl.cs @@ -17,13 +17,13 @@ namespace DotNetNuke.Entities.Users.Social using DotNetNuke.Services.Social.Notifications; internal class RelationshipControllerImpl : IRelationshipController - { + { internal const string FriendRequest = "FriendRequest"; internal const string FollowerRequest = "FollowerRequest"; - internal const string FollowBackRequest = "FollowBackRequest"; + internal const string FollowBackRequest = "FollowBackRequest"; private readonly IDataService _dataService; - private readonly IEventLogController _eventLogController; - + private readonly IEventLogController _eventLogController; + public RelationshipControllerImpl() : this(DataService.Instance, EventLogController.Instance) { @@ -37,8 +37,8 @@ public RelationshipControllerImpl(IDataService dataService, IEventLogController this._dataService = dataService; this._eventLogController = eventLogController; - } - + } + public void DeleteRelationshipType(RelationshipType relationshipType) { Requires.NotNull("relationshipType", relationshipType); @@ -47,7 +47,7 @@ public void DeleteRelationshipType(RelationshipType relationshipType) // log event string logContent = - string.Format( + string.Format( Localization.GetString("RelationshipType_Deleted", Localization.GlobalResourceFile), relationshipType.Name, relationshipType.RelationshipTypeId); this.AddLog(logContent); @@ -58,11 +58,11 @@ public void DeleteRelationshipType(RelationshipType relationshipType) public IList GetAllRelationshipTypes() { - var cacheArgs = new CacheItemArgs( + var cacheArgs = new CacheItemArgs( DataCache.RelationshipTypesCacheKey, DataCache.RelationshipTypesCacheTimeOut, DataCache.RelationshipTypesCachePriority); - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( cacheArgs, c => CBO.FillCollection( @@ -82,21 +82,21 @@ public void SaveRelationshipType(RelationshipType relationshipType) ? "RelationshipType_Added" : "RelationshipType_Updated"; - relationshipType.RelationshipTypeId = this._dataService.SaveRelationshipType( + relationshipType.RelationshipTypeId = this._dataService.SaveRelationshipType( relationshipType, UserController.Instance.GetCurrentUserInfo(). UserID); // log event - string logContent = string.Format( + string logContent = string.Format( Localization.GetString(localizationKey, Localization.GlobalResourceFile), relationshipType.Name); this.AddLog(logContent); // clear cache DataCache.RemoveCache(DataCache.RelationshipTypesCacheKey); - } - + } + public void DeleteRelationship(Relationship relationship) { Requires.NotNull("relationship", relationship); @@ -105,7 +105,7 @@ public void DeleteRelationship(Relationship relationship) // log event string logContent = - string.Format( + string.Format( Localization.GetString("Relationship_Deleted", Localization.GlobalResourceFile), relationship.Name, relationship.RelationshipId); this.AddLog(logContent); @@ -131,13 +131,13 @@ public IList GetRelationshipsByPortalId(int portalId) { pid = PortalController.GetEffectivePortalId(portalId); } - - var cacheArgs = new CacheItemArgs( + + var cacheArgs = new CacheItemArgs( string.Format(DataCache.RelationshipByPortalIDCacheKey, pid), DataCache.RelationshipByPortalIDCacheTimeOut, DataCache.RelationshipByPortalIDCachePriority, pid); - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( cacheArgs, c => CBO.FillCollection( @@ -153,20 +153,20 @@ public void SaveRelationship(Relationship relationship) ? "Relationship_Added" : "Relationship_Updated"; - relationship.RelationshipId = this._dataService.SaveRelationship( + relationship.RelationshipId = this._dataService.SaveRelationship( relationship, UserController.Instance.GetCurrentUserInfo().UserID); // log event - string logContent = string.Format( + string logContent = string.Format( Localization.GetString(localizationKey, Localization.GlobalResourceFile), relationship.Name); this.AddLog(logContent); // clear cache this.ClearRelationshipCache(relationship); - } - + } + public void DeleteUserRelationship(UserRelationship userRelationship) { Requires.NotNull("userRelationship", userRelationship); @@ -175,7 +175,7 @@ public void DeleteUserRelationship(UserRelationship userRelationship) // log event string logContent = - string.Format( + string.Format( Localization.GetString("UserRelationship_Deleted", Localization.GlobalResourceFile), userRelationship.UserRelationshipId, userRelationship.UserId, userRelationship.RelatedUserId); @@ -201,7 +201,7 @@ public UserRelationship GetUserRelationship(UserInfo user, UserInfo relatedUser, relationship.RelationshipTypeId). Direction)); } - + return userRelationship; } @@ -218,13 +218,13 @@ public void SaveUserRelationship(UserRelationship userRelationship) ? "UserRelationship_Added" : "UserRelationship_Updated"; - userRelationship.UserRelationshipId = this._dataService.SaveUserRelationship( + userRelationship.UserRelationshipId = this._dataService.SaveUserRelationship( userRelationship, UserController.Instance.GetCurrentUserInfo(). UserID); // log event - string logContent = string.Format( + string logContent = string.Format( Localization.GetString(localizationKey, Localization.GlobalResourceFile), userRelationship.UserRelationshipId, userRelationship.UserId, userRelationship.RelatedUserId); @@ -232,8 +232,8 @@ public void SaveUserRelationship(UserRelationship userRelationship) // cache clear this.ClearUserCache(userRelationship); - } - + } + public void DeleteUserRelationshipPreference(UserRelationshipPreference userRelationshipPreference) { Requires.NotNull("userRelationshipPreference", userRelationshipPreference); @@ -258,7 +258,7 @@ public UserRelationshipPreference GetUserRelationshipPreference(int preferenceId public UserRelationshipPreference GetUserRelationshipPreference(int userId, int relationshipId) { return - CBO.FillObject(this._dataService.GetUserRelationshipPreference( + CBO.FillObject(this._dataService.GetUserRelationshipPreference( userId, relationshipId)); } @@ -272,18 +272,18 @@ public void SaveUserRelationshipPreference(UserRelationshipPreference userRelati : "UserRelationshipPreference_Updated"; userRelationshipPreference.PreferenceId = - this._dataService.SaveUserRelationshipPreference( + this._dataService.SaveUserRelationshipPreference( userRelationshipPreference, UserController.Instance.GetCurrentUserInfo().UserID); // log event - string logContent = string.Format( + string logContent = string.Format( Localization.GetString(localizationKey, Localization.GlobalResourceFile), userRelationshipPreference.PreferenceId, userRelationshipPreference.UserId, userRelationshipPreference.RelationshipId); this.AddLog(logContent); - } - + } + /// ----------------------------------------------------------------------------- /// /// Initiate an UserRelationship Request. @@ -319,7 +319,7 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn if (initiatingUser.UserID == targetUser.UserID) { throw new UserRelationshipForSameUsersException( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "UserRelationshipForSameUsersError", "Initiating and Target Users cannot have same UserID '{0}'.", initiatingUser.UserID)); @@ -329,7 +329,7 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn if (initiatingUser.PortalID != targetUser.PortalID) { throw new UserRelationshipForDifferentPortalException( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "UserRelationshipForDifferentPortalError", "Portal ID '{0}' of Initiating User is different from Portal ID '{1}' of Target User.", initiatingUser.PortalID, targetUser.PortalID)); @@ -346,30 +346,30 @@ public UserRelationship InitiateUserRelationship(UserInfo initiatingUser, UserIn } // no existing UserRelationship record found - + // use Relationship DefaultResponse as status RelationshipStatus status = relationship.DefaultResponse; - - UserRelationshipPreference preference = this.GetUserRelationshipPreference( + + UserRelationshipPreference preference = this.GetUserRelationshipPreference( targetUser.UserID, relationship.RelationshipId); if (preference != null) { status = preference.DefaultResponse; } - + if (status == RelationshipStatus.None) { 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); @@ -407,8 +407,8 @@ public void RemoveUserRelationship(int userRelationshipId) { this.DeleteUserRelationship(userRelationship); } - } - + } + /// ----------------------------------------------------------------------------- /// /// GetFollowerRelationship - Get the UserRelationship between Current User and the Target Users in Follower Relationship. @@ -512,24 +512,24 @@ public UserRelationship GetFriendRelationship(UserInfo initiatingUser, UserInfo return this.GetUserRelationship(initiatingUser, targetUser, this.GetFriendsRelationshipByPortal(initiatingUser.PortalID)); - } - + } + 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, - - // default response is None - RelationshipTypeId = (int)DefaultRelationshipTypes.Friends, + 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, }; this.SaveRelationship(friendRelationship); } @@ -537,32 +537,32 @@ public void CreateDefaultRelationshipsForPortal(int portalId) // 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, - - // default response is Accepted - RelationshipTypeId = (int)DefaultRelationshipTypes.Followers, + 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, }; this.SaveRelationship(followerRelationship); } } public Relationship GetFriendsRelationshipByPortal(int portalId) - { + { return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Friends); } public Relationship GetFollowersRelationshipByPortal(int portalId) { return this.GetRelationshipsByPortalId(portalId).FirstOrDefault(re => re.RelationshipTypeId == (int)DefaultRelationshipTypes.Followers); - } - + } + private void AddLog(string logContent) { this._eventLogController.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT); @@ -637,12 +637,12 @@ private UserRelationship VerifyUserRelationshipExist(int userRelationshipId) if (userRelationship == null) { throw new UserRelationshipDoesNotExistException( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "UserRelationshipDoesNotExistError", "UserRelationshipID '{0}' does not exist.", userRelationshipId)); } return userRelationship; - } + } } } diff --git a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs index 7c10da02b05..a4552eae525 100644 --- a/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs +++ b/DNN Platform/Library/Entities/Users/Social/RelationshipType.cs @@ -33,7 +33,7 @@ public int RelationshipTypeId { return this._relationshipTypeId; } - + set { this._relationshipTypeId = value; @@ -68,7 +68,7 @@ public int KeyID { return this.RelationshipTypeId; } - + set { this.RelationshipTypeId = value; diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs index 9354ef368d9..aa6d73dfd08 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationship.cs @@ -69,7 +69,7 @@ public int KeyID { return this.UserRelationshipId; } - + set { this.UserRelationshipId = value; diff --git a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs index cc155c197b6..2cafa7cc624 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserRelationshipPreference.cs @@ -61,7 +61,7 @@ public int KeyID { return this.PreferenceId; } - + set { this.PreferenceId = value; diff --git a/DNN Platform/Library/Entities/Users/Social/UserSocial.cs b/DNN Platform/Library/Entities/Users/Social/UserSocial.cs index f348a5e3db1..1db07e46d50 100644 --- a/DNN Platform/Library/Entities/Users/Social/UserSocial.cs +++ b/DNN Platform/Library/Entities/Users/Social/UserSocial.cs @@ -23,17 +23,17 @@ namespace DotNetNuke.Entities.Users.Social /// ----------------------------------------------------------------------------- [Serializable] public class UserSocial - { + { + private readonly UserInfo _userInfo; private IList _relationships; private IList _userRelationships; private IList _roles; - private readonly UserInfo _userInfo; - + public UserSocial(UserInfo userInfo) { this._userInfo = userInfo; - } - + } + /// /// Gets the Friend Relationship (if it exists with the current User). /// @@ -127,6 +127,6 @@ public IList Roles ? new List(0) : RoleController.Instance.GetUserRoles(this._userInfo, true)); } - } + } } } diff --git a/DNN Platform/Library/Entities/Users/UserController.cs b/DNN Platform/Library/Entities/Users/UserController.cs index c6f4141f230..ea2eb0f43e6 100644 --- a/DNN Platform/Library/Entities/Users/UserController.cs +++ b/DNN Platform/Library/Entities/Users/UserController.cs @@ -89,2063 +89,1944 @@ public static void AddUserPortal(int portalId, int userId) MembershipProvider.Instance().AddUserPortal(portalId, userId); } - UserInfo IUserController.GetCurrentUserInfo() + /// + /// ApproveUser removes the Unverified Users role from the user and adds the auto assigned roles. + /// + /// The user to update. + public static void ApproveUser(UserInfo user) { - return GetCurrentUserInternal(); + Requires.NotNull("user", user); + + var settings = PortalController.Instance.GetCurrentPortalSettings(); + var role = RoleController.Instance.GetRole(settings.PortalId, r => r.RoleName == "Unverified Users"); + + RoleController.DeleteUserRole(user, role, settings, false); + + AutoAssignUsersToRoles(user, settings.PortalId); + } + + /// + /// User has agreed to terms and conditions. The time is recorded at the same time in SQL. + /// + /// The user that agreed. + public static void UserAgreedToTerms(UserInfo user) + { + Requires.NotNull("user", user); + MembershipProvider.Instance().UserAgreedToTerms(user); + } + + /// + /// When called all users in the portal will need to agree to terms and conditions again. + /// + /// The portal for which to reset. + public static void ResetTermsAgreement(int portalId) + { + Requires.NotNull("portalId", portalId); + MembershipProvider.Instance().ResetTermsAgreement(portalId); + } + + /// + /// A user may request that their account be removed. This sets a flag on the user portal + /// so further processing may occur manually by the site admins. + /// + /// The user that desires to be removed. + public static void UserRequestsRemoval(UserInfo user, bool remove) + { + Requires.NotNull("user", user); + MembershipProvider.Instance().UserRequestsRemoval(user, remove); } /// ----------------------------------------------------------------------------- /// - /// GetUser retrieves a User from the DataStore. + /// ChangePassword attempts to change the users password. /// /// /// - /// The Id of the Portal. - /// The Id of the user being retrieved from the Data Store. - /// The User as a UserInfo object. + /// The user to update. + /// The old password. + /// The new password. + /// A Boolean indicating success or failure. /// ----------------------------------------------------------------------------- - public UserInfo GetUser(int portalId, int userId) - { - return GetUserById(portalId, userId); - } - - internal static Hashtable GetUserSettings(int portalId, Hashtable settings) + public static bool ChangePassword(UserInfo user, string oldPassword, string newPassword) { - portalId = GetEffectivePortalId(portalId); + bool passwordChanged; - if (settings["Column_FirstName"] == null) + // Although we would hope that the caller has already validated the password, + // Validate the new Password + if (ValidatePassword(newPassword)) { - settings["Column_FirstName"] = false; - } + passwordChanged = MembershipProvider.Instance().ChangePassword(user, oldPassword, newPassword); - if (settings["Column_LastName"] == null) - { - settings["Column_LastName"] = false; + if (passwordChanged) + { + // Update User + user.Membership.UpdatePassword = false; + UpdateUser(user.PortalID, user); + } } - - if (settings["Column_DisplayName"] == null) + else { - settings["Column_DisplayName"] = true; + throw new Exception("Invalid Password"); } - if (settings["Column_Address"] == null) - { - settings["Column_Address"] = true; - } + return passwordChanged; + } - if (settings["Column_Telephone"] == null) - { - settings["Column_Telephone"] = true; - } + /// + /// overload will validate the token and if valid change the password + /// it does not require an old password as it supports hashed passwords. + /// + /// The new password. + /// /// The reset token, typically supplied through a password reset email. + /// A Boolean indicating success or failure. + public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken) + { + bool passwordChanged; - if (settings["Column_Email"] == null) - { - settings["Column_Email"] = false; - } + Guid resetTokenGuid = new Guid(resetToken); - if (settings["Column_CreatedDate"] == null) - { - settings["Column_CreatedDate"] = true; - } + var user = GetUserByName(portalid, username); - if (settings["Column_LastLogin"] == null) + // if user does not exist return false + if (user == null) { - settings["Column_LastLogin"] = false; + return false; } - if (settings["Column_Authorized"] == null) + // check if the token supplied is the same as the users and is still valid + if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) { - settings["Column_Authorized"] = true; + return false; } - if (settings["Display_Mode"] == null) - { - settings["Display_Mode"] = DisplayMode.All; - } - else + var m = new MembershipPasswordController(); + if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword)) { - settings["Display_Mode"] = (DisplayMode)Convert.ToInt32(settings["Display_Mode"]); + return false; } - if (settings["Display_SuppressPager"] == null) + // Although we would hope that the caller has already validated the password, + // Validate the new Password + if (ValidatePassword(newPassword)) { - settings["Display_SuppressPager"] = false; - } + passwordChanged = MembershipProvider.Instance().ResetAndChangePassword(user, newPassword); - if (settings["Records_PerPage"] == null) - { - settings["Records_PerPage"] = 10; - } + // update reset token values to ensure token is 1-time use + user.PasswordResetExpiration = DateTime.MinValue; + user.PasswordResetToken = Guid.NewGuid(); - if (settings["Profile_DefaultVisibility"] == null) - { - settings["Profile_DefaultVisibility"] = UserVisibilityMode.AdminOnly; + if (passwordChanged) + { + // Update User + user.Membership.UpdatePassword = false; + UpdateUser(user.PortalID, user); + } } else { - settings["Profile_DefaultVisibility"] = (UserVisibilityMode)Convert.ToInt32(settings["Profile_DefaultVisibility"]); - } - - if (settings["Profile_DisplayVisibility"] == null) - { - settings["Profile_DisplayVisibility"] = true; + throw new Exception("Invalid Password"); } - if (settings["Profile_ManageServices"] == null) - { - settings["Profile_ManageServices"] = true; - } + return passwordChanged; + } - if (settings["Redirect_AfterLogin"] == null) - { - settings["Redirect_AfterLogin"] = -1; - } + /// + /// overload will validate the token and if valid change the password + /// it does not require an old password as it supports hashed passwords + /// errorMessage will define why reset failed. + /// + /// The new password. + /// The reset token, typically supplied through a password reset email. + /// A Boolean indicating success or failure. + public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage) + { + bool passwordChanged; + errorMessage = Null.NullString; + Guid resetTokenGuid = new Guid(resetToken); - if (settings["Redirect_AfterRegistration"] == null) - { - settings["Redirect_AfterRegistration"] = -1; - } + var user = GetUserByName(portalid, username); - if (settings["Redirect_AfterLogout"] == null) + // if user does not exist return false + if (user == null) { - settings["Redirect_AfterLogout"] = -1; + errorMessage = Localization.GetString("PasswordResetFailed_UserUndefined"); + return false; } - if (settings["Security_CaptchaLogin"] == null) + // check if the token supplied is the same as the users and is still valid + if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) { - settings["Security_CaptchaLogin"] = false; + errorMessage = Localization.GetString("PasswordResetFailed_ResetLinkExpired"); + return false; } - if (settings["Security_CaptchaRegister"] == null) + var m = new MembershipPasswordController(); + if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, false)) { - settings["Security_CaptchaRegister"] = false; + errorMessage = Localization.GetString("PasswordResetFailed_PasswordInHistory"); + return false; } - if (settings["Security_CaptchaChangePassword"] == null) + // Although we would hope that the caller has already validated the password, + // Validate the new Password + if (ValidatePassword(newPassword)) { - settings["Security_CaptchaChangePassword"] = false; - } + try + { + passwordChanged = MembershipProvider.Instance().ResetAndChangePassword(user, newPassword, answer); - if (settings["Security_CaptchaRetrivePassword"] == null) - { - settings["Security_CaptchaRetrivePassword"] = false; - } + if (passwordChanged) + { + // update reset token values to ensure token is 1-time use + user.PasswordResetExpiration = DateTime.MinValue; + user.PasswordResetToken = Guid.NewGuid(); - if (settings["Security_EmailValidation"] == null) - { - settings["Security_EmailValidation"] = Globals.glbEmailRegEx; - } + // Update User + user.Membership.UpdatePassword = false; + UpdateUser(user.PortalID, user); - if (settings["Security_UserNameValidation"] == null) - { - settings["Security_UserNameValidation"] = Globals.glbUserNameRegEx; + m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, true); // add the password into history. + } + else + { + errorMessage = Localization.GetString("PasswordResetFailed_WrongAnswer"); + } + } + catch (Exception) + { + passwordChanged = false; + errorMessage = Localization.GetString("PasswordResetFailed_WrongAnswer"); + } } - - // Forces a valid profile on registration - if (settings["Security_RequireValidProfile"] == null) + else { - settings["Security_RequireValidProfile"] = false; + throw new Exception("Invalid Password"); } - // Forces a valid profile on login - if (settings["Security_RequireValidProfileAtLogin"] == null) - { - settings["Security_RequireValidProfileAtLogin"] = true; - } - - if (settings["Security_UsersControl"] == null) - { - var portal = PortalController.Instance.GetPortal(portalId); - - if (portal != null && portal.Users > 1000) - { - settings["Security_UsersControl"] = UsersControl.TextBox; - } - else - { - settings["Security_UsersControl"] = UsersControl.Combo; - } - } - else - { - settings["Security_UsersControl"] = (UsersControl)Convert.ToInt32(settings["Security_UsersControl"]); - } - - // Display name format - if (settings["Security_DisplayNameFormat"] == null) - { - settings["Security_DisplayNameFormat"] = string.Empty; - } + return passwordChanged; + } - if (settings["Registration_RequireConfirmPassword"] == null) - { - settings["Registration_RequireConfirmPassword"] = true; - } + /// ----------------------------------------------------------------------------- + /// + /// ChangePasswordQuestionAndAnswer attempts to change the users password Question + /// and PasswordAnswer. + /// + /// + /// + /// The user to update. + /// The password. + /// The new password question. + /// The new password answer. + /// A Boolean indicating success or failure. + /// ----------------------------------------------------------------------------- + public static bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, string passwordAnswer) + { + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); + return MembershipProvider.Instance().ChangePasswordQuestionAndAnswer(user, password, passwordQuestion, passwordAnswer); + } - if (settings["Registration_RandomPassword"] == null) - { - settings["Registration_RandomPassword"] = false; - } + /// + /// update username in the system + /// works around membershipprovider limitation. + /// + /// user id. + /// new one. + public static void ChangeUsername(int userId, string newUsername) + { + MembershipProvider.Instance().ChangeUsername(userId, newUsername); + } - if (settings["Registration_UseEmailAsUserName"] == null) + public static void CheckInsecurePassword(string username, string password, ref UserLoginStatus loginStatus) + { + if (username == "admin" && (password == "admin" || password == "dnnadmin")) { - settings["Registration_UseEmailAsUserName"] = false; + loginStatus = UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; } - if (settings["Registration_UseAuthProviders"] == null) + if (username == "host" && (password == "host" || password == "dnnhost")) { - settings["Registration_UseAuthProviders"] = false; + loginStatus = UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD; } + } - if (settings["Registration_UseProfanityFilter"] == null) + /// + /// Copys a user to a different portal. + /// + /// The user to copy. + /// The destination portal. + /// A flag that indicates whether to merge the original user. + public static void CopyUserToPortal(UserInfo user, PortalInfo destinationPortal, bool mergeUser) + { + var targetUser = GetUserById(destinationPortal.PortalID, user.UserID); + if (targetUser == null) { - settings["Registration_UseProfanityFilter"] = false; - } + AddUserPortal(destinationPortal.PortalID, user.UserID); - if (settings["Registration_RegistrationFormType"] == null) - { - settings["Registration_RegistrationFormType"] = 0; - } + if (!user.IsSuperUser) + { + AutoAssignUsersToRoles(user, destinationPortal.PortalID); + } - if (settings["Registration_RegistrationFields"] == null) - { - settings["Registration_RegistrationFields"] = string.Empty; + targetUser = GetUserById(destinationPortal.PortalID, user.UserID); + MergeUserProperties(user, targetUser); + MergeUserProfileProperties(user, targetUser); } - - if (settings["Registration_ExcludeTerms"] == null) + else { - settings["Registration_ExcludeTerms"] = string.Empty; - } + targetUser.PortalID = destinationPortal.PortalID; - if (settings["Registration_RequireUniqueDisplayName"] == null) - { - settings["Registration_RequireUniqueDisplayName"] = false; + if (mergeUser) + { + MergeUserProperties(user, targetUser); + MergeUserProfileProperties(user, targetUser); + } } - return settings; + UpdateUser(targetUser.PortalID, targetUser); } - protected override Func GetFactory() + /// ----------------------------------------------------------------------------- + /// + /// Creates a new User in the Data Store. + /// + /// + /// The userInfo object to persist to the Database. + /// The Created status ot the User. + /// ----------------------------------------------------------------------------- + public static UserCreateStatus CreateUser(ref UserInfo user) { - return () => new UserController(); + return CreateUser(ref user, false); } - private static void AddEventLog(int portalId, string username, int userId, string portalName, string ip, UserLoginStatus loginStatus) + /// ----------------------------------------------------------------------------- + /// + /// Creates a new User in the Data Store. + /// + /// + /// The userInfo object to persist to the Database. + /// The sendEmailNotification flag defines whether registration email will be sent to user. + /// The Created status ot the User. + /// ----------------------------------------------------------------------------- + public static UserCreateStatus CreateUser(ref UserInfo user, bool sendEmailNotification) { - // 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); + int portalId = user.PortalID; + user.PortalID = GetEffectivePortalId(portalId); - // create log record - LogController.Instance.AddLog(log); - } + // ensure valid GUID exists (covers case where password is randomly generated - has 24 hr validity as per other Admin user steps + var passwordExpiry = DateTime.Now.AddMinutes(1440); + var passwordGuid = Guid.NewGuid(); + user.PasswordResetExpiration = passwordExpiry; + user.PasswordResetToken = passwordGuid; - private static void AutoAssignUsersToPortalRoles(UserInfo user, int portalId) - { - foreach (var role in RoleController.Instance.GetRoles(portalId, role => role.AutoAssignment && role.Status == RoleStatus.Approved)) + // Create the User + var createStatus = MembershipProvider.Instance().CreateUser(ref user); + + if (createStatus == UserCreateStatus.Success) { - RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); + // reapply guid/expiry (cleared when user is created) + user.PasswordResetExpiration = passwordExpiry; + user.PasswordResetToken = passwordGuid; + UpdateUser(user.PortalID, user); + EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_CREATED); + CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalId)); + if (!user.IsSuperUser) + { + // autoassign user to portal roles + AutoAssignUsersToRoles(user, portalId); + } + + EventManager.Instance.OnUserCreated(new UserEventArgs { User = user, SendNotification = sendEmailNotification }); } - // Clear the roles cache - so the usercount is correct - RoleController.Instance.ClearRoleCache(portalId); + // Reset PortalId + FixMemberPortalId(user, portalId); + return createStatus; } - private static void AutoAssignUsersToRoles(UserInfo user, int portalId) + /// ----------------------------------------------------------------------------- + /// + /// Deletes all Unauthorized Users for a Portal. + /// + /// + /// The Id of the Portal. + /// ----------------------------------------------------------------------------- + public static void DeleteUnauthorizedUsers(int portalId) { - var thisPortal = PortalController.Instance.GetPortal(portalId); - - if (IsMemberOfPortalGroup(portalId)) + // DNN-6924 for superusers call GetUsers(includeDeleted, superUsersOnly, portalId) + var arrUsers = (portalId == -1) ? GetUsers(true, true, portalId) : GetUnAuthorizedUsers(portalId); + for (int i = 0; i < arrUsers.Count; i++) { - foreach (var portal in PortalGroupController.Instance.GetPortalsByGroup(thisPortal.PortalGroupID)) + var user = arrUsers[i] as UserInfo; + if (user != null) { - 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 + if (user.Membership.Approved == false || user.Membership.LastLoginDate == Null.NullDate) { - AutoAssignUsersToPortalRoles(user, portal.PortalID); + DeleteUser(ref user, true, false); } } } - 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) + /// ----------------------------------------------------------------------------- + /// + /// Deletes an existing User from the Data Store. + /// + /// + /// The userInfo object to delete from the Database. + /// A flag that indicates whether an email notification should be sent. + /// A flag that indicates whether the Portal Administrator should be deleted. + /// A Boolean value that indicates whether the User was successfully deleted. + /// ----------------------------------------------------------------------------- + public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) { - FolderPermissionController.DeleteFolderPermissionsByUser(user); + int portalId = user.PortalID; + user.PortalID = GetEffectivePortalId(portalId); - // Delete Module Permissions - ModulePermissionController.DeleteModulePermissionsByUser(user); + // If the HTTP Current Context is unavailable (e.g. when called from within a SchedulerClient) GetCurrentPortalSettings() returns null and the + // PortalSettings are created/loaded for the portal (originally) assigned to the user. + var portalSettings = PortalController.Instance.GetCurrentPortalSettings() ?? new PortalSettings(portalId); - // Delete Tab Permissions - TabPermissionController.DeleteTabPermissionsByUser(user); - } + var canDelete = deleteAdmin || (user.UserID != portalSettings.AdministratorId); - 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 (canDelete) + { + // Delete Permissions + DeleteUserPermissions(user); + canDelete = MembershipProvider.Instance().DeleteUser(user); + } - if (userFolder != null) + if (canDelete) { - foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) + // Obtain PortalSettings from Current Context or from the users (original) portal if the HTTP Current Context is unavailable. + EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_DELETED); + if (notify && !user.IsSuperUser) { - 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, - }; + // send email notification to portal administrator that the user was removed from the portal + SendDeleteEmailNotifications(user, portalSettings); + } - userFolder.FolderPermissions.Add(folderPermission, true); - } + DataCache.ClearPortalUserCountCache(user.PortalID); + DataCache.ClearUserCache(user.PortalID, user.Username); + + // also clear current portal's cache if the user is a host user + if (portalSettings.PortalId != portalId) + { + DataCache.ClearPortalCache(portalSettings.PortalId, false); + DataCache.ClearUserCache(portalSettings.PortalId, user.Username); } - FolderPermissionController.SaveFolderPermissions((FolderInfo)userFolder); + // queue remove user contributions from search index + var document = new Services.Search.Entities.SearchDocumentToDelete + { + PortalId = portalId, + AuthorUserId = user.UserID, + SearchTypeId = Services.Search.Internals.SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId, + }; + + DataProvider.Instance().AddSearchDeletedItems(document); + + EventManager.Instance.OnUserDeleted(new UserEventArgs { User = user }); } + + FixMemberPortalId(user, portalId); + UpdateUser(portalId, GetUserById(portalId, user.UserID)); + return canDelete; } - private static void FixMemberPortalId(UserInfo user, int portalId) + /// ----------------------------------------------------------------------------- + /// + /// Deletes all Users for a Portal. + /// + /// + /// The Id of the Portal. + /// A flag that indicates whether an email notification should be sent. + /// A flag that indicates whether the Portal Administrator should be deleted. + /// ----------------------------------------------------------------------------- + public static void DeleteUsers(int portalId, bool notify, bool deleteAdmin) { - if (user != null) + var arrUsers = GetUsers(portalId); + for (int i = 0; i < arrUsers.Count; i++) { - user.PortalID = portalId; + var objUser = arrUsers[i] as UserInfo; + DeleteUser(ref objUser, notify, deleteAdmin); } } - private static UserInfo GetCurrentUserInternal() + /// ----------------------------------------------------------------------------- + /// + /// Generates a new random password (Length = Minimum Length + 4). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public static string GeneratePassword() { - UserInfo user; - if (HttpContext.Current == null) - { - if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) - { - return new UserInfo(); - } + return GeneratePassword(MembershipProviderConfig.MinPasswordLength + 4); + } - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) + /// ----------------------------------------------------------------------------- + /// + /// Generates a new random password. + /// + /// The length of password to generate. + /// A String. + /// ----------------------------------------------------------------------------- + public static string GeneratePassword(int length) + { + return MembershipProvider.Instance().GeneratePassword(length); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetCachedUser retrieves the User from the Cache, or fetches a fresh copy if + /// not in cache or if Cache settings not set to HeavyCaching. + /// + /// + /// + /// The Id of the Portal. + /// The username of the user being retrieved. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public static UserInfo GetCachedUser(int portalId, string username) + { + var masterPortalId = GetEffectivePortalId(portalId); + + // user is cached inside the MembershipProvider.Instance().GetUserByUserName method + var user = MembershipProvider.Instance().GetUserByUserName(masterPortalId, username); + FixMemberPortalId(user, portalId); + + if (user != null) + { + var lookUp = GetUserLookupDictionary(portalId); + using (lookUp.GetWriteLock()) { - user = GetCachedUser(portalSettings.PortalId, Thread.CurrentPrincipal.Identity.Name); - return user ?? new UserInfo(); + lookUp[user.UserID] = user.Username; } - - return new UserInfo(); } - user = (UserInfo)HttpContext.Current.Items["UserInfo"]; - return user ?? new UserInfo(); + return user; } - private static int GetEffectivePortalId(int portalId) + public static ArrayList GetDeletedUsers(int portalId) { - return PortalController.GetEffectivePortalId(portalId); + return MembershipProvider.Instance().GetDeletedUsers(GetEffectivePortalId(portalId)); } - private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) + /// ----------------------------------------------------------------------------- + /// + /// Gets a collection of Online Users. + /// + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + [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 static ArrayList GetOnlineUsers(int portalId) { - var portalId = (int)cacheItemArgs.ParamList[0]; - var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); - DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); - return portalUserCount; + return MembershipProvider.Instance().GetOnlineUsers(GetEffectivePortalId(portalId)); } - private static SharedDictionary GetUserLookupDictionary(int portalId) + /// ----------------------------------------------------------------------------- + /// + /// Gets the Current Password Information for the User. + /// + /// This method will only return the password if the memberProvider supports + /// and is using a password encryption method that supports decryption. + /// The user whose Password information we are retrieving. + /// The answer to the "user's" password Question. + /// + /// ----------------------------------------------------------------------------- + public static string GetPassword(ref UserInfo user, string passwordAnswer) { - 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); + if (MembershipProviderConfig.PasswordRetrievalEnabled) + { + user.Membership.Password = MembershipProvider.Instance().GetPassword(user, passwordAnswer); + } + else + { + // Throw a configuration exception as password retrieval is not enabled + throw new ConfigurationErrorsException("Password Retrieval is not enabled"); + } + + return user.Membership.Password; } - private static bool IsMemberOfPortalGroup(int portalId) + public static ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) { - return PortalController.IsMemberOfPortalGroup(portalId); + return MembershipProvider.Instance().GetUnAuthorizedUsers(GetEffectivePortalId(portalId), includeDeleted, superUsersOnly); } - private static void MergeUserProfileProperties(UserInfo userMergeFrom, UserInfo userMergeTo) + /// ----------------------------------------------------------------------------- + /// + /// GetUnAuthorizedUsers gets all the users of the portal, that are not authorized. + /// + /// + /// + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUnAuthorizedUsers(int portalId) { - foreach (ProfilePropertyDefinition property in userMergeFrom.Profile.ProfileProperties) - { - if (string.IsNullOrEmpty(userMergeTo.Profile.GetPropertyValue(property.PropertyName))) - { - userMergeTo.Profile.SetProfileProperty(property.PropertyName, property.PropertyValue); - } - } + return GetUnAuthorizedUsers(portalId, false, false); } - private static void MergeUserProperties(UserInfo userMergeFrom, UserInfo userMergeTo) + /// ----------------------------------------------------------------------------- + /// + /// 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 static UserInfo GetUserById(int portalId, int userId) { - if (string.IsNullOrEmpty(userMergeTo.DisplayName)) + // stop any sql calls for guest users + if (userId == Null.NullInteger) { - userMergeTo.DisplayName = userMergeFrom.DisplayName; + return null; } - if (string.IsNullOrEmpty(userMergeTo.Email)) + var lookUp = GetUserLookupDictionary(portalId); + + UserInfo user; + string userName; + bool userFound; + using (lookUp.GetReadLock()) { - userMergeTo.Email = userMergeFrom.Email; + userFound = lookUp.TryGetValue(userId, out userName); } - if (string.IsNullOrEmpty(userMergeTo.FirstName)) + if (userFound) { - userMergeTo.FirstName = userMergeFrom.FirstName; + user = GetCachedUser(portalId, userName); } - - if (string.IsNullOrEmpty(userMergeTo.LastName)) + else { - userMergeTo.LastName = userMergeFrom.LastName; + user = MembershipProvider.Instance().GetUser(GetEffectivePortalId(portalId), userId); + FixMemberPortalId(user, portalId); + if (user != null) + { + using (lookUp.GetWriteLock()) + { + lookUp[userId] = user.Username; + } + } } + + return user; } - private static void SendDeleteEmailNotifications(UserInfo user, PortalSettings portalSettings) - { - var message = new Message(); - message.FromUserID = portalSettings.AdministratorId; - message.ToUserID = portalSettings.AdministratorId; - message.Subject = Localization.GetSystemMessage( - 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); - } - - public UserInfo GetUserByDisplayname(int portalId, string displayName) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByUserName retrieves a User from the DataStore. + /// + /// + /// + /// The username of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public static UserInfo GetUserByName(string username) { - return MembershipProvider.Instance().GetUserByDisplayName(PortalController.GetEffectivePortalId(portalId), displayName); + return MembershipProvider.Instance().GetUserByUserName(-1, username); } - UserInfo IUserController.GetUserById(int portalId, int userId) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByUserName retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The username of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public static UserInfo GetUserByName(int portalId, string username) { - return GetUserById(portalId, userId); + return GetCachedUser(portalId, username); } - 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, - string propertyValues) + public static UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) { - return MembershipProvider.Instance().GetUsersAdvancedSearch(PortalController.GetEffectivePortalId(portalId), userId, filterUserId, filterRoleId, relationTypeId, - isAdmin, pageIndex, pageSize, sortColumn, - sortAscending, propertyNames, propertyValues); + portalId = GetEffectivePortalId(portalId); + return MembershipProvider.Instance().GetUserByVanityUrl(portalId, vanityUrl); } - public IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, bool sortAscending, - string propertyName, string propertyValue) + public static UserInfo GetUserByPasswordResetToken(int portalId, string resetToken) { - return MembershipProvider.Instance().GetUsersBasicSearch(PortalController.GetEffectivePortalId(portalId), pageIndex, pageSize, sortColumn, - sortAscending, propertyName, propertyValue); + portalId = GetEffectivePortalId(portalId); + return MembershipProvider.Instance().GetUserByPasswordResetToken(portalId, resetToken); } + /// ----------------------------------------------------------------------------- /// - /// Return User Profile Picture relative Url. + /// GetUserCountByPortal gets the number of users in the portal. /// - /// User Id. - /// Width in pixel. - /// Height in pixel. - /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal. - /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> - /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32). + /// /// - public string GetUserProfilePictureUrl(int userId, int width, int height) - { - var url = $"/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={width}&w={height}"; - - var childPortalAlias = GetChildPortalAlias(); - var cdv = GetProfilePictureCdv(userId); - - return childPortalAlias.StartsWith(Globals.ApplicationPath) - ? childPortalAlias + url + cdv - : Globals.ApplicationPath + childPortalAlias + url + cdv; - } - - public bool IsValidUserName(string userName) - { - // Validate username against bad characters; it must not start or end with space, - // must not contain control characters, and not contain special punctuations - // Printable ASCII: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" - // Fallback to default if there is no host setting configured - char[] unallowedAscii = HostController.Instance.GetString("UsernameUnallowedCharacters", Globals.USERNAME_UNALLOWED_ASCII).ToCharArray(); - return userName.Length >= 5 && - userName == userName.Trim() && - userName.All(ch => ch >= ' ') && - userName.IndexOfAny(unallowedAscii) < 0; - } - - public string GetUserProfilePictureUrl(int portalId, int userId, int width, int height) + /// The Id of the Portal. + /// The no of users. + /// ----------------------------------------------------------------------------- + public static int GetUserCountByPortal(int portalId) { - var url = $"/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={width}&w={height}"; - - var childPortalAlias = Globals.ResolveUrl(this.GetUserProfilePictureUrl(userId, width, height)); - var cdv = GetProfilePictureCdv(portalId, userId); - - return childPortalAlias.StartsWith(Globals.ApplicationPath) - ? childPortalAlias + url + cdv - : Globals.ApplicationPath + childPortalAlias + url + cdv; + portalId = GetEffectivePortalId(portalId); + var cacheKey = string.Format(DataCache.PortalUserCountCacheKey, portalId); + return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalUserCountCacheTimeOut, DataCache.PortalUserCountCachePriority, portalId), GetUserCountByPortalCallBack); } /// ----------------------------------------------------------------------------- /// - /// Update all the Users Display Names. + /// Retruns a String corresponding to the Registration Status of the User. /// + /// The AUserCreateStatus. + /// A String. /// ----------------------------------------------------------------------------- - public void UpdateDisplayNames() + public static string GetUserCreateStatus(UserCreateStatus userRegistrationStatus) { - int portalId = GetEffectivePortalId(this.PortalId); - - var arrUsers = GetUsers(this.PortalId); - foreach (UserInfo objUser in arrUsers) + switch (userRegistrationStatus) { - objUser.UpdateDisplayName(this.DisplayFormat); - UpdateUser(portalId, objUser); + case UserCreateStatus.DuplicateEmail: + return Localization.GetString("UserEmailExists"); + case UserCreateStatus.InvalidAnswer: + return Localization.GetString("InvalidAnswer"); + case UserCreateStatus.InvalidEmail: + return Localization.GetString("InvalidEmail"); + case UserCreateStatus.InvalidPassword: + string strInvalidPassword = Localization.GetString("InvalidPassword"); + strInvalidPassword = strInvalidPassword.Replace("[PasswordLength]", MembershipProviderConfig.MinPasswordLength.ToString()); + strInvalidPassword = strInvalidPassword.Replace("[NoneAlphabet]", MembershipProviderConfig.MinNonAlphanumericCharacters.ToString()); + return strInvalidPassword; + case UserCreateStatus.PasswordMismatch: + return Localization.GetString("PasswordMismatch"); + case UserCreateStatus.InvalidQuestion: + return Localization.GetString("InvalidQuestion"); + case UserCreateStatus.InvalidUserName: + return Localization.GetString("InvalidUserName"); + case UserCreateStatus.InvalidDisplayName: + return Localization.GetString("InvalidDisplayName"); + case UserCreateStatus.DuplicateDisplayName: + return Localization.GetString("DuplicateDisplayName"); + case UserCreateStatus.UserRejected: + return Localization.GetString("UserRejected"); + case UserCreateStatus.DuplicateUserName: + case UserCreateStatus.UserAlreadyRegistered: + case UserCreateStatus.UsernameAlreadyExists: + return Localization.GetString("UserNameExists"); + case UserCreateStatus.BannedPasswordUsed: + return Localization.GetString("BannedPasswordUsed"); + case UserCreateStatus.ProviderError: + case UserCreateStatus.DuplicateProviderUserKey: + case UserCreateStatus.InvalidProviderUserKey: + return Localization.GetString("RegError"); + case UserCreateStatus.InvalidFirstName: + return Localization.GetString("InvalidFirstName"); + case UserCreateStatus.InvalidLastName: + return Localization.GetString("InvalidLastName"); + default: + throw new ArgumentException("Unknown UserCreateStatus value encountered", "userRegistrationStatus"); } } - private static string GetChildPortalAlias() + /// ----------------------------------------------------------------------------- + /// + /// Gets the Membership Information for the User. + /// + /// + /// The user whose Membership information we are retrieving. + /// ----------------------------------------------------------------------------- + public static void GetUserMembership(UserInfo user) { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - var currentAlias = settings.PortalAlias.HTTPAlias; - var index = currentAlias.IndexOf('/'); - var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; - return childPortalAlias; + int portalId = user.PortalID; + user.PortalID = GetEffectivePortalId(portalId); + MembershipProvider.Instance().GetUserMembership(ref user); + FixMemberPortalId(user, portalId); } - private static string GetProfilePictureCdv(int userId) + /// ----------------------------------------------------------------------------- + /// + /// Gets the Default Settings for the Module. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + public static Hashtable GetDefaultUserSettings() { - var settings = PortalController.Instance.GetCurrentPortalSettings(); - var userInfo = GetUserById(settings.PortalId, userId); - if (userInfo?.Profile == null) - { - return string.Empty; - } - - var cdv = string.Empty; - var photoProperty = userInfo.Profile.GetProperty("Photo"); + var portalId = -1; + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - int photoFileId; - if (int.TryParse(photoProperty?.PropertyValue, out photoFileId)) + if (portalSettings != null) { - var photoFile = FileManager.Instance.GetFile(photoFileId); - if (photoFile != null) - { - cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; - } + portalId = portalSettings.PortalId; } - return cdv; + return GetUserSettings(portalId, new Hashtable()); } - private static string GetProfilePictureCdv(int portalId, int userId) + /// ----------------------------------------------------------------------------- + /// + /// GetUserSettings retrieves the UserSettings from the User. + /// + /// + /// + /// The Id of the Portal. + /// The Settings Hashtable. + /// ----------------------------------------------------------------------------- + public static Hashtable GetUserSettings(int portalId) { - var userInfo = GetUserById(portalId, userId); - if (userInfo?.Profile == null) + var settings = GetDefaultUserSettings(); + var masterPortalId = GetEffectivePortalId(portalId); + Dictionary settingsDictionary = (portalId == Null.NullInteger) + ? HostController.Instance.GetSettingsDictionary() + : PortalController.Instance.GetPortalSettings(masterPortalId); + Dictionary currentPortalSettings = null; + if (portalId != Null.NullInteger && masterPortalId != portalId) { - return string.Empty; + currentPortalSettings = PortalController.Instance.GetPortalSettings(portalId); } - var cdv = string.Empty; - var photoProperty = userInfo.Profile.GetProperty("Photo"); - - int photoFileId; - if (int.TryParse(photoProperty?.PropertyValue, out photoFileId)) + if (settingsDictionary != null) { - var photoFile = FileManager.Instance.GetFile(photoFileId); - if (photoFile != null) + foreach (KeyValuePair kvp in settingsDictionary) { - cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; - } - } - - return cdv; - } - - /// - /// ApproveUser removes the Unverified Users role from the user and adds the auto assigned roles. - /// - /// The user to update. - public static void ApproveUser(UserInfo user) - { - Requires.NotNull("user", user); + int index = kvp.Key.IndexOf("_"); + if (index > 0) + { + // Get the prefix + string prefix = kvp.Key.Substring(0, index + 1); + switch (prefix) + { + case "Column_": + case "Display_": + case "Profile_": + case "Records_": + case "Redirect_": + case "Registration_": + case "Security_": + switch (kvp.Key) + { + case "Display_Mode": + settings[kvp.Key] = (DisplayMode)Convert.ToInt32(kvp.Value); + break; + case "Profile_DefaultVisibility": + settings[kvp.Key] = (UserVisibilityMode)Convert.ToInt32(kvp.Value); + break; + case "Security_UsersControl": + settings[kvp.Key] = (UsersControl)Convert.ToInt32(kvp.Value); + break; + default: + // update value or add any new values + settings[kvp.Key] = kvp.Value; + break; + } - var settings = PortalController.Instance.GetCurrentPortalSettings(); - var role = RoleController.Instance.GetRole(settings.PortalId, r => r.RoleName == "Unverified Users"); + break; + } + } + } + } - RoleController.DeleteUserRole(user, role, settings, false); + if (currentPortalSettings != null) + { + foreach (var kvp in currentPortalSettings.Where(kvp => kvp.Key.StartsWith("Redirect_"))) + { + settings[kvp.Key] = kvp.Value; + } + } - AutoAssignUsersToRoles(user, settings.PortalId); + return settings; } + /// ----------------------------------------------------------------------------- /// - /// User has agreed to terms and conditions. The time is recorded at the same time in SQL. + /// GetUsers gets all the users of the portal. /// - /// The user that agreed. - public static void UserAgreedToTerms(UserInfo user) + /// + /// + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsers(int portalId) { - Requires.NotNull("user", user); - MembershipProvider.Instance().UserAgreedToTerms(user); + return GetUsers(false, false, portalId); } + /// ----------------------------------------------------------------------------- /// - /// When called all users in the portal will need to agree to terms and conditions again. + /// GetUsers gets all the users of the portal. /// - /// The portal for which to reset. - public static void ResetTermsAgreement(int portalId) + /// + /// + /// The Id of the Portal. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsers(bool includeDeleted, bool superUsersOnly, int portalId) { - Requires.NotNull("portalId", portalId); - MembershipProvider.Instance().ResetTermsAgreement(portalId); + var totalrecords = -1; + return GetUsers(portalId, -1, -1, ref totalrecords, includeDeleted, superUsersOnly); } + /// ----------------------------------------------------------------------------- /// - /// A user may request that their account be removed. This sets a flag on the user portal - /// so further processing may occur manually by the site admins. + /// GetUsers gets all the users of the portal, by page. /// - /// The user that desires to be removed. - public static void UserRequestsRemoval(UserInfo user, bool remove) + /// + /// + /// The Id of the Portal. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords) { - Requires.NotNull("user", user); - MembershipProvider.Instance().UserRequestsRemoval(user, remove); + return GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// ChangePassword attempts to change the users password. + /// GetUsers gets all the users of the portal, by page. /// /// /// - /// The user to update. - /// The old password. - /// The new password. - /// A Boolean indicating success or failure. + /// The Id of the Portal. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public static bool ChangePassword(UserInfo user, string oldPassword, string newPassword) + public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - bool passwordChanged; - - // Although we would hope that the caller has already validated the password, - // Validate the new Password - if (ValidatePassword(newPassword)) - { - passwordChanged = MembershipProvider.Instance().ChangePassword(user, oldPassword, newPassword); - - if (passwordChanged) - { - // Update User - user.Membership.UpdatePassword = false; - UpdateUser(user.PortalID, user); - } - } - else - { - throw new Exception("Invalid Password"); - } - - return passwordChanged; + return MembershipProvider.Instance().GetUsers(GetEffectivePortalId(portalId), pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); } + /// ----------------------------------------------------------------------------- /// - /// overload will validate the token and if valid change the password - /// it does not require an old password as it supports hashed passwords. + /// GetUsersByEmail gets all the users of the portal whose email matches a provided + /// filter expression. /// - /// The new password. - /// /// The reset token, typically supplied through a password reset email. - /// A Boolean indicating success or failure. - public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string resetToken) + /// + /// + /// The Id of the Portal. + /// The email address to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords) { - bool passwordChanged; - - Guid resetTokenGuid = new Guid(resetToken); - - var user = GetUserByName(portalid, username); - - // if user does not exist return false - if (user == null) - { - return false; - } - - // check if the token supplied is the same as the users and is still valid - if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) - { - return false; - } - - var m = new MembershipPasswordController(); - if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword)) - { - return false; - } - - // Although we would hope that the caller has already validated the password, - // Validate the new Password - if (ValidatePassword(newPassword)) - { - passwordChanged = MembershipProvider.Instance().ResetAndChangePassword(user, newPassword); - - // update reset token values to ensure token is 1-time use - user.PasswordResetExpiration = DateTime.MinValue; - user.PasswordResetToken = Guid.NewGuid(); + return GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); + } - if (passwordChanged) - { - // Update User - user.Membership.UpdatePassword = false; - UpdateUser(user.PortalID, user); - } - } - else + /// ----------------------------------------------------------------------------- + /// + /// GetUserByEmail gets one single user matching the email address provided + /// This will only be useful in portals without duplicate email addresses + /// filter expression. + /// + /// + /// + /// The Id of the Portal. + /// The email address to use to find a match. + /// A single user object or null if no user found. + /// ----------------------------------------------------------------------------- + public static UserInfo GetUserByEmail(int portalId, string emailToMatch) + { + int uid = DataProvider.Instance().GetSingleUserByEmail(portalId, emailToMatch); + if (uid > -1) { - throw new Exception("Invalid Password"); + return GetUserById(portalId, uid); } - return passwordChanged; + return null; } + /// ----------------------------------------------------------------------------- /// - /// overload will validate the token and if valid change the password - /// it does not require an old password as it supports hashed passwords - /// errorMessage will define why reset failed. + /// GetUsersByEmail gets all the users of the portal whose email matches a provided + /// filter expression. /// - /// The new password. - /// The reset token, typically supplied through a password reset email. - /// A Boolean indicating success or failure. - public static bool ChangePasswordByToken(int portalid, string username, string newPassword, string answer, string resetToken, out string errorMessage) + /// + /// + /// The Id of the Portal. + /// The email address to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - bool passwordChanged; - errorMessage = Null.NullString; - Guid resetTokenGuid = new Guid(resetToken); - - var user = GetUserByName(portalid, username); - - // if user does not exist return false - if (user == null) - { - errorMessage = Localization.GetString("PasswordResetFailed_UserUndefined"); - return false; - } - - // check if the token supplied is the same as the users and is still valid - if (user.PasswordResetToken != resetTokenGuid || user.PasswordResetExpiration < DateTime.Now) - { - errorMessage = Localization.GetString("PasswordResetFailed_ResetLinkExpired"); - return false; - } - - var m = new MembershipPasswordController(); - if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, false)) - { - errorMessage = Localization.GetString("PasswordResetFailed_PasswordInHistory"); - return false; - } - - // Although we would hope that the caller has already validated the password, - // Validate the new Password - if (ValidatePassword(newPassword)) - { - try - { - passwordChanged = MembershipProvider.Instance().ResetAndChangePassword(user, newPassword, answer); - - if (passwordChanged) - { - // update reset token values to ensure token is 1-time use - user.PasswordResetExpiration = DateTime.MinValue; - user.PasswordResetToken = Guid.NewGuid(); - - // Update User - user.Membership.UpdatePassword = false; - UpdateUser(user.PortalID, user); - - m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword, true); // add the password into history. - } - else - { - errorMessage = Localization.GetString("PasswordResetFailed_WrongAnswer"); - } - } - catch (Exception) - { - passwordChanged = false; - errorMessage = Localization.GetString("PasswordResetFailed_WrongAnswer"); - } - } - else - { - throw new Exception("Invalid Password"); - } - - return passwordChanged; - } + return MembershipProvider.Instance().GetUsersByEmail(GetEffectivePortalId(portalId), emailToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + } /// ----------------------------------------------------------------------------- /// - /// ChangePasswordQuestionAndAnswer attempts to change the users password Question - /// and PasswordAnswer. + /// GetUsersByProfileProperty gets all the users of the portal whose profile matches + /// the profile property pased as a parameter. /// /// /// - /// The user to update. - /// The password. - /// The new password question. - /// The new password answer. - /// A Boolean indicating success or failure. + /// The Id of the Portal. + /// The name of the property being matched. + /// The value of the property being matched. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public static bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, string passwordAnswer) + public static ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords) { - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_UPDATED); - return MembershipProvider.Instance().ChangePasswordQuestionAndAnswer(user, password, passwordQuestion, passwordAnswer); + return GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, ref totalRecords, false, false); } + /// ----------------------------------------------------------------------------- /// - /// update username in the system - /// works around membershipprovider limitation. + /// GetUsersByProfileProperty gets all the users of the portal whose profile matches + /// the profile property pased as a parameter. /// - /// user id. - /// new one. - public static void ChangeUsername(int userId, string newUsername) - { - MembershipProvider.Instance().ChangeUsername(userId, newUsername); - } - - public static void CheckInsecurePassword(string username, string password, ref UserLoginStatus loginStatus) + /// + /// + /// The Id of the Portal. + /// The name of the property being matched. + /// The value of the property being matched. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - if (username == "admin" && (password == "admin" || password == "dnnadmin")) - { - loginStatus = UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; - } - - if (username == "host" && (password == "host" || password == "dnnhost")) - { - loginStatus = UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD; - } + return MembershipProvider.Instance().GetUsersByProfileProperty(GetEffectivePortalId(portalId), propertyName, propertyValue, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); } + /// ----------------------------------------------------------------------------- /// - /// Copys a user to a different portal. + /// GetUsersByUserName gets all the users of the portal whose username matches a provided + /// filter expression. /// - /// The user to copy. - /// The destination portal. - /// A flag that indicates whether to merge the original user. - public static void CopyUserToPortal(UserInfo user, PortalInfo destinationPortal, bool mergeUser) + /// + /// + /// The Id of the Portal. + /// The username to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords) { - var targetUser = GetUserById(destinationPortal.PortalID, user.UserID); - if (targetUser == null) - { - AddUserPortal(destinationPortal.PortalID, user.UserID); - - if (!user.IsSuperUser) - { - AutoAssignUsersToRoles(user, destinationPortal.PortalID); - } - - targetUser = GetUserById(destinationPortal.PortalID, user.UserID); - MergeUserProperties(user, targetUser); - MergeUserProfileProperties(user, targetUser); - } - else - { - targetUser.PortalID = destinationPortal.PortalID; - - if (mergeUser) - { - MergeUserProperties(user, targetUser); - MergeUserProfileProperties(user, targetUser); - } - } - - UpdateUser(targetUser.PortalID, targetUser); + return GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// Creates a new User in the Data Store. + /// GetUsersByUserName gets all the users of the portal whose username matches a provided + /// filter expression. /// - /// - /// The userInfo object to persist to the Database. - /// The Created status ot the User. + /// + /// + /// The Id of the Portal. + /// The username to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public static UserCreateStatus CreateUser(ref UserInfo user) + public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - return CreateUser(ref user, false); + return MembershipProvider.Instance().GetUsersByUserName(GetEffectivePortalId(portalId), userNameToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); } /// ----------------------------------------------------------------------------- /// - /// Creates a new User in the Data Store. + /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided + /// filter expression. /// - /// - /// The userInfo object to persist to the Database. - /// The sendEmailNotification flag defines whether registration email will be sent to user. - /// The Created status ot the User. + /// + /// + /// The Id of the Portal. + /// The display name to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include Deleted Users. + /// Only get super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public static UserCreateStatus CreateUser(ref UserInfo user, bool sendEmailNotification) + public static ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - int portalId = user.PortalID; - user.PortalID = GetEffectivePortalId(portalId); + return MembershipProvider.Instance().GetUsersByDisplayName(GetEffectivePortalId(portalId), nameToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + } - // ensure valid GUID exists (covers case where password is randomly generated - has 24 hr validity as per other Admin user steps - var passwordExpiry = DateTime.Now.AddMinutes(1440); - var passwordGuid = Guid.NewGuid(); - user.PasswordResetExpiration = passwordExpiry; - user.PasswordResetToken = passwordGuid; + /// + /// Move a user to a different portal. + /// + /// The user to move. + /// The destination portal. + /// A flag that indicates whether to merge the original user. + public static void MoveUserToPortal(UserInfo user, PortalInfo portal, bool mergeUser) + { + CopyUserToPortal(user, portal, mergeUser); + RemoveUser(user); + } - // Create the User - var createStatus = MembershipProvider.Instance().CreateUser(ref user); + /// + /// Permanently deletes all users marked as deleted from a portal. It will delete the membership + /// user as well if the user has no other portals. + /// + /// Portal ID to get the deleted users for. + public static void RemoveDeletedUsers(int portalId) + { + var arrUsers = GetDeletedUsers(portalId); - if (createStatus == UserCreateStatus.Success) + foreach (UserInfo objUser in arrUsers) { - // reapply guid/expiry (cleared when user is created) - user.PasswordResetExpiration = passwordExpiry; - user.PasswordResetToken = passwordGuid; - UpdateUser(user.PortalID, user); - EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), GetCurrentUserInternal().UserID, string.Empty, EventLogController.EventLogType.USER_CREATED); - CachingProvider.Instance().Remove(string.Format(DataCache.PortalUserCountCacheKey, portalId)); - if (!user.IsSuperUser) + if (objUser.IsDeleted) { - // autoassign user to portal roles - AutoAssignUsersToRoles(user, portalId); + RemoveUser(objUser); } - - EventManager.Instance.OnUserCreated(new UserEventArgs { User = user, SendNotification = sendEmailNotification }); } - - // Reset PortalId - FixMemberPortalId(user, portalId); - return createStatus; } - /// ----------------------------------------------------------------------------- /// - /// Deletes all Unauthorized Users for a Portal. + /// Permanently delete a user and the associated user folder on disk. + /// This also deletes the membership user if the user is + /// not a member of any other portal. /// - /// - /// The Id of the Portal. - /// ----------------------------------------------------------------------------- - public static void DeleteUnauthorizedUsers(int portalId) - { - // DNN-6924 for superusers call GetUsers(includeDeleted, superUsersOnly, portalId) - var arrUsers = (portalId == -1) ? GetUsers(true, true, portalId) : GetUnAuthorizedUsers(portalId); - for (int i = 0; i < arrUsers.Count; i++) - { - var user = arrUsers[i] as UserInfo; - if (user != null) - { - if (user.Membership.Approved == false || user.Membership.LastLoginDate == Null.NullDate) - { - DeleteUser(ref user, true, false); - } - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Deletes an existing User from the Data Store. - /// - /// - /// The userInfo object to delete from the Database. - /// A flag that indicates whether an email notification should be sent. - /// A flag that indicates whether the Portal Administrator should be deleted. - /// A Boolean value that indicates whether the User was successfully deleted. - /// ----------------------------------------------------------------------------- - public static bool DeleteUser(ref UserInfo user, bool notify, bool deleteAdmin) + /// The user to delete. + /// + public static bool RemoveUser(UserInfo user) { int portalId = user.PortalID; user.PortalID = GetEffectivePortalId(portalId); - // If the HTTP Current Context is unavailable (e.g. when called from within a SchedulerClient) GetCurrentPortalSettings() returns null and the - // PortalSettings are created/loaded for the portal (originally) assigned to the user. - var portalSettings = PortalController.Instance.GetCurrentPortalSettings() ?? new PortalSettings(portalId); - - var canDelete = deleteAdmin || (user.UserID != portalSettings.AdministratorId); - - if (canDelete) - { - // Delete Permissions - DeleteUserPermissions(user); - canDelete = MembershipProvider.Instance().DeleteUser(user); - } + // Remove the User + var retValue = MembershipProvider.Instance().RemoveUser(user); - if (canDelete) + if (retValue) { - // Obtain PortalSettings from Current Context or from the users (original) portal if the HTTP Current Context is unavailable. - EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_DELETED); - if (notify && !user.IsSuperUser) - { - // send email notification to portal administrator that the user was removed from the portal - SendDeleteEmailNotifications(user, portalSettings); - } - - DataCache.ClearPortalUserCountCache(user.PortalID); - DataCache.ClearUserCache(user.PortalID, user.Username); + // Obtain PortalSettings from Current Context + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - // also clear current portal's cache if the user is a host user - if (portalSettings.PortalId != portalId) - { - DataCache.ClearPortalCache(portalSettings.PortalId, false); - DataCache.ClearUserCache(portalSettings.PortalId, user.Username); - } + // Log event + EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_REMOVED); - // queue remove user contributions from search index - var document = new Services.Search.Entities.SearchDocumentToDelete - { - PortalId = portalId, - AuthorUserId = user.UserID, - SearchTypeId = Services.Search.Internals.SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId, - }; + // Delete userFolder - DNN-3787 + DeleteUserFolder(user); - DataProvider.Instance().AddSearchDeletedItems(document); + DataCache.ClearPortalCache(portalId, false); + DataCache.ClearUserCache(portalId, user.Username); - EventManager.Instance.OnUserDeleted(new UserEventArgs { User = user }); + EventManager.Instance.OnUserRemoved(new UserEventArgs { User = user }); } + // Reset PortalId FixMemberPortalId(user, portalId); - UpdateUser(portalId, GetUserById(portalId, user.UserID)); - return canDelete; + + return retValue; } - /// ----------------------------------------------------------------------------- /// - /// Deletes all Users for a Portal. + /// reset and change password + /// used by admin/host users who do not need to supply an "old" password. /// - /// - /// The Id of the Portal. - /// A flag that indicates whether an email notification should be sent. - /// A flag that indicates whether the Portal Administrator should be deleted. - /// ----------------------------------------------------------------------------- - public static void DeleteUsers(int portalId, bool notify, bool deleteAdmin) + /// user being changed. + /// new password. + /// + public static bool ResetAndChangePassword(UserInfo user, string newPassword) { - var arrUsers = GetUsers(portalId); - for (int i = 0; i < arrUsers.Count; i++) + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (GetCurrentUserInternal().IsInRole(portalSettings.AdministratorRoleName)) { - var objUser = arrUsers[i] as UserInfo; - DeleteUser(ref objUser, notify, deleteAdmin); + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); } - } - - /// ----------------------------------------------------------------------------- - /// - /// Generates a new random password (Length = Minimum Length + 4). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public static string GeneratePassword() - { - return GeneratePassword(MembershipProviderConfig.MinPasswordLength + 4); - } - /// ----------------------------------------------------------------------------- - /// - /// Generates a new random password. - /// - /// The length of password to generate. - /// A String. - /// ----------------------------------------------------------------------------- - public static string GeneratePassword(int length) - { - return MembershipProvider.Instance().GeneratePassword(length); + return false; } - /// ----------------------------------------------------------------------------- - /// - /// GetCachedUser retrieves the User from the Cache, or fetches a fresh copy if - /// not in cache or if Cache settings not set to HeavyCaching. - /// - /// - /// - /// The Id of the Portal. - /// The username of the user being retrieved. - /// The User as a UserInfo object. - /// ----------------------------------------------------------------------------- - public static UserInfo GetCachedUser(int portalId, string username) + public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) { - var masterPortalId = GetEffectivePortalId(portalId); - - // user is cached inside the MembershipProvider.Instance().GetUserByUserName method - var user = MembershipProvider.Instance().GetUserByUserName(masterPortalId, username); - FixMemberPortalId(user, portalId); - - if (user != null) + if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) { - var lookUp = GetUserLookupDictionary(portalId); - using (lookUp.GetWriteLock()) - { - lookUp[user.UserID] = user.Username; - } + string resetPassword = ResetPassword(user, string.Empty); + return ChangePassword(user, resetPassword, newPassword); } - return user; - } - - public static ArrayList GetDeletedUsers(int portalId) - { - return MembershipProvider.Instance().GetDeletedUsers(GetEffectivePortalId(portalId)); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a collection of Online Users. - /// - /// The Id of the Portal. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - [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 static ArrayList GetOnlineUsers(int portalId) - { - return MembershipProvider.Instance().GetOnlineUsers(GetEffectivePortalId(portalId)); + return false; } /// ----------------------------------------------------------------------------- /// - /// Gets the Current Password Information for the User. + /// Resets the password for the specified user. /// - /// This method will only return the password if the memberProvider supports - /// and is using a password encryption method that supports decryption. - /// The user whose Password information we are retrieving. + /// Resets the user's password. + /// The user whose Password information we are resetting. /// The answer to the "user's" password Question. /// /// ----------------------------------------------------------------------------- - public static string GetPassword(ref UserInfo user, string passwordAnswer) + public static string ResetPassword(UserInfo user, string passwordAnswer) { - if (MembershipProviderConfig.PasswordRetrievalEnabled) + if (MembershipProviderConfig.PasswordResetEnabled) { - user.Membership.Password = MembershipProvider.Instance().GetPassword(user, passwordAnswer); + user.Membership.Password = MembershipProvider.Instance().ResetPassword(user, passwordAnswer); } else { - // Throw a configuration exception as password retrieval is not enabled - throw new ConfigurationErrorsException("Password Retrieval is not enabled"); + // Throw a configuration exception as password reset is not enabled + throw new ConfigurationErrorsException("Password Reset is not enabled"); } return user.Membership.Password; } - public static ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) - { - return MembershipProvider.Instance().GetUnAuthorizedUsers(GetEffectivePortalId(portalId), includeDeleted, superUsersOnly); - } - - /// ----------------------------------------------------------------------------- - /// - /// GetUnAuthorizedUsers gets all the users of the portal, that are not authorized. - /// - /// - /// - /// The Id of the Portal. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUnAuthorizedUsers(int portalId) + public static void ResetPasswordToken(UserInfo user) { - return GetUnAuthorizedUsers(portalId, false, false); + ResetPasswordToken(user, false); } - /// ----------------------------------------------------------------------------- - /// - /// 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 static UserInfo GetUserById(int portalId, int userId) + public static bool ResetPasswordToken(UserInfo user, bool sendEmail) { - // stop any sql calls for guest users - if (userId == Null.NullInteger) + var settings = new MembershipPasswordSettings(user.PortalID); + var expiry = DateTime.Now.AddMinutes(settings.ResetLinkValidity); + if (user.PasswordResetExpiration < DateTime.Now) { - return null; + user.PasswordResetExpiration = expiry; + user.PasswordResetToken = Guid.NewGuid(); + UpdateUser(user.PortalID, user); } - - var lookUp = GetUserLookupDictionary(portalId); - - UserInfo user; - string userName; - bool userFound; - using (lookUp.GetReadLock()) + else if (user.PasswordResetExpiration > expiry) { - userFound = lookUp.TryGetValue(userId, out userName); + user.PasswordResetExpiration = expiry; + UpdateUser(user.PortalID, user); } - if (userFound) + if (sendEmail) { - user = GetCachedUser(portalId, userName); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return Mail.SendMail(user, MessageType.PasswordReminder, portalSettings) == string.Empty; } - else - { - user = MembershipProvider.Instance().GetUser(GetEffectivePortalId(portalId), userId); - FixMemberPortalId(user, portalId); - if (user != null) - { - using (lookUp.GetWriteLock()) - { - lookUp[userId] = user.Username; - } - } + + return true; + } + + public static void ResetPasswordToken(UserInfo user, int minutesValid) + { + user.PasswordResetExpiration = DateTime.Now.AddMinutes(minutesValid); + user.PasswordResetToken = Guid.NewGuid(); + UpdateUser(user.PortalID, user); + } + + public static bool RestoreUser(ref UserInfo user) + { + int portalId = user.PortalID; + user.PortalID = GetEffectivePortalId(portalId); + + // Restore the User + var retValue = MembershipProvider.Instance().RestoreUser(user); + + if (retValue) + { + // restore user permissions + RestoreUserPermissions(user); + + // Obtain PortalSettings from Current Context + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + + // Log event + EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_RESTORED); + + DataCache.ClearPortalUserCountCache(user.PortalID); + DataCache.ClearUserCache(user.PortalID, user.Username); } - return user; + // Reset PortalId + FixMemberPortalId(user, portalId); + UpdateUser(portalId, GetUserById(portalId, user.UserID)); + return retValue; + } + + public static string SettingsKey(int portalId) + { + return "UserSettings|" + portalId; } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore. + /// Unlocks the User's Account. /// - /// - /// - /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object. + /// + /// The user whose account is being Unlocked. + /// /// ----------------------------------------------------------------------------- - public static UserInfo GetUserByName(string username) + public static bool UnLockUser(UserInfo user) { - return MembershipProvider.Instance().GetUserByUserName(-1, username); + int portalId = user.PortalID; + user.PortalID = GetEffectivePortalId(portalId); + + // Unlock the User + var retValue = MembershipProvider.Instance().UnLockUser(user); + DataCache.ClearUserCache(portalId, user.Username); + UpdateUser(portalId, GetUserById(portalId, user.UserID)); + return retValue; } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore. + /// Updates a User. /// + /// The Id of the Portal. + /// The use to update. /// /// - /// The Id of the Portal. - /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- - public static UserInfo GetUserByName(int portalId, string username) - { - return GetCachedUser(portalId, username); - } - - public static UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) - { - portalId = GetEffectivePortalId(portalId); - return MembershipProvider.Instance().GetUserByVanityUrl(portalId, vanityUrl); - } - - public static UserInfo GetUserByPasswordResetToken(int portalId, string resetToken) + public static void UpdateUser(int portalId, UserInfo user) { - portalId = GetEffectivePortalId(portalId); - return MembershipProvider.Instance().GetUserByPasswordResetToken(portalId, resetToken); + UpdateUser(portalId, user, true); } /// ----------------------------------------------------------------------------- /// - /// GetUserCountByPortal gets the number of users in the portal. + /// 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. /// /// - /// The Id of the Portal. - /// The no of users. - /// ----------------------------------------------------------------------------- - public static int GetUserCountByPortal(int portalId) + public static void UpdateUser(int portalId, UserInfo user, bool loggedAction) { - portalId = GetEffectivePortalId(portalId); - var cacheKey = string.Format(DataCache.PortalUserCountCacheKey, portalId); - return CBO.GetCachedObject(new CacheItemArgs(cacheKey, DataCache.PortalUserCountCacheTimeOut, DataCache.PortalUserCountCachePriority, portalId), GetUserCountByPortalCallBack); + UpdateUser(portalId, user, loggedAction, true); } /// ----------------------------------------------------------------------------- /// - /// Retruns a String corresponding to the Registration Status of the User. + /// updates a user. /// - /// The AUserCreateStatus. - /// A String. - /// ----------------------------------------------------------------------------- - public static string GetUserCreateStatus(UserCreateStatus userRegistrationStatus) + /// 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). + /// + /// + public static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification) { - switch (userRegistrationStatus) - { - case UserCreateStatus.DuplicateEmail: - return Localization.GetString("UserEmailExists"); - case UserCreateStatus.InvalidAnswer: - return Localization.GetString("InvalidAnswer"); - case UserCreateStatus.InvalidEmail: - return Localization.GetString("InvalidEmail"); - case UserCreateStatus.InvalidPassword: - string strInvalidPassword = Localization.GetString("InvalidPassword"); - strInvalidPassword = strInvalidPassword.Replace("[PasswordLength]", MembershipProviderConfig.MinPasswordLength.ToString()); - strInvalidPassword = strInvalidPassword.Replace("[NoneAlphabet]", MembershipProviderConfig.MinNonAlphanumericCharacters.ToString()); - return strInvalidPassword; - case UserCreateStatus.PasswordMismatch: - return Localization.GetString("PasswordMismatch"); - case UserCreateStatus.InvalidQuestion: - return Localization.GetString("InvalidQuestion"); - case UserCreateStatus.InvalidUserName: - return Localization.GetString("InvalidUserName"); - case UserCreateStatus.InvalidDisplayName: - return Localization.GetString("InvalidDisplayName"); - case UserCreateStatus.DuplicateDisplayName: - return Localization.GetString("DuplicateDisplayName"); - case UserCreateStatus.UserRejected: - return Localization.GetString("UserRejected"); - case UserCreateStatus.DuplicateUserName: - case UserCreateStatus.UserAlreadyRegistered: - case UserCreateStatus.UsernameAlreadyExists: - return Localization.GetString("UserNameExists"); - case UserCreateStatus.BannedPasswordUsed: - return Localization.GetString("BannedPasswordUsed"); - case UserCreateStatus.ProviderError: - case UserCreateStatus.DuplicateProviderUserKey: - case UserCreateStatus.InvalidProviderUserKey: - return Localization.GetString("RegError"); - case UserCreateStatus.InvalidFirstName: - return Localization.GetString("InvalidFirstName"); - case UserCreateStatus.InvalidLastName: - return Localization.GetString("InvalidLastName"); - default: - throw new ArgumentException("Unknown UserCreateStatus value encountered", "userRegistrationStatus"); - } + UpdateUser(portalId, user, loggedAction, sendNotification, true); } /// ----------------------------------------------------------------------------- /// - /// Gets the Membership Information for the User. + /// Validates a User's credentials against the Data Store, and sets the Forms Authentication + /// Ticket. /// - /// - /// The user whose Membership information we are retrieving. + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the + /// Login attempt. This value is returned by reference. + /// A flag that indicates whether the login credentials + /// should be persisted. + /// The UserInfo object representing a successful login. /// ----------------------------------------------------------------------------- - public static void GetUserMembership(UserInfo user) + public static UserInfo UserLogin(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus, bool createPersistentCookie) { - int portalId = user.PortalID; - user.PortalID = GetEffectivePortalId(portalId); - MembershipProvider.Instance().GetUserMembership(ref user); - FixMemberPortalId(user, portalId); + portalId = GetEffectivePortalId(portalId); + + loginStatus = UserLoginStatus.LOGIN_FAILURE; + + // Validate the user + var objUser = ValidateUser(portalId, username, password, verificationCode, portalName, ip, ref loginStatus); + if (objUser != null) + { + // Call UserLogin overload + UserLogin(portalId, objUser, portalName, ip, createPersistentCookie); + } + else + { + AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); + } + + // return the User object + return objUser; } /// ----------------------------------------------------------------------------- /// - /// Gets the Default Settings for the Module. + /// Logs a Validated User in. /// - /// - /// - /// + /// The Id of the Portal the user belongs to. + /// The validated User. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A flag that indicates whether the login credentials should be persisted. /// ----------------------------------------------------------------------------- - public static Hashtable GetDefaultUserSettings() + public static void UserLogin(int portalId, UserInfo user, string portalName, string ip, bool createPersistentCookie) { - var portalId = -1; - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + portalId = GetEffectivePortalId(portalId); - if (portalSettings != null) + AddEventLog(portalId, user.Username, user.UserID, portalName, ip, user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS); + + if (user.LastIPAddress != ip) { - portalId = portalSettings.PortalId; + // Update User in Database with Last IP used + user.LastIPAddress = ip; + DataProvider.Instance().UpdateUserLastIpAddress(user.UserID, ip); } - return GetUserSettings(portalId, new Hashtable()); + // set the forms authentication cookie ( log the user in ) + var security = PortalSecurity.Instance; + security.SignIn(user, createPersistentCookie); + + EventManager.Instance.OnUserAuthenticated(new UserEventArgs { User = user }); } /// ----------------------------------------------------------------------------- /// - /// GetUserSettings retrieves the UserSettings from the User. + /// Validates a Password. /// - /// - /// - /// The Id of the Portal. - /// The Settings Hashtable. + /// The password to Validate. + /// A boolean. /// ----------------------------------------------------------------------------- - public static Hashtable GetUserSettings(int portalId) + public static bool ValidatePassword(string password) { - var settings = GetDefaultUserSettings(); - var masterPortalId = GetEffectivePortalId(portalId); - Dictionary settingsDictionary = (portalId == Null.NullInteger) - ? HostController.Instance.GetSettingsDictionary() - : PortalController.Instance.GetPortalSettings(masterPortalId); - Dictionary currentPortalSettings = null; - if (portalId != Null.NullInteger && masterPortalId != portalId) + // Valid Length + var isValid = password.Length >= MembershipProviderConfig.MinPasswordLength; + + // Validate NonAlphaChars + var rx = Globals.NonAlphanumericCharacters; + if (rx.Matches(password).Count < MembershipProviderConfig.MinNonAlphanumericCharacters) { - currentPortalSettings = PortalController.Instance.GetPortalSettings(portalId); + isValid = false; } - if (settingsDictionary != null) + // Validate Regex + if (!string.IsNullOrEmpty(MembershipProviderConfig.PasswordStrengthRegularExpression) && isValid) { - foreach (KeyValuePair kvp in settingsDictionary) - { - int index = kvp.Key.IndexOf("_"); - if (index > 0) - { - // Get the prefix - string prefix = kvp.Key.Substring(0, index + 1); - switch (prefix) - { - case "Column_": - case "Display_": - case "Profile_": - case "Records_": - case "Redirect_": - case "Registration_": - case "Security_": - switch (kvp.Key) - { - case "Display_Mode": - settings[kvp.Key] = (DisplayMode)Convert.ToInt32(kvp.Value); - break; - case "Profile_DefaultVisibility": - settings[kvp.Key] = (UserVisibilityMode)Convert.ToInt32(kvp.Value); - break; - case "Security_UsersControl": - settings[kvp.Key] = (UsersControl)Convert.ToInt32(kvp.Value); - break; - default: - // update value or add any new values - settings[kvp.Key] = kvp.Value; - break; - } - - break; - } - } - } - } - - if (currentPortalSettings != null) - { - foreach (var kvp in currentPortalSettings.Where(kvp => kvp.Key.StartsWith("Redirect_"))) - { - settings[kvp.Key] = kvp.Value; - } + isValid = Regex.IsMatch(password, MembershipProviderConfig.PasswordStrengthRegularExpression); } - return settings; + return isValid; } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal. + /// Validates a User's credentials against the Data Store. /// - /// - /// - /// The Id of the Portal. - /// An ArrayList of UserInfo objects. + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the + /// Login attempt. This value is returned by reference. + /// The UserInfo object representing a valid user. /// ----------------------------------------------------------------------------- - public static ArrayList GetUsers(int portalId) + public static UserInfo ValidateUser(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) { - return GetUsers(false, false, portalId); + return ValidateUser(portalId, username, password, "DNN", verificationCode, portalName, ip, ref loginStatus); } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal. + /// Validates a User's credentials against the Data Store. /// - /// - /// - /// The Id of the Portal. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The type of Authentication Used. + /// The verification code of the User attempting to log in. + /// The name of the Portal. + /// The IP Address of the user attempting to log in. + /// A UserLoginStatus enumeration that indicates the status of the + /// Login attempt. This value is returned by reference. + /// The UserInfo object representing a valid user. /// ----------------------------------------------------------------------------- - public static ArrayList GetUsers(bool includeDeleted, bool superUsersOnly, int portalId) + public static UserInfo ValidateUser(int portalId, string username, string password, string authType, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) { - var totalrecords = -1; - return GetUsers(portalId, -1, -1, ref totalrecords, includeDeleted, superUsersOnly); - } + loginStatus = UserLoginStatus.LOGIN_FAILURE; - /// ----------------------------------------------------------------------------- - /// - /// GetUsers gets all the users of the portal, by page. - /// - /// - /// - /// The Id of the Portal. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords) - { - return GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); - } + // Try and Log the user in + var user = MembershipProvider.Instance().UserLogin(GetEffectivePortalId(portalId), username, password, authType, verificationCode, ref loginStatus); + if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE || loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED) + { + // User Locked Out so log to event log + AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); + } - /// ----------------------------------------------------------------------------- - /// - /// GetUsers gets all the users of the portal, by page. - /// - /// - /// - /// The Id of the Portal. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) - { - return MembershipProvider.Instance().GetUsers(GetEffectivePortalId(portalId), pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + // Check Default Accounts + if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER) + { + CheckInsecurePassword(username, password, ref loginStatus); + } + + // Reset portalId + FixMemberPortalId(user, portalId); + + // return the User object + return user; } /// ----------------------------------------------------------------------------- /// - /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression. + /// Validates a User's Password and Profile. /// - /// - /// - /// The Id of the Portal. - /// The email address to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. + /// This overload takes a valid User (Credentials check out) and check whether the Password and Profile need updating. + /// The Id of the Portal the user belongs to. + /// The user attempting to log in. + /// Ingore expired user. + /// The UserLoginStatus. /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords) + public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool ignoreExpiring) { - return GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); + portalId = GetEffectivePortalId(portalId); + + var validStatus = UserValidStatus.VALID; + + // Check if Password needs to be updated + if (objUser.Membership.UpdatePassword) + { + // Admin has forced password update + validStatus = UserValidStatus.UPDATEPASSWORD; + } + else if (PasswordConfig.PasswordExpiry > 0) + { + var expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); + if (expiryDate < DateTime.Now) + { + // Password Expired + validStatus = UserValidStatus.PASSWORDEXPIRED; + } + else if (expiryDate < DateTime.Now.AddDays(PasswordConfig.PasswordExpiryReminder) && (!ignoreExpiring)) + { + // Password update reminder + validStatus = UserValidStatus.PASSWORDEXPIRING; + } + } + + // Check if user needs to consent to terms + if (validStatus == UserValidStatus.VALID && !(objUser.IsSuperUser || PortalSettings.Current.AdministratorId == objUser.UserID)) + { + if (PortalSettings.Current.DataConsentActive) + { + if (!objUser.HasAgreedToTerms) + { + validStatus = UserValidStatus.MUSTAGREETOTERMS; + } + } + } + + // Check if Profile needs updating + if (validStatus == UserValidStatus.VALID) + { + var validProfile = Convert.ToBoolean(UserModuleBase.GetSetting(portalId, "Security_RequireValidProfileAtLogin")); + if (validProfile && (!ProfileController.ValidateProfile(portalId, objUser.Profile))) + { + validStatus = UserValidStatus.UPDATEPROFILE; + } + } + + return validStatus; } - /// ----------------------------------------------------------------------------- /// - /// GetUserByEmail gets one single user matching the email address provided - /// This will only be useful in portals without duplicate email addresses - /// filter expression. + /// Tries to validate a verification code sent after a user is registered in a portal configured to use a verified registration. /// - /// - /// - /// The Id of the Portal. - /// The email address to use to find a match. - /// A single user object or null if no user found. - /// ----------------------------------------------------------------------------- - public static UserInfo GetUserByEmail(int portalId, string emailToMatch) + /// The verification code. + /// Thrown when provided verification code has been already used. + /// Thrown when the provided verification code is invalid. + /// Thrown when the user does not exist. + public static void VerifyUser(string verificationCode) { - int uid = DataProvider.Instance().GetSingleUserByEmail(portalId, emailToMatch); - if (uid > -1) + Requires.NotNullOrEmpty("verificationCode", verificationCode); + + var portalSecurity = PortalSecurity.Instance; + var decryptString = portalSecurity.Decrypt(Config.GetDecryptionkey(), verificationCode); + var strings = decryptString.Split('-'); + + if (strings.Length != 2) { - return GetUserById(portalId, uid); + throw new InvalidVerificationCodeException(); } - return null; + int portalId; + int userId; + var userIdString = strings[1]; + + if (!int.TryParse(strings[0], out portalId) || string.IsNullOrWhiteSpace(userIdString)) + { + throw new InvalidVerificationCodeException(); + } + + var user = int.TryParse(userIdString, out userId) ? GetUserById(portalId, userId) : GetUserByMembershipUserKey(portalId, userIdString); + + if (user == null) + { + throw new UserDoesNotExistException(); + } + + if (user.Membership.Approved) + { + throw new UserAlreadyVerifiedException(); + } + + if (!user.IsInRole("Unverified Users")) + { + // A Registered User that has been unapproved has managed to get a valid verification code + throw new InvalidVerificationCodeException(); + } + + user.Membership.Approved = true; + UpdateUser(portalId, user); + ApproveUser(user); } - /// ----------------------------------------------------------------------------- /// - /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression. + /// Returns a absolute URL for the user profile image while removing that of the deleted and super users. /// - /// - /// - /// The Id of the Portal. - /// The email address to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) + /// Portal Id. + /// user info. + /// width in pixel. + /// height in pixel. + /// true if want show super users user profile picture, false otherwise. + /// absolute user profile picture url. + /// + public static string GetProfileAvatarAbsoluteUrl(int portalId, UserInfo user, int width = 64, + int height = 64, bool showSuperUsers = true) { - return MembershipProvider.Instance().GetUsersByEmail(GetEffectivePortalId(portalId), emailToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + var userId = user != null && user.UserID > 0 && !user.IsDeleted && (showSuperUsers || !user.IsSuperUser) ? user.UserID : 0; + var relativePath = Instance.GetUserProfilePictureUrl(portalId, userId, width, height); + return GetAbsoluteUrl(portalId, relativePath); } /// ----------------------------------------------------------------------------- /// - /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter. + /// GetUser retrieves a User from the DataStore. /// /// /// /// The Id of the Portal. - /// The name of the property being matched. - /// The value of the property being matched. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. + /// The Id of the user being retrieved from the Data Store. + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords) + public UserInfo GetUser(int portalId, int userId) { - return GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, ref totalRecords, false, false); + return GetUserById(portalId, userId); } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter. - /// - /// - /// - /// The Id of the Portal. - /// The name of the property being matched. - /// The value of the property being matched. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) + public UserInfo GetUserByDisplayname(int portalId, string displayName) { - return MembershipProvider.Instance().GetUsersByProfileProperty(GetEffectivePortalId(portalId), propertyName, propertyValue, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + return MembershipProvider.Instance().GetUserByDisplayName(PortalController.GetEffectivePortalId(portalId), displayName); } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression. - /// - /// - /// - /// The Id of the Portal. - /// The username to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords) + 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, + string propertyValues) { - return GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); + return MembershipProvider.Instance().GetUsersAdvancedSearch(PortalController.GetEffectivePortalId(portalId), userId, filterUserId, filterRoleId, relationTypeId, + isAdmin, pageIndex, pageSize, sortColumn, + sortAscending, propertyNames, propertyValues); } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression. - /// - /// - /// - /// The Id of the Portal. - /// The username to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) + public IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, bool sortAscending, + string propertyName, string propertyValue) { - return MembershipProvider.Instance().GetUsersByUserName(GetEffectivePortalId(portalId), userNameToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + return MembershipProvider.Instance().GetUsersBasicSearch(PortalController.GetEffectivePortalId(portalId), pageIndex, pageSize, sortColumn, + sortAscending, propertyName, propertyValue); } - /// ----------------------------------------------------------------------------- /// - /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided - /// filter expression. + /// Return User Profile Picture relative Url. /// - /// + /// User Id. + /// Width in pixel. + /// Height in pixel. + /// Relative url, e.g. /DnnImageHandler.ashx?userid=1&h=32&w=32 considering child portal. + /// Usage: ascx - <asp:Image ID="avatar" runat="server" CssClass="SkinObject" /> + /// code behind - avatar.ImageUrl = UserController.Instance.GetUserProfilePictureUrl(userInfo.UserID, 32, 32). /// - /// The Id of the Portal. - /// The display name to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include Deleted Users. - /// Only get super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public static ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, ref int totalRecords, bool includeDeleted, bool superUsersOnly) + public string GetUserProfilePictureUrl(int userId, int width, int height) { - return MembershipProvider.Instance().GetUsersByDisplayName(GetEffectivePortalId(portalId), nameToMatch, pageIndex, pageSize, ref totalRecords, includeDeleted, superUsersOnly); + var url = $"/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={width}&w={height}"; + + var childPortalAlias = GetChildPortalAlias(); + var cdv = GetProfilePictureCdv(userId); + + return childPortalAlias.StartsWith(Globals.ApplicationPath) + ? childPortalAlias + url + cdv + : Globals.ApplicationPath + childPortalAlias + url + cdv; } - /// - /// Move a user to a different portal. - /// - /// The user to move. - /// The destination portal. - /// A flag that indicates whether to merge the original user. - public static void MoveUserToPortal(UserInfo user, PortalInfo portal, bool mergeUser) + public bool IsValidUserName(string userName) { - CopyUserToPortal(user, portal, mergeUser); - RemoveUser(user); + // Validate username against bad characters; it must not start or end with space, + // must not contain control characters, and not contain special punctuations + // Printable ASCII: " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" + // Fallback to default if there is no host setting configured + char[] unallowedAscii = HostController.Instance.GetString("UsernameUnallowedCharacters", Globals.USERNAME_UNALLOWED_ASCII).ToCharArray(); + return userName.Length >= 5 && + userName == userName.Trim() && + userName.All(ch => ch >= ' ') && + userName.IndexOfAny(unallowedAscii) < 0; + } + + public string GetUserProfilePictureUrl(int portalId, int userId, int width, int height) + { + var url = $"/DnnImageHandler.ashx?mode=profilepic&userId={userId}&h={width}&w={height}"; + + var childPortalAlias = Globals.ResolveUrl(this.GetUserProfilePictureUrl(userId, width, height)); + var cdv = GetProfilePictureCdv(portalId, userId); + + return childPortalAlias.StartsWith(Globals.ApplicationPath) + ? childPortalAlias + url + cdv + : Globals.ApplicationPath + childPortalAlias + url + cdv; } + /// ----------------------------------------------------------------------------- /// - /// Permanently deletes all users marked as deleted from a portal. It will delete the membership - /// user as well if the user has no other portals. + /// Update all the Users Display Names. /// - /// Portal ID to get the deleted users for. - public static void RemoveDeletedUsers(int portalId) + /// ----------------------------------------------------------------------------- + public void UpdateDisplayNames() { - var arrUsers = GetDeletedUsers(portalId); + int portalId = GetEffectivePortalId(this.PortalId); + var arrUsers = GetUsers(this.PortalId); foreach (UserInfo objUser in arrUsers) { - if (objUser.IsDeleted) - { - RemoveUser(objUser); - } + objUser.UpdateDisplayName(this.DisplayFormat); + UpdateUser(portalId, objUser); } } - /// - /// Permanently delete a user and the associated user folder on disk. - /// This also deletes the membership user if the user is - /// not a member of any other portal. - /// - /// The user to delete. - /// - public static bool RemoveUser(UserInfo user) + internal static Hashtable GetUserSettings(int portalId, Hashtable settings) { - int portalId = user.PortalID; - user.PortalID = GetEffectivePortalId(portalId); - - // Remove the User - var retValue = MembershipProvider.Instance().RemoveUser(user); + portalId = GetEffectivePortalId(portalId); - if (retValue) + if (settings["Column_FirstName"] == null) { - // Obtain PortalSettings from Current Context - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - - // Log event - EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_REMOVED); - - // Delete userFolder - DNN-3787 - DeleteUserFolder(user); - - DataCache.ClearPortalCache(portalId, false); - DataCache.ClearUserCache(portalId, user.Username); - - EventManager.Instance.OnUserRemoved(new UserEventArgs { User = user }); + settings["Column_FirstName"] = false; } - // Reset PortalId - FixMemberPortalId(user, portalId); - - 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)) + if (settings["Column_LastName"] == null) { - string resetPassword = ResetPassword(user, string.Empty); - return ChangePassword(user, resetPassword, newPassword); + settings["Column_LastName"] = false; } - return false; - } + if (settings["Column_DisplayName"] == null) + { + settings["Column_DisplayName"] = true; + } - public static bool ResetAndChangePassword(UserInfo user, string oldPassword, string newPassword) - { - if (System.Web.Security.Membership.ValidateUser(user.Username, oldPassword)) + if (settings["Column_Address"] == null) { - string resetPassword = ResetPassword(user, string.Empty); - return ChangePassword(user, resetPassword, newPassword); + settings["Column_Address"] = true; } - return false; - } + if (settings["Column_Telephone"] == null) + { + settings["Column_Telephone"] = true; + } - /// - /// Delete the contents and folder that belongs to a user in a specific portal. - /// - /// The user for whom to delete the folder. - /// Note the PortalID is taken to specify which portal to delete the folder from. - private static void DeleteUserFolder(UserInfo user) - { - var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); - var folderPortalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; - var userFolder = FolderManager.Instance.GetFolder(folderPortalId, userFolderPath); - if (userFolder != null) + if (settings["Column_Email"] == null) + { + settings["Column_Email"] = false; + } + + if (settings["Column_CreatedDate"] == null) { - FolderManager.Instance.Synchronize(folderPortalId, userFolderPath, true, true); - var notDeletedSubfolders = new List(); - FolderManager.Instance.DeleteFolder(userFolder, notDeletedSubfolders); + settings["Column_CreatedDate"] = true; + } - if (notDeletedSubfolders.Count == 0) - { - // try to remove the parent folder if there is no other users use this folder. - var parentFolder = FolderManager.Instance.GetFolder(userFolder.ParentID); - FolderManager.Instance.Synchronize(folderPortalId, parentFolder.FolderPath, true, true); - if (parentFolder != null && !FolderManager.Instance.GetFolders(parentFolder).Any()) - { - FolderManager.Instance.DeleteFolder(parentFolder, notDeletedSubfolders); + if (settings["Column_LastLogin"] == null) + { + settings["Column_LastLogin"] = false; + } - if (notDeletedSubfolders.Count == 0) - { - // try to remove the root folder if there is no other users use this folder. - var rootFolder = FolderManager.Instance.GetFolder(parentFolder.ParentID); - FolderManager.Instance.Synchronize(folderPortalId, rootFolder.FolderPath, true, true); - if (rootFolder != null && !FolderManager.Instance.GetFolders(rootFolder).Any()) - { - FolderManager.Instance.DeleteFolder(rootFolder, notDeletedSubfolders); - } - } - } - } + if (settings["Column_Authorized"] == null) + { + settings["Column_Authorized"] = true; } - } - /// ----------------------------------------------------------------------------- - /// - /// Resets the password for the specified user. - /// - /// Resets the user's password. - /// The user whose Password information we are resetting. - /// The answer to the "user's" password Question. - /// - /// ----------------------------------------------------------------------------- - public static string ResetPassword(UserInfo user, string passwordAnswer) - { - if (MembershipProviderConfig.PasswordResetEnabled) + if (settings["Display_Mode"] == null) { - user.Membership.Password = MembershipProvider.Instance().ResetPassword(user, passwordAnswer); + settings["Display_Mode"] = DisplayMode.All; } else { - // Throw a configuration exception as password reset is not enabled - throw new ConfigurationErrorsException("Password Reset is not enabled"); + settings["Display_Mode"] = (DisplayMode)Convert.ToInt32(settings["Display_Mode"]); } - return user.Membership.Password; - } + if (settings["Display_SuppressPager"] == null) + { + settings["Display_SuppressPager"] = false; + } - public static void ResetPasswordToken(UserInfo user) - { - ResetPasswordToken(user, false); - } + if (settings["Records_PerPage"] == null) + { + settings["Records_PerPage"] = 10; + } - public static bool ResetPasswordToken(UserInfo user, bool sendEmail) - { - var settings = new MembershipPasswordSettings(user.PortalID); - var expiry = DateTime.Now.AddMinutes(settings.ResetLinkValidity); - if (user.PasswordResetExpiration < DateTime.Now) + if (settings["Profile_DefaultVisibility"] == null) { - user.PasswordResetExpiration = expiry; - user.PasswordResetToken = Guid.NewGuid(); - UpdateUser(user.PortalID, user); + settings["Profile_DefaultVisibility"] = UserVisibilityMode.AdminOnly; } - else if (user.PasswordResetExpiration > expiry) + else { - user.PasswordResetExpiration = expiry; - UpdateUser(user.PortalID, user); + settings["Profile_DefaultVisibility"] = (UserVisibilityMode)Convert.ToInt32(settings["Profile_DefaultVisibility"]); } - if (sendEmail) + if (settings["Profile_DisplayVisibility"] == null) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return Mail.SendMail(user, MessageType.PasswordReminder, portalSettings) == string.Empty; + settings["Profile_DisplayVisibility"] = true; } - return true; - } - - public static void ResetPasswordToken(UserInfo user, int minutesValid) - { - user.PasswordResetExpiration = DateTime.Now.AddMinutes(minutesValid); - user.PasswordResetToken = Guid.NewGuid(); - UpdateUser(user.PortalID, user); - } - - public static bool RestoreUser(ref UserInfo user) - { - int portalId = user.PortalID; - user.PortalID = GetEffectivePortalId(portalId); + if (settings["Profile_ManageServices"] == null) + { + settings["Profile_ManageServices"] = true; + } - // Restore the User - var retValue = MembershipProvider.Instance().RestoreUser(user); + if (settings["Redirect_AfterLogin"] == null) + { + settings["Redirect_AfterLogin"] = -1; + } - if (retValue) + if (settings["Redirect_AfterRegistration"] == null) { - // restore user permissions - RestoreUserPermissions(user); + settings["Redirect_AfterRegistration"] = -1; + } - // Obtain PortalSettings from Current Context - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (settings["Redirect_AfterLogout"] == null) + { + settings["Redirect_AfterLogout"] = -1; + } - // Log event - EventLogController.Instance.AddLog("Username", user.Username, portalSettings, user.UserID, EventLogController.EventLogType.USER_RESTORED); + if (settings["Security_CaptchaLogin"] == null) + { + settings["Security_CaptchaLogin"] = false; + } - DataCache.ClearPortalUserCountCache(user.PortalID); - DataCache.ClearUserCache(user.PortalID, user.Username); + if (settings["Security_CaptchaRegister"] == null) + { + settings["Security_CaptchaRegister"] = false; } - // Reset PortalId - FixMemberPortalId(user, portalId); - UpdateUser(portalId, GetUserById(portalId, user.UserID)); - return retValue; - } + if (settings["Security_CaptchaChangePassword"] == null) + { + settings["Security_CaptchaChangePassword"] = false; + } - public static string SettingsKey(int portalId) - { - return "UserSettings|" + portalId; - } + if (settings["Security_CaptchaRetrivePassword"] == null) + { + settings["Security_CaptchaRetrivePassword"] = false; + } - /// ----------------------------------------------------------------------------- - /// - /// Unlocks the User's Account. - /// - /// - /// The user whose account is being Unlocked. - /// - /// ----------------------------------------------------------------------------- - public static bool UnLockUser(UserInfo user) - { - int portalId = user.PortalID; - user.PortalID = GetEffectivePortalId(portalId); + if (settings["Security_EmailValidation"] == null) + { + settings["Security_EmailValidation"] = Globals.glbEmailRegEx; + } - // Unlock the User - var retValue = MembershipProvider.Instance().UnLockUser(user); - DataCache.ClearUserCache(portalId, user.Username); - UpdateUser(portalId, GetUserById(portalId, user.UserID)); - return retValue; - } + if (settings["Security_UserNameValidation"] == null) + { + settings["Security_UserNameValidation"] = Globals.glbUserNameRegEx; + } - /// ----------------------------------------------------------------------------- - /// - /// Updates a User. - /// - /// The Id of the Portal. - /// The use to update. - /// - /// - /// ----------------------------------------------------------------------------- - public static void UpdateUser(int portalId, UserInfo user) - { - UpdateUser(portalId, user, true); - } + // Forces a valid profile on registration + if (settings["Security_RequireValidProfile"] == null) + { + settings["Security_RequireValidProfile"] = false; + } - /// ----------------------------------------------------------------------------- - /// - /// 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. - /// - /// - public static void UpdateUser(int portalId, UserInfo user, bool loggedAction) - { - UpdateUser(portalId, user, loggedAction, true); - } + // Forces a valid profile on login + if (settings["Security_RequireValidProfileAtLogin"] == null) + { + settings["Security_RequireValidProfileAtLogin"] = 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). - /// - /// - public static void UpdateUser(int portalId, UserInfo user, bool loggedAction, bool sendNotification) - { - UpdateUser(portalId, user, loggedAction, sendNotification, true); - } + if (settings["Security_UsersControl"] == null) + { + var portal = PortalController.Instance.GetPortal(portalId); - /// ----------------------------------------------------------------------------- - /// - /// Validates a User's credentials against the Data Store, and sets the Forms Authentication - /// Ticket. - /// - /// The Id of the Portal the user belongs to. - /// The user name of the User attempting to log in. - /// The password of the User attempting to log in. - /// The verification code of the User attempting to log in. - /// The name of the Portal. - /// The IP Address of the user attempting to log in. - /// A UserLoginStatus enumeration that indicates the status of the - /// Login attempt. This value is returned by reference. - /// A flag that indicates whether the login credentials - /// should be persisted. - /// The UserInfo object representing a successful login. - /// ----------------------------------------------------------------------------- - public static UserInfo UserLogin(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus, bool createPersistentCookie) - { - portalId = GetEffectivePortalId(portalId); + if (portal != null && portal.Users > 1000) + { + settings["Security_UsersControl"] = UsersControl.TextBox; + } + else + { + settings["Security_UsersControl"] = UsersControl.Combo; + } + } + else + { + settings["Security_UsersControl"] = (UsersControl)Convert.ToInt32(settings["Security_UsersControl"]); + } - loginStatus = UserLoginStatus.LOGIN_FAILURE; + // Display name format + if (settings["Security_DisplayNameFormat"] == null) + { + settings["Security_DisplayNameFormat"] = string.Empty; + } - // Validate the user - var objUser = ValidateUser(portalId, username, password, verificationCode, portalName, ip, ref loginStatus); - if (objUser != null) + if (settings["Registration_RequireConfirmPassword"] == null) { - // Call UserLogin overload - UserLogin(portalId, objUser, portalName, ip, createPersistentCookie); + settings["Registration_RequireConfirmPassword"] = true; } - else + + if (settings["Registration_RandomPassword"] == null) { - AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); + settings["Registration_RandomPassword"] = false; } - // return the User object - return objUser; - } + if (settings["Registration_UseEmailAsUserName"] == null) + { + settings["Registration_UseEmailAsUserName"] = false; + } - /// ----------------------------------------------------------------------------- - /// - /// Logs a Validated User in. - /// - /// The Id of the Portal the user belongs to. - /// The validated User. - /// The name of the Portal. - /// The IP Address of the user attempting to log in. - /// A flag that indicates whether the login credentials should be persisted. - /// ----------------------------------------------------------------------------- - public static void UserLogin(int portalId, UserInfo user, string portalName, string ip, bool createPersistentCookie) - { - portalId = GetEffectivePortalId(portalId); + if (settings["Registration_UseAuthProviders"] == null) + { + settings["Registration_UseAuthProviders"] = false; + } - AddEventLog(portalId, user.Username, user.UserID, portalName, ip, user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS); + if (settings["Registration_UseProfanityFilter"] == null) + { + settings["Registration_UseProfanityFilter"] = false; + } - if (user.LastIPAddress != ip) + if (settings["Registration_RegistrationFormType"] == null) { - // Update User in Database with Last IP used - user.LastIPAddress = ip; - DataProvider.Instance().UpdateUserLastIpAddress(user.UserID, ip); + settings["Registration_RegistrationFormType"] = 0; } - // set the forms authentication cookie ( log the user in ) - var security = PortalSecurity.Instance; - security.SignIn(user, createPersistentCookie); + if (settings["Registration_RegistrationFields"] == null) + { + settings["Registration_RegistrationFields"] = string.Empty; + } - EventManager.Instance.OnUserAuthenticated(new UserEventArgs { User = user }); + if (settings["Registration_ExcludeTerms"] == null) + { + settings["Registration_ExcludeTerms"] = string.Empty; + } + + if (settings["Registration_RequireUniqueDisplayName"] == null) + { + settings["Registration_RequireUniqueDisplayName"] = false; + } + + return settings; } /// ----------------------------------------------------------------------------- @@ -2209,223 +2090,332 @@ internal static void UpdateUser(int portalId, UserInfo user, bool loggedAction, EventManager.Instance.OnUserApproved(new UserEventArgs { User = user }); } - /// ----------------------------------------------------------------------------- - /// - /// Validates a Password. - /// - /// The password to Validate. - /// A boolean. - /// ----------------------------------------------------------------------------- - public static bool ValidatePassword(string password) + protected override Func GetFactory() { - // Valid Length - var isValid = password.Length >= MembershipProviderConfig.MinPasswordLength; + return () => new UserController(); + } - // Validate NonAlphaChars - var rx = Globals.NonAlphanumericCharacters; - if (rx.Matches(password).Count < MembershipProviderConfig.MinNonAlphanumericCharacters) + 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 { - isValid = false; - } + 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); - // Validate Regex - if (!string.IsNullOrEmpty(MembershipProviderConfig.PasswordStrengthRegularExpression) && isValid) + // 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)) { - isValid = Regex.IsMatch(password, MembershipProviderConfig.PasswordStrengthRegularExpression); + RoleController.Instance.AddUserRole(portalId, user.UserID, role.RoleID, RoleStatus.Approved, false, Null.NullDate, Null.NullDate); } - return isValid; + // Clear the roles cache - so the usercount is correct + RoleController.Instance.ClearRoleCache(portalId); } - /// ----------------------------------------------------------------------------- - /// - /// Validates a User's credentials against the Data Store. - /// - /// The Id of the Portal the user belongs to. - /// The user name of the User attempting to log in. - /// The password of the User attempting to log in. - /// The verification code of the User attempting to log in. - /// The name of the Portal. - /// The IP Address of the user attempting to log in. - /// A UserLoginStatus enumeration that indicates the status of the - /// Login attempt. This value is returned by reference. - /// The UserInfo object representing a valid user. - /// ----------------------------------------------------------------------------- - public static UserInfo ValidateUser(int portalId, string username, string password, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) + private static void AutoAssignUsersToRoles(UserInfo user, int portalId) { - return ValidateUser(portalId, username, password, "DNN", verificationCode, portalName, ip, ref loginStatus); + 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); + } + } } - /// ----------------------------------------------------------------------------- - /// - /// Validates a User's credentials against the Data Store. - /// - /// The Id of the Portal the user belongs to. - /// The user name of the User attempting to log in. - /// The password of the User attempting to log in. - /// The type of Authentication Used. - /// The verification code of the User attempting to log in. - /// The name of the Portal. - /// The IP Address of the user attempting to log in. - /// A UserLoginStatus enumeration that indicates the status of the - /// Login attempt. This value is returned by reference. - /// The UserInfo object representing a valid user. - /// ----------------------------------------------------------------------------- - public static UserInfo ValidateUser(int portalId, string username, string password, string authType, string verificationCode, string portalName, string ip, ref UserLoginStatus loginStatus) + // TODO - Handle Portal Groups + private static void DeleteUserPermissions(UserInfo user) { - loginStatus = UserLoginStatus.LOGIN_FAILURE; + FolderPermissionController.DeleteFolderPermissionsByUser(user); - // Try and Log the user in - var user = MembershipProvider.Instance().UserLogin(GetEffectivePortalId(portalId), username, password, authType, verificationCode, ref loginStatus); - if (loginStatus == UserLoginStatus.LOGIN_USERLOCKEDOUT || loginStatus == UserLoginStatus.LOGIN_FAILURE || loginStatus == UserLoginStatus.LOGIN_USERNOTAPPROVED) + // 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) { - // User Locked Out so log to event log - AddEventLog(portalId, username, Null.NullInteger, portalName, ip, loginStatus); + 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(); + } - // Check Default Accounts - if (loginStatus == UserLoginStatus.LOGIN_SUCCESS || loginStatus == UserLoginStatus.LOGIN_SUPERUSER) - { - CheckInsecurePassword(username, password, ref loginStatus); + return new UserInfo(); } - // Reset portalId - FixMemberPortalId(user, portalId); + user = (UserInfo)HttpContext.Current.Items["UserInfo"]; + return user ?? new UserInfo(); + } - // return the User object - return user; + private static int GetEffectivePortalId(int portalId) + { + return PortalController.GetEffectivePortalId(portalId); } - /// ----------------------------------------------------------------------------- - /// - /// Validates a User's Password and Profile. - /// - /// This overload takes a valid User (Credentials check out) and check whether the Password and Profile need updating. - /// The Id of the Portal the user belongs to. - /// The user attempting to log in. - /// Ingore expired user. - /// The UserLoginStatus. - /// ----------------------------------------------------------------------------- - public static UserValidStatus ValidateUser(UserInfo objUser, int portalId, bool ignoreExpiring) + private static object GetUserCountByPortalCallBack(CacheItemArgs cacheItemArgs) { - portalId = GetEffectivePortalId(portalId); + var portalId = (int)cacheItemArgs.ParamList[0]; + var portalUserCount = MembershipProvider.Instance().GetUserCountByPortal(portalId); + DataCache.SetCache(cacheItemArgs.CacheKey, portalUserCount); + return portalUserCount; + } - var validStatus = UserValidStatus.VALID; + 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); + } - // Check if Password needs to be updated - if (objUser.Membership.UpdatePassword) - { - // Admin has forced password update - validStatus = UserValidStatus.UPDATEPASSWORD; - } - else if (PasswordConfig.PasswordExpiry > 0) + private static bool IsMemberOfPortalGroup(int portalId) + { + return PortalController.IsMemberOfPortalGroup(portalId); + } + + private static void MergeUserProfileProperties(UserInfo userMergeFrom, UserInfo userMergeTo) + { + foreach (ProfilePropertyDefinition property in userMergeFrom.Profile.ProfileProperties) { - var expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); - if (expiryDate < DateTime.Now) - { - // Password Expired - validStatus = UserValidStatus.PASSWORDEXPIRED; - } - else if (expiryDate < DateTime.Now.AddDays(PasswordConfig.PasswordExpiryReminder) && (!ignoreExpiring)) + if (string.IsNullOrEmpty(userMergeTo.Profile.GetPropertyValue(property.PropertyName))) { - // Password update reminder - validStatus = UserValidStatus.PASSWORDEXPIRING; + userMergeTo.Profile.SetProfileProperty(property.PropertyName, property.PropertyValue); } } + } - // Check if user needs to consent to terms - if (validStatus == UserValidStatus.VALID && !(objUser.IsSuperUser || PortalSettings.Current.AdministratorId == objUser.UserID)) + private static void MergeUserProperties(UserInfo userMergeFrom, UserInfo userMergeTo) + { + if (string.IsNullOrEmpty(userMergeTo.DisplayName)) { - if (PortalSettings.Current.DataConsentActive) - { - if (!objUser.HasAgreedToTerms) - { - validStatus = UserValidStatus.MUSTAGREETOTERMS; - } - } + userMergeTo.DisplayName = userMergeFrom.DisplayName; } - // Check if Profile needs updating - if (validStatus == UserValidStatus.VALID) + if (string.IsNullOrEmpty(userMergeTo.Email)) { - var validProfile = Convert.ToBoolean(UserModuleBase.GetSetting(portalId, "Security_RequireValidProfileAtLogin")); - if (validProfile && (!ProfileController.ValidateProfile(portalId, objUser.Profile))) - { - validStatus = UserValidStatus.UPDATEPROFILE; - } + userMergeTo.Email = userMergeFrom.Email; } - return validStatus; + if (string.IsNullOrEmpty(userMergeTo.FirstName)) + { + userMergeTo.FirstName = userMergeFrom.FirstName; + } + + if (string.IsNullOrEmpty(userMergeTo.LastName)) + { + userMergeTo.LastName = userMergeFrom.LastName; + } } - /// - /// Tries to validate a verification code sent after a user is registered in a portal configured to use a verified registration. - /// - /// The verification code. - /// Thrown when provided verification code has been already used. - /// Thrown when the provided verification code is invalid. - /// Thrown when the user does not exist. - public static void VerifyUser(string verificationCode) + private static void SendDeleteEmailNotifications(UserInfo user, PortalSettings portalSettings) { - Requires.NotNullOrEmpty("verificationCode", verificationCode); + var message = new Message(); + message.FromUserID = portalSettings.AdministratorId; + message.ToUserID = portalSettings.AdministratorId; + message.Subject = Localization.GetSystemMessage( + 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); + } - var portalSecurity = PortalSecurity.Instance; - var decryptString = portalSecurity.Decrypt(Config.GetDecryptionkey(), verificationCode); - var strings = decryptString.Split('-'); + private static string GetChildPortalAlias() + { + var settings = PortalController.Instance.GetCurrentPortalSettings(); + var currentAlias = settings.PortalAlias.HTTPAlias; + var index = currentAlias.IndexOf('/'); + var childPortalAlias = index > 0 ? "/" + currentAlias.Substring(index + 1) : string.Empty; + return childPortalAlias; + } - if (strings.Length != 2) + private static string GetProfilePictureCdv(int userId) + { + var settings = PortalController.Instance.GetCurrentPortalSettings(); + var userInfo = GetUserById(settings.PortalId, userId); + if (userInfo?.Profile == null) { - throw new InvalidVerificationCodeException(); + return string.Empty; } - int portalId; - int userId; - var userIdString = strings[1]; + var cdv = string.Empty; + var photoProperty = userInfo.Profile.GetProperty("Photo"); - if (!int.TryParse(strings[0], out portalId) || string.IsNullOrWhiteSpace(userIdString)) + int photoFileId; + if (int.TryParse(photoProperty?.PropertyValue, out photoFileId)) { - throw new InvalidVerificationCodeException(); + var photoFile = FileManager.Instance.GetFile(photoFileId); + if (photoFile != null) + { + cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; + } } - var user = int.TryParse(userIdString, out userId) ? GetUserById(portalId, userId) : GetUserByMembershipUserKey(portalId, userIdString); + return cdv; + } - if (user == null) + private static string GetProfilePictureCdv(int portalId, int userId) + { + var userInfo = GetUserById(portalId, userId); + if (userInfo?.Profile == null) { - throw new UserDoesNotExistException(); + return string.Empty; } - if (user.Membership.Approved) - { - throw new UserAlreadyVerifiedException(); - } + var cdv = string.Empty; + var photoProperty = userInfo.Profile.GetProperty("Photo"); - if (!user.IsInRole("Unverified Users")) + int photoFileId; + if (int.TryParse(photoProperty?.PropertyValue, out photoFileId)) { - // A Registered User that has been unapproved has managed to get a valid verification code - throw new InvalidVerificationCodeException(); + var photoFile = FileManager.Instance.GetFile(photoFileId); + if (photoFile != null) + { + cdv = "&cdv=" + photoFile.LastModifiedOnDate.Ticks; + } } - user.Membership.Approved = true; - UpdateUser(portalId, user); - ApproveUser(user); + return cdv; } /// - /// Returns a absolute URL for the user profile image while removing that of the deleted and super users. + /// Delete the contents and folder that belongs to a user in a specific portal. /// - /// Portal Id. - /// user info. - /// width in pixel. - /// height in pixel. - /// true if want show super users user profile picture, false otherwise. - /// absolute user profile picture url. - /// - public static string GetProfileAvatarAbsoluteUrl(int portalId, UserInfo user, int width = 64, - int height = 64, bool showSuperUsers = true) + /// The user for whom to delete the folder. + /// Note the PortalID is taken to specify which portal to delete the folder from. + private static void DeleteUserFolder(UserInfo user) { - var userId = user != null && user.UserID > 0 && !user.IsDeleted && (showSuperUsers || !user.IsSuperUser) ? user.UserID : 0; - var relativePath = Instance.GetUserProfilePictureUrl(portalId, userId, width, height); - return GetAbsoluteUrl(portalId, relativePath); + var userFolderPath = ((PathUtils)PathUtils.Instance).GetUserFolderPathInternal(user); + var folderPortalId = user.IsSuperUser ? Null.NullInteger : user.PortalID; + var userFolder = FolderManager.Instance.GetFolder(folderPortalId, userFolderPath); + if (userFolder != null) + { + FolderManager.Instance.Synchronize(folderPortalId, userFolderPath, true, true); + var notDeletedSubfolders = new List(); + FolderManager.Instance.DeleteFolder(userFolder, notDeletedSubfolders); + + if (notDeletedSubfolders.Count == 0) + { + // try to remove the parent folder if there is no other users use this folder. + var parentFolder = FolderManager.Instance.GetFolder(userFolder.ParentID); + FolderManager.Instance.Synchronize(folderPortalId, parentFolder.FolderPath, true, true); + if (parentFolder != null && !FolderManager.Instance.GetFolders(parentFolder).Any()) + { + FolderManager.Instance.DeleteFolder(parentFolder, notDeletedSubfolders); + + if (notDeletedSubfolders.Count == 0) + { + // try to remove the root folder if there is no other users use this folder. + var rootFolder = FolderManager.Instance.GetFolder(parentFolder.ParentID); + FolderManager.Instance.Synchronize(folderPortalId, rootFolder.FolderPath, true, true); + if (rootFolder != null && !FolderManager.Instance.GetFolders(rootFolder).Any()) + { + FolderManager.Instance.DeleteFolder(rootFolder, notDeletedSubfolders); + } + } + } + } + } } /// @@ -2461,5 +2451,15 @@ private static UserInfo GetUserByMembershipUserKey(int portalId, string membersh FixMemberPortalId(user, portalId); return user; } + + UserInfo IUserController.GetCurrentUserInfo() + { + return GetCurrentUserInternal(); + } + + UserInfo IUserController.GetUserById(int portalId, int userId) + { + return GetUserById(portalId, userId); + } } } diff --git a/DNN Platform/Library/Entities/Users/UserEventArgs.cs b/DNN Platform/Library/Entities/Users/UserEventArgs.cs index 00a2c643110..b7b951f604f 100644 --- a/DNN Platform/Library/Entities/Users/UserEventArgs.cs +++ b/DNN Platform/Library/Entities/Users/UserEventArgs.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Entities.Users public class UserEventArgs : EventArgs { public UserInfo User { get; set; } - + public bool SendNotification { get; set; } } } diff --git a/DNN Platform/Library/Entities/Users/UserEventHandlers.cs b/DNN Platform/Library/Entities/Users/UserEventHandlers.cs index 9d0e914f47f..989316c692c 100644 --- a/DNN Platform/Library/Entities/Users/UserEventHandlers.cs +++ b/DNN Platform/Library/Entities/Users/UserEventHandlers.cs @@ -42,7 +42,7 @@ public void UserApproved(object sender, UserEventArgs args) { UserRegistrationEmailNotifier.NotifyUser(args.User, MessageType.UserRegistrationPublic); } - + DeleteAllNewUnauthorizedUserRegistrationNotifications(args.User.UserID); } diff --git a/DNN Platform/Library/Entities/Users/UserInfo.cs b/DNN Platform/Library/Entities/Users/UserInfo.cs index b79d46ef03f..ce417661b5c 100644 --- a/DNN Platform/Library/Entities/Users/UserInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserInfo.cs @@ -33,12 +33,12 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- [Serializable] public class UserInfo : BaseEntityInfo, IPropertyAccess - { + { + private readonly ConcurrentDictionary _social = new ConcurrentDictionary(); private string _administratorRoleName; private UserMembership _membership; private UserProfile _profile; - private readonly ConcurrentDictionary _social = new ConcurrentDictionary(); - + public UserInfo() { this.IsDeleted = Null.NullBoolean; @@ -46,8 +46,48 @@ public UserInfo() this.PortalID = Null.NullInteger; this.IsSuperUser = Null.NullBoolean; this.AffiliateID = Null.NullInteger; - } - + } + + /// + /// Gets a value indicating whether gets whether the user is in the portal's administrators role. + /// + public bool IsAdmin + { + get + { + if (this.IsSuperUser) + { + return true; + } + + PortalInfo ps = PortalController.Instance.GetPortal(this.PortalID); + return ps != null && this.IsInRole(ps.AdministratorRoleName); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the Social property. + /// + /// ----------------------------------------------------------------------------- + [Browsable(false)] + public UserSocial Social + { + get + { + return this._social.GetOrAdd(this.PortalID, i => new UserSocial(this)); + } + } + + [Browsable(false)] + public CacheLevel Cacheability + { + get + { + return CacheLevel.notCacheable; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the AffiliateId for this user. @@ -61,8 +101,8 @@ public UserInfo() /// Gets or sets and sets the Display Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(3)] - [Required(true)] + [SortOrder(3)] + [Required(true)] [MaxLength(128)] public string DisplayName { get; set; } @@ -71,9 +111,9 @@ public UserInfo() /// Gets or sets and sets the Email Address. /// /// ----------------------------------------------------------------------------- - [SortOrder(4)] - [MaxLength(256)] - [Required(true)] + [SortOrder(4)] + [MaxLength(256)] + [Required(true)] [RegularExpressionValidator(Globals.glbEmailRegEx)] public string Email { get; set; } @@ -82,7 +122,7 @@ public UserInfo() /// Gets or sets and sets the First Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(1)] + [SortOrder(1)] [MaxLength(50)] public string FirstName { @@ -105,23 +145,6 @@ public string FirstName /// ----------------------------------------------------------------------------- [Browsable(false)] public bool IsSuperUser { get; set; } - - /// - /// Gets a value indicating whether gets whether the user is in the portal's administrators role. - /// - public bool IsAdmin - { - get - { - if (this.IsSuperUser) - { - return true; - } - - PortalInfo ps = PortalController.Instance.GetPortal(this.PortalID); - return ps != null && this.IsInRole(ps.AdministratorRoleName); - } - } /// ----------------------------------------------------------------------------- /// @@ -136,7 +159,7 @@ public bool IsAdmin /// Gets or sets and sets the Last Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(2)] + [SortOrder(2)] [MaxLength(50)] public string LastName { @@ -162,10 +185,10 @@ public UserMembership Membership UserController.GetUserMembership(this); } } - + return this._membership; } - + set { this._membership = value; } } @@ -180,7 +203,7 @@ public UserMembership Membership /// [Browsable(false)] public DateTime PasswordResetExpiration { get; set; } - + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the PortalId. @@ -229,10 +252,10 @@ public UserProfile Profile UserInfo userInfo = this; ProfileController.GetUserProfile(ref userInfo); } - + return this._profile; } - + set { this._profile = value; } } @@ -242,11 +265,11 @@ public string[] Roles get { var socialRoles = this.Social.Roles; - if (socialRoles.Count == 0) - { - return new string[0]; - } - + if (socialRoles.Count == 0) + { + return new string[0]; + } + return (from r in this.Social.Roles where r.Status == RoleStatus.Approved && @@ -255,22 +278,8 @@ public string[] Roles select r.RoleName) .ToArray(); } - - set { } - } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the Social property. - /// - /// ----------------------------------------------------------------------------- - [Browsable(false)] - public UserSocial Social - { - get - { - return this._social.GetOrAdd(this.PortalID, i => new UserSocial(this)); - } + set { } } /// ----------------------------------------------------------------------------- @@ -286,23 +295,14 @@ public UserSocial Social /// Gets or sets and sets the User Name. /// /// ----------------------------------------------------------------------------- - [SortOrder(0)] - [MaxLength(100)] - [IsReadOnly(true)] + [SortOrder(0)] + [MaxLength(100)] + [IsReadOnly(true)] [Required(true)] public string Username { get; set; } - public string VanityUrl { get; set; } + public string VanityUrl { get; set; } - [Browsable(false)] - public CacheLevel Cacheability - { - get - { - return CacheLevel.notCacheable; - } - } - /// /// Property access, initially provided for TokenReplace. /// @@ -328,7 +328,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format { internScope = currentScope; // admins and user himself can access all data } - + string outputFormat = format == string.Empty ? "g" : format; switch (propertyName.ToLowerInvariant()) { @@ -338,7 +338,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + var ps = PortalSecurity.Instance; var code = ps.Encrypt(Config.GetDecryptionkey(), this.PortalID + "-" + this.GetMembershipUserId()); return code.Replace("+", ".").Replace("/", "-").Replace("=", "_"); @@ -348,7 +348,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return this.AffiliateID.ToString(outputFormat, formatProvider); case "displayname": if (internScope < Scope.Configuration) @@ -356,7 +356,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.DisplayName, format); case "email": if (internScope < Scope.DefaultSettings) @@ -364,7 +364,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.Email, format); case "firstname": // using profile property is recommended! if (internScope < Scope.DefaultSettings) @@ -372,7 +372,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.FirstName, format); case "issuperuser": if (internScope < Scope.Debug) @@ -380,7 +380,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return this.IsSuperUser.ToString(formatProvider); case "lastname": // using profile property is recommended! if (internScope < Scope.DefaultSettings) @@ -388,7 +388,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.LastName, format); case "portalid": if (internScope < Scope.Configuration) @@ -396,7 +396,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return this.PortalID.ToString(outputFormat, formatProvider); case "userid": if (internScope < Scope.DefaultSettings) @@ -404,7 +404,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return this.UserID.ToString(outputFormat, formatProvider); case "username": if (internScope < Scope.DefaultSettings) @@ -412,7 +412,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.Username, format); case "fullname": // fullname is obsolete, it will return DisplayName if (internScope < Scope.Configuration) @@ -420,7 +420,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(this.DisplayName, format); case "roles": if (currentScope < Scope.SystemMessages) @@ -428,14 +428,14 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return PropertyAccess.ContentLocked; } - + return PropertyAccess.FormatString(string.Join(", ", this.Roles), format); } - + propertyNotFound = true; return string.Empty; } - + /// ----------------------------------------------------------------------------- /// /// IsInRole determines whether the user is in the role passed. @@ -455,12 +455,12 @@ public bool IsInRole(string role) { return true; } - + if (this.UserID == Null.NullInteger && role == Globals.glbRoleUnauthUserName) { return true; } - + if ("[" + this.UserID + "]" == role) { return true; @@ -471,52 +471,26 @@ public bool IsInRole(string role) { return roles.Any(s => s == role); } - + return false; } /// ----------------------------------------------------------------------------- /// /// Gets current time in User's timezone. - /// + /// /// /// ----------------------------------------------------------------------------- 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; - } /// ----------------------------------------------------------------------------- /// /// Convert utc time in User's timezone. /// - /// Utc time to convert. + /// Utc time to convert. /// /// ----------------------------------------------------------------------------- public DateTime LocalTime(DateTime utcTime) @@ -525,7 +499,7 @@ public DateTime LocalTime(DateTime utcTime) { return TimeZoneInfo.ConvertTime(utcTime, TimeZoneInfo.Utc, this.Profile.PreferredTimeZone); } - + return TimeZoneInfo.ConvertTime(utcTime, TimeZoneInfo.Utc, PortalController.Instance.GetCurrentPortalSettings().TimeZone); } @@ -543,6 +517,32 @@ public void UpdateDisplayName(string format) format = format.Replace("[LASTNAME]", this.LastName); format = format.Replace("[USERNAME]", this.Username); this.DisplayName = format; - } + } + + /// + /// 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 a7361bf83c0..1b5536538b5 100644 --- a/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs +++ b/DNN Platform/Library/Entities/Users/UserRegistrationEmailNotifier.cs @@ -18,7 +18,7 @@ public class UserRegistrationEmailNotifier public UserRegistrationEmailNotifier() { } - + private static UserInfo CurrentUser => UserController.Instance.GetCurrentUserInfo(); public static void NotifyAdministrator(UserInfo user) diff --git a/DNN Platform/Library/Entities/Users/UserRoleInfo.cs b/DNN Platform/Library/Entities/Users/UserRoleInfo.cs index ac5e27bdc99..72f4b01a0e6 100644 --- a/DNN Platform/Library/Entities/Users/UserRoleInfo.cs +++ b/DNN Platform/Library/Entities/Users/UserRoleInfo.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- [Serializable] public class UserRoleInfo : RoleInfo - { + { public int UserRoleID { get; set; } public int UserID { get; set; } @@ -40,8 +40,8 @@ public class UserRoleInfo : RoleInfo public bool IsTrialUsed { get; set; } - public bool Subscribed { get; set; } - + public bool Subscribed { get; set; } + public override void Fill(IDataReader dr) { // Fill base class properties diff --git a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs index 1301494117c..345e04bad00 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/AnonymousUserInfo.cs @@ -33,7 +33,7 @@ public string UserID { return this._UserID; } - + set { this._UserID = value; diff --git a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs index eaedfe55329..a30aa7a3981 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/BaseUserInfo.cs @@ -37,7 +37,7 @@ public int PortalID { return this._PortalID; } - + set { this._PortalID = value; @@ -56,7 +56,7 @@ public int TabID { return this._TabID; } - + set { this._TabID = value; @@ -75,7 +75,7 @@ public DateTime CreationDate { return this._CreationDate; } - + set { this._CreationDate = value; @@ -94,7 +94,7 @@ public DateTime LastActiveDate { return this._LastActiveDate; } - + set { this._LastActiveDate = value; diff --git a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs index 4c2c64bd930..cfb826758da 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/OnlineUserInfo.cs @@ -34,7 +34,7 @@ public int UserID { return this._UserID; } - + set { this._UserID = value; diff --git a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs index 910ba317b1a..646e2ed0098 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/PurgeUsersOnline.cs @@ -22,9 +22,9 @@ namespace DotNetNuke.Entities.Users /// ----------------------------------------------------------------------------- [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 class PurgeUsersOnline : SchedulerClient - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a PurgeUsesOnline SchedulerClient. /// diff --git a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs index c1ea8093a47..3ec6a886c36 100644 --- a/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs +++ b/DNN Platform/Library/Entities/Users/Users Online/UserOnlineController.cs @@ -48,7 +48,7 @@ public void ClearUserList() /// ----------------------------------------------------------------------------- /// /// Gets the Online time window. - /// + /// /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -60,7 +60,7 @@ public int GetOnlineTimeWindow() /// ----------------------------------------------------------------------------- /// /// Gets the cached 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.")] @@ -79,14 +79,14 @@ public Hashtable GetUserList() } } } - + return userList; } /// ----------------------------------------------------------------------------- /// /// Gets whether the Users Online functionality is enabled. - /// + /// /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -98,7 +98,7 @@ public bool IsEnabled() /// ----------------------------------------------------------------------------- /// /// Determines whether a User is online. - /// + /// /// /// ----------------------------------------------------------------------------- [Obsolete("Support for users online was removed in 8.x, other solutions exist outside of the DNN Platform. Scheduled removal in v11.0.0.")] @@ -109,7 +109,7 @@ public bool IsUserOnline(UserInfo user) { isOnline = memberProvider.IsUserOnline(user); } - + return isOnline; } @@ -143,7 +143,7 @@ public void TrackUsers() { context.Items["CheckedUsersOnlineCookie"] = "true"; } - + if (context.Request.IsAuthenticated) { this.TrackAuthenticatedUser(context); @@ -200,14 +200,14 @@ private void TrackAnonymousUser(HttpContext context) { return; } - + AnonymousUserInfo user; Hashtable userList = this.GetUserList(); string userID; // Check if the Tracking cookie exists HttpCookie cookie = context.Request.Cookies[cookieName]; - + // Track Anonymous User if (cookie == null) { @@ -291,7 +291,7 @@ private void TrackAuthenticatedUser(HttpContext context) { return; } - + // Get the logged in User ID UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -303,7 +303,7 @@ private void TrackAuthenticatedUser(HttpContext context) { user.UserID = objUserInfo.UserID; } - + user.PortalID = portalSettings.PortalId; user.TabID = portalSettings.ActiveTab.TabID; user.LastActiveDate = DateTime.Now; @@ -311,7 +311,7 @@ private void TrackAuthenticatedUser(HttpContext context) { user.CreationDate = user.LastActiveDate; } - + userList[objUserInfo.UserID.ToString()] = user; this.SetUserList(userList); } diff --git a/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs index 9931292bae0..bb335ea906c 100644 --- a/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/DefaultExtensionControl.cs @@ -23,7 +23,7 @@ public string Module var s = (string)this.ViewState["Module"]; return s ?? string.Empty; } - + set { this.ViewState["Module"] = value; @@ -39,7 +39,7 @@ public string Group var s = (string)this.ViewState["Group"]; return s ?? string.Empty; } - + set { this.ViewState["Group"] = value; @@ -55,7 +55,7 @@ public string Name var s = (string)this.ViewState["Name"]; return s ?? string.Empty; } - + set { this.ViewState["Name"] = value; diff --git a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs index 1bd6556f22a..b9685deaa97 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPagePanelExtensionControl.cs @@ -51,7 +51,26 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } - + + public void CancelAction(int portalId, int tabId, int moduleId) + { + foreach (var control in this.Controls) + { + var panelcontrol = control as PanelEditPagePanelExtensionControl; + if (panelcontrol != null) + { + foreach (var extensionControl in panelcontrol.Controls) + { + var actionsControl = extensionControl as IEditPagePanelControlActions; + if (actionsControl != null) + { + actionsControl.CancelAction(portalId, tabId, moduleId); + } + } + } + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -76,7 +95,7 @@ protected override void OnInit(EventArgs e) } } } - + private void LoadControl(IEditPagePanelExtensionPoint extension) { var editPanel = new PanelEditPagePanelExtensionControl { PanelId = extension.EditPagePanelId, Text = extension.Text, CssClass = extension.CssClass }; @@ -85,31 +104,12 @@ private void LoadControl(IEditPagePanelExtensionPoint extension) editPanel.Controls.Add(control); this.Controls.Add(editPanel); } - - public void CancelAction(int portalId, int tabId, int moduleId) - { - foreach (var control in this.Controls) - { - var panelcontrol = control as PanelEditPagePanelExtensionControl; - if (panelcontrol != null) - { - foreach (var extensionControl in panelcontrol.Controls) - { - var actionsControl = extensionControl as IEditPagePanelControlActions; - if (actionsControl != null) - { - actionsControl.CancelAction(portalId, tabId, moduleId); - } - } - } - } - } } public class PanelEditPagePanelExtensionControl : WebControl { public string PanelId { get; set; } - + public string Text { get; set; } protected override void RenderContents(HtmlTextWriter op) diff --git a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs index 4bfb7c3ab98..a3bc763b9db 100644 --- a/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/EditPageTabExtensionControl.cs @@ -24,7 +24,7 @@ public string TabControlId var s = (string)this.ViewState["TabControlId"]; return s ?? string.Empty; } - + set { this.ViewState["TabControlId"] = value; @@ -40,7 +40,7 @@ public string PanelControlId var s = (string)this.ViewState["PanelControlId"]; return s ?? string.Empty; } - + set { this.ViewState["PanelControlId"] = value; @@ -89,6 +89,27 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } + public void CancelAction(int portalId, int tabId, int moduleId) + { + var panel = this.Parent.FindControl(this.PanelControlId); + + foreach (var control in panel.Controls) + { + var panelcontrol = control as PanelTabExtensionControl; + if (panelcontrol != null) + { + foreach (var extensionControl in panelcontrol.Controls) + { + var actionsControl = extensionControl as IEditPageTabControlActions; + if (actionsControl != null) + { + actionsControl.CancelAction(portalId, tabId, moduleId); + } + } + } + } + } + protected override void OnInit(EventArgs e) { var extensionPointManager = new ExtensionPointManager(); @@ -115,27 +136,6 @@ protected override void OnInit(EventArgs e) } } } - - public void CancelAction(int portalId, int tabId, int moduleId) - { - var panel = this.Parent.FindControl(this.PanelControlId); - - foreach (var control in panel.Controls) - { - var panelcontrol = control as PanelTabExtensionControl; - if (panelcontrol != null) - { - foreach (var extensionControl in panelcontrol.Controls) - { - var actionsControl = extensionControl as IEditPageTabControlActions; - if (actionsControl != null) - { - actionsControl.CancelAction(portalId, tabId, moduleId); - } - } - } - } - } } public class PanelTabExtensionControl : WebControl diff --git a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs index 193e0b8c1f3..bc6710f7c94 100644 --- a/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs +++ b/DNN Platform/Library/ExtensionPoints/ExtensionPointManager.cs @@ -20,34 +20,6 @@ public class ExtensionPointManager private static readonly CompositionContainer MefCompositionContainer = InitializeMefCompositionContainer(); -#pragma warning disable 649 - - [ImportMany] - private IEnumerable> _scripts; - - [ImportMany] - private IEnumerable> _editPageTabExtensionPoint; - - [ImportMany] - private IEnumerable> _toolbarButtonExtensionPoints; - - [ImportMany] - private IEnumerable> _editPagePanelExtensionPoints; - - [ImportMany] - private IEnumerable> _ctxMenuItemExtensionPoints; - - [ImportMany] - private IEnumerable> _userControlExtensionPoints; - - [ImportMany] - private IEnumerable> _menuItems; - - [ImportMany] - private IEnumerable> _gridColumns; - -#pragma warning restore 649 - public ExtensionPointManager() { ComposeParts(this); @@ -66,14 +38,6 @@ 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 @@ -108,7 +72,7 @@ public IToolBarButtonExtensionPoint GetToolBarButtonExtensionPointFirstByPriorit orderby e.Metadata.Priority select e.Value).FirstOrDefault(); } - + public IEnumerable GetScriptItemExtensionPoints(string module) { return this.GetScriptItemExtensionPoints(module, null); @@ -116,10 +80,10 @@ 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 + 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; } @@ -169,9 +133,9 @@ 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 + return from e in this._userControlExtensionPoints + where e.Metadata.Module == module && e.Metadata.Group == @group + orderby e.Value.Order select e.Value; } @@ -211,9 +175,45 @@ orderby e.Value.Order select e.Value; } + 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); + } + private bool FilterCondition(IExtensionPointData data, string module, string group) { return data.Module == module && (string.IsNullOrEmpty(@group) || data.Group == @group); } + +#pragma warning disable 649 + + [ImportMany] + private IEnumerable> _scripts; + + [ImportMany] + private IEnumerable> _editPageTabExtensionPoint; + + [ImportMany] + private IEnumerable> _toolbarButtonExtensionPoints; + + [ImportMany] + private IEnumerable> _editPagePanelExtensionPoints; + + [ImportMany] + private IEnumerable> _ctxMenuItemExtensionPoints; + + [ImportMany] + private IEnumerable> _userControlExtensionPoints; + + [ImportMany] + private IEnumerable> _menuItems; + + [ImportMany] + private IEnumerable> _gridColumns; + +#pragma warning restore 649 } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs b/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs index 0ac606cc198..a03e2301f86 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.ExtensionPoints public interface IEditPagePanelControlActions { void SaveAction(int portalId, int tabId, int moduleId); - + void CancelAction(int portalId, int tabId, int moduleId); - + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs index 43ea69cb891..4704a288443 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPagePanelExtensionPoint.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.ExtensionPoints public interface IEditPagePanelExtensionPoint : IUserControlExtensionPoint { string EditPagePanelId { get; } - + string CssClass { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs b/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs index 5f2fa941816..63e58f93525 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPageTabControlActions.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.ExtensionPoints public interface IEditPageTabControlActions { void SaveAction(int portalId, int tabId, int moduleId); - + void CancelAction(int portalId, int tabId, int moduleId); - + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs index 47b2c4bfc31..dcadb62c620 100644 --- a/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IEditPageTabExtensionPoint.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.ExtensionPoints public interface IEditPageTabExtensionPoint : IUserControlExtensionPoint { string EditPageTabId { get; } - + string CssClass { get; } - + string Permission { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs index d0837a4c4e1..0026ae793cb 100644 --- a/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IExtensionPoint.cs @@ -7,9 +7,9 @@ namespace DotNetNuke.ExtensionPoints public interface IExtensionPoint { string Text { get; } - + string Icon { get; } - + int Order { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs index 49800255b8d..b13b7eadc5d 100644 --- a/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IGridColumnExtensionPoint.cs @@ -9,19 +9,19 @@ namespace DotNetNuke.ExtensionPoints public interface IGridColumnExtensionPoint : IExtensionPoint { int ColumnAt { get; } - + string UniqueName { get; } - + string DataField { get; } - + string HeaderText { get; } - + Unit HeaderStyleWidth { get; } - + bool ReadOnly { get; } - + bool Reorderable { get; } - + string SortExpression { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs index 0213babfab9..3e1b26e0fd0 100644 --- a/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IToolBarMenuButtonExtensionPoint.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.ExtensionPoints public interface IToolBarMenuButtonExtensionPoint : IToolBarButtonExtensionPoint { List Items { get; } - + string MenuCssClass { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs b/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs index 2ce4e1862c5..4e61c8b896b 100644 --- a/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs +++ b/DNN Platform/Library/ExtensionPoints/IUserControlActions.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.ExtensionPoints public interface IUserControlActions { void SaveAction(int portalId, int tabId, int moduleId); - + void CancelAction(int portalId, int tabId, int moduleId); - + void BindAction(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs b/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs index f98f9fdbc40..7ba7545c781 100644 --- a/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs +++ b/DNN Platform/Library/ExtensionPoints/IUserControlExtensionPoint.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.ExtensionPoints public interface IUserControlExtensionPoint : IExtensionPoint { string UserControlSrc { get; } - + bool Visible { get; } } } diff --git a/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs b/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs index 7d4e6e575e3..f773bb8736b 100644 --- a/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs +++ b/DNN Platform/Library/ExtensionPoints/SafeDirectoryCatalog.cs @@ -29,10 +29,10 @@ public SafeDirectoryCatalog(string directory) // Force MEF to load the plugin and figure out if there are any exports // good assemblies will not throw the RTLE exception and can be added to the catalog - if (asmCat.Parts.ToList().Count > 0) - { - this._catalog.Catalogs.Add(asmCat); - } + if (asmCat.Parts.ToList().Count > 0) + { + this._catalog.Catalogs.Add(asmCat); + } } catch (ReflectionTypeLoadException) { diff --git a/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs b/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs index eee8a512a06..5424e57b800 100644 --- a/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs +++ b/DNN Platform/Library/ExtensionPoints/ToolBarMenuButtonRenderer.cs @@ -23,7 +23,7 @@ public string GetOutput(IExtensionPoint extensionPoint) cssClass += " disabled"; action = "void(0);"; } - + var icon = extension.Icon; if (icon.StartsWith("~/")) { diff --git a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs index 9a0606a89e7..505e34344fb 100644 --- a/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs +++ b/DNN Platform/Library/ExtensionPoints/UserControlExtensionControl.cs @@ -36,7 +36,19 @@ public void SaveAction(int portalId, int tabId, int moduleId) } } } - + + public void CancelAction(int portalId, int tabId, int moduleId) + { + foreach (var control in this.Controls) + { + var actionsControl = control as IUserControlActions; + if (actionsControl != null) + { + actionsControl.CancelAction(portalId, tabId, moduleId); + } + } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -55,24 +67,12 @@ protected override void OnInit(EventArgs e) } } } - + 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) - { - foreach (var control in this.Controls) - { - var actionsControl = control as IUserControlActions; - if (actionsControl != null) - { - actionsControl.CancelAction(portalId, tabId, moduleId); - } - } - } } } diff --git a/DNN Platform/Library/Framework/AJAX.cs b/DNN Platform/Library/Framework/AJAX.cs index 4ded65c023a..dc50d95f2c9 100644 --- a/DNN Platform/Library/Framework/AJAX.cs +++ b/DNN Platform/Library/Framework/AJAX.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Framework using DotNetNuke.UI.WebControls; public class AJAX - { + { /// ----------------------------------------------------------------------------- /// /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page. @@ -23,7 +23,7 @@ public static void AddScriptManager(Page page) { AddScriptManager(page, true); } - + /// /// AddScriptManager is used internally by the framework to add a ScriptManager control to the page. /// @@ -37,11 +37,11 @@ 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) @@ -49,10 +49,10 @@ public static void AddScriptManager(Page page, bool checkCdn) scriptManager.EnableCdn = Host.EnableMsAjaxCdn; scriptManager.EnableCdnFallback = Host.EnableMsAjaxCdn; } - + page.Form.Controls.AddAt(0, scriptManager); } - + if (HttpContext.Current.Items["System.Web.UI.ScriptManager"] == null) { HttpContext.Current.Items.Add("System.Web.UI.ScriptManager", true); @@ -63,7 +63,7 @@ public static void AddScriptManager(Page page, bool checkCdn) // suppress error adding script manager to support edge-case of module developers custom aspx pages that inherit from basepage and use code blocks } } - + if (page.Form != null) { try @@ -92,8 +92,8 @@ public static void AddScriptManager(Page page, bool checkCdn) } } } - } - + } + /// Gets the current ScriptManager on the page. /// the page instance. /// The ScriptManager instance, or null. @@ -108,7 +108,7 @@ public static ScriptManager GetScriptManager(Page objPage) /// only need one Script Manager per page. /// /// - /// + /// /// public static bool IsEnabled() { @@ -127,7 +127,7 @@ public static bool IsEnabled() /// IsInstalled can be used to determine if AJAX is installed on the server. /// /// - /// + /// /// public static bool IsInstalled() { @@ -186,7 +186,7 @@ public static void RemoveScriptManager(Page objPage) /// Wraps a control in an update panel. /// /// - /// + /// /// public static Control WrapUpdatePanelControl(Control objControl, bool blnIncludeProgress) { @@ -203,10 +203,10 @@ public static Control WrapUpdatePanelControl(Control objControl, bool blnInclude { // if ID matches objControl.Parent.Controls.AddAt(i, updatePanel); - + // insert update panel in that position objContentTemplateContainer.Controls.Add(objControl); - + // inject passed in control into update panel break; } @@ -217,7 +217,7 @@ public static Control WrapUpdatePanelControl(Control objControl, bool blnInclude // create image for update progress control var objImage = new Image(); objImage.ImageUrl = "~/images/progressbar.gif"; - + // hardcoded objImage.AlternateText = "ProgressBar"; @@ -230,6 +230,6 @@ public static Control WrapUpdatePanelControl(Control objControl, bool blnInclude } return updatePanel; - } + } } } diff --git a/DNN Platform/Library/Framework/BaseHttpHandler.cs b/DNN Platform/Library/Framework/BaseHttpHandler.cs index b2e8a2fbe3b..a266753e240 100644 --- a/DNN Platform/Library/Framework/BaseHttpHandler.cs +++ b/DNN Platform/Library/Framework/BaseHttpHandler.cs @@ -101,8 +101,8 @@ public virtual bool HasPermission /// /// Gets the content MIME type for the response object. /// - /// - /// The content MIME type for the response object. + /// + /// The content MIME type for the response object. /// public virtual string ContentMimeType { @@ -115,8 +115,8 @@ public virtual string ContentMimeType /// /// Gets the content encoding for the response object. /// - /// - /// The content encoding for the response object. + /// + /// The content encoding for the response object. /// public virtual Encoding ContentEncoding { @@ -124,7 +124,7 @@ public virtual Encoding ContentEncoding { return Encoding.UTF8; } - } + } public virtual bool IsReusable { @@ -132,8 +132,8 @@ public virtual bool IsReusable { return true; } - } - + } + /// /// Processs the incoming HTTP request. /// @@ -161,7 +161,7 @@ public void ProcessRequest(HttpContext context) this.HandleRequest(); } - + /// /// Handles the request. This is where you put your /// business logic. diff --git a/DNN Platform/Library/Framework/CachePageStatePersister.cs b/DNN Platform/Library/Framework/CachePageStatePersister.cs index ec3316aad0a..1c78ede2e1c 100644 --- a/DNN Platform/Library/Framework/CachePageStatePersister.cs +++ b/DNN Platform/Library/Framework/CachePageStatePersister.cs @@ -22,15 +22,15 @@ namespace DotNetNuke.Framework /// ----------------------------------------------------------------------------- public class CachePageStatePersister : PageStatePersister { - private const string VIEW_STATE_CACHEKEY = "__VIEWSTATE_CACHEKEY"; - + private const string VIEW_STATE_CACHEKEY = "__VIEWSTATE_CACHEKEY"; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Creates the CachePageStatePersister. /// /// ----------------------------------------------------------------------------- - public CachePageStatePersister(Page page) + public CachePageStatePersister(Page page) : base(page) { } @@ -50,7 +50,7 @@ public override void Load() { throw new ApplicationException("Missing valid " + VIEW_STATE_CACHEKEY); } - + var state = DataCache.GetCache(key); if (state != null) { @@ -58,7 +58,7 @@ public override void Load() this.ViewState = state.First; this.ControlState = state.Second; } - + // Remove this ViewState from the cache as it has served its purpose if (!this.Page.IsCallback) { diff --git a/DNN Platform/Library/Framework/DiskPageStatePersister.cs b/DNN Platform/Library/Framework/DiskPageStatePersister.cs index 3043004cb4a..2b7192ed52e 100644 --- a/DNN Platform/Library/Framework/DiskPageStatePersister.cs +++ b/DNN Platform/Library/Framework/DiskPageStatePersister.cs @@ -20,14 +20,14 @@ namespace DotNetNuke.Framework /// /// ----------------------------------------------------------------------------- public class DiskPageStatePersister : PageStatePersister - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Creates the DiskPageStatePersister. /// /// ----------------------------------------------------------------------------- - public DiskPageStatePersister(Page page) + public DiskPageStatePersister(Page page) : base(page) { } @@ -66,7 +66,7 @@ public string StateFileName key.Append("_"); key.Append(this.Page.Request.RawUrl); } - + return this.CacheDirectory + "\\" + Globals.CleanFileName(key.ToString()) + ".txt"; } } @@ -79,7 +79,7 @@ public string StateFileName public override void Load() { StreamReader reader = null; - + // Read the state string, using the StateFormatter. try { @@ -116,7 +116,7 @@ public override void Save() { return; } - + if (this.Page.Session != null) { if (!Directory.Exists(this.CacheDirectory)) diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs index 7bbe86f8ebe..5c0b3069541 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScript.cs @@ -168,6 +168,52 @@ public static string JQueryUIFile(bool getMinFile) return jfile; } + public static string GetJQueryScriptReference() + { +#pragma warning disable 618 + string scriptsrc = jQuery.HostedUrl; + if (!jQuery.UseHostedScript) + { + scriptsrc = jQuery.JQueryFile(!jQuery.UseDebugScript); + } + + return scriptsrc; +#pragma warning restore 618 + } + + public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceReferences reference) + { + switch (reference) + { + case ClientAPI.ClientNamespaceReferences.dnn: + case ClientAPI.ClientNamespaceReferences.dnn_dom: + if (HttpContextSource.Current.Items.Contains(LegacyPrefix + "dnn.js")) + { + break; + } + + ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.js", 12); + HttpContextSource.Current.Items.Add(LegacyPrefix + "dnn.js", true); + page.ClientScript.RegisterClientScriptBlock(page.GetType(), "dnn.js", string.Empty); + + if (!ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.SingleCharDelimiters)) + { + ClientAPI.RegisterClientVariable(page, "__scdoff", "1", true); + } + + if (!ClientAPI.UseExternalScripts) + { + ClientAPI.RegisterEmbeddedResource(page, "dnn.scripts.js", typeof(ClientAPI)); + } + + break; + case ClientAPI.ClientNamespaceReferences.dnn_dom_positioning: + RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn); + ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.dom.positioning.js", 13); + break; + } + } + private static void RequestHighestVersionLibraryRegistration(string jsname) { var library = GetHighestVersionLibrary(jsname); @@ -563,51 +609,5 @@ where item.ToString().StartsWith(LegacyPrefix) } #pragma warning restore 618 } - - public static string GetJQueryScriptReference() - { -#pragma warning disable 618 - string scriptsrc = jQuery.HostedUrl; - if (!jQuery.UseHostedScript) - { - scriptsrc = jQuery.JQueryFile(!jQuery.UseDebugScript); - } - - return scriptsrc; -#pragma warning restore 618 - } - - public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceReferences reference) - { - switch (reference) - { - case ClientAPI.ClientNamespaceReferences.dnn: - case ClientAPI.ClientNamespaceReferences.dnn_dom: - if (HttpContextSource.Current.Items.Contains(LegacyPrefix + "dnn.js")) - { - break; - } - - ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.js", 12); - HttpContextSource.Current.Items.Add(LegacyPrefix + "dnn.js", true); - page.ClientScript.RegisterClientScriptBlock(page.GetType(), "dnn.js", string.Empty); - - if (!ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.SingleCharDelimiters)) - { - ClientAPI.RegisterClientVariable(page, "__scdoff", "1", true); - } - - if (!ClientAPI.UseExternalScripts) - { - ClientAPI.RegisterEmbeddedResource(page, "dnn.scripts.js", typeof(ClientAPI)); - } - - break; - case ClientAPI.ClientNamespaceReferences.dnn_dom_positioning: - RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn); - ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.dom.positioning.js", 13); - break; - } - } } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs index 815596896d7..6faa75d8661 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibrary.cs @@ -16,43 +16,43 @@ public class JavaScriptLibrary : IXmlSerializable /// Gets or sets unique identifier id for a javscript library package. /// public int JavaScriptLibraryID { get; set; } - + /// /// Gets or sets package id associated with the javscript library package. /// public int PackageID { get; set; } - + /// /// Gets or sets name of the javscript library package (used when requesting library). /// public string LibraryName { get; set; } - + /// /// Gets or sets version of the the javscript library package from the database. /// public Version Version { get; set; } - + /// /// Gets or sets main object (where relevant) of the javscript library package /// used to generate the local file fallback code in the case where the CDN file is not available. /// public string ObjectName { get; set; } - + /// /// Gets or sets filename of the script in the filesystem. /// public string FileName { get; set; } - + /// /// Gets or sets position in the page the script reference is injected. /// public ScriptLocation PreferredScriptLocation { get; set; } - + /// /// Gets or sets location of the content delivery network (CDN) where the script is loaded from when CDN has been enabled in host. /// - public string CDNPath { get; set; } - + public string CDNPath { get; set; } + public XmlSchema GetSchema() { throw new NotImplementedException(); @@ -72,7 +72,7 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; @@ -106,7 +106,7 @@ public void ReadXml(XmlReader reader) this.PreferredScriptLocation = ScriptLocation.PageHead; break; } - + break; case "CDNPath": this.CDNPath = reader.ReadElementContentAsString(); @@ -116,7 +116,7 @@ public void ReadXml(XmlReader reader) { reader.ReadElementContentAsString(); } - + break; } } @@ -143,6 +143,6 @@ public void WriteXml(XmlWriter writer) // Write end of main element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs index 154603fba3d..c060fcbbc35 100644 --- a/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.cs +++ b/DNN Platform/Library/Framework/JavaScriptLibraries/JavaScriptLibraryController.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 DotNetNuke.Framework.JavaScriptLibraries { using System; @@ -33,16 +32,6 @@ 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,12 +47,12 @@ 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), + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.JavaScriptLibrariesCacheKey, + DataCache.JavaScriptLibrariesCacheTimeout, + DataCache.JavaScriptLibrariesCachePriority), c => CBO.FillCollection(DataProvider.Instance().ExecuteReader("GetJavaScriptLibraries"))); } @@ -71,7 +60,7 @@ public IEnumerable GetLibraries() /// Library to be saved. public void SaveLibrary(JavaScriptLibrary library) { - library.JavaScriptLibraryID = DataProvider.Instance().ExecuteScalar( + library.JavaScriptLibraryID = DataProvider.Instance().ExecuteScalar( "SaveJavaScriptLibrary", library.JavaScriptLibraryID, library.PackageID, @@ -82,6 +71,16 @@ public void SaveLibrary(JavaScriptLibrary library) library.PreferredScriptLocation, library.CDNPath); this.ClearCache(); - } + } + + protected override Func GetFactory() + { + return () => new JavaScriptLibraryController(); + } + + private void ClearCache() + { + DataCache.RemoveCache(DataCache.JavaScriptLibrariesCacheKey); + } } } diff --git a/DNN Platform/Library/Framework/PageBase.cs b/DNN Platform/Library/Framework/PageBase.cs index cdc6719d6ae..ed24ed4a253 100644 --- a/DNN Platform/Library/Framework/PageBase.cs +++ b/DNN Platform/Library/Framework/PageBase.cs @@ -39,19 +39,19 @@ namespace DotNetNuke.Framework public abstract class PageBase : Page { 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(); private readonly ArrayList _localizedControls; + + private PageStatePersister _persister; private CultureInfo _pageCulture; - private string _localResourceFile; - + private string _localResourceFile; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Creates the Page. /// @@ -59,8 +59,8 @@ public abstract class PageBase : Page protected PageBase() { this._localizedControls = new ArrayList(); - } - + } + public PortalSettings PortalSettings { get @@ -76,39 +76,6 @@ public NameValueCollection HtmlAttributes return this._htmlAttributes; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets pageStatePersister returns an instance of the class that will be used to persist the Page State. - /// - /// A System.Web.UI.PageStatePersister. - /// ----------------------------------------------------------------------------- - protected override PageStatePersister PageStatePersister - { - get - { - // Set ViewState Persister to default (as defined in Base Class) - if (this._persister == null) - { - this._persister = base.PageStatePersister; - - if (Globals.Status == Globals.UpgradeStatus.None) - { - switch (Host.PageStatePersister) - { - case "M": - this._persister = new CachePageStatePersister(this); - break; - case "D": - this._persister = new DiskPageStatePersister(this); - break; - } - } - } - - return this._persister; - } - } public CultureInfo PageCulture { @@ -132,10 +99,10 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; @@ -147,7 +114,40 @@ public string LocalResourceFile /// /// Gets a value indicating whether indicate whether http headers has been sent to client. /// - public bool HeaderIsWritten { get; internal set; } + public bool HeaderIsWritten { get; internal set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets pageStatePersister returns an instance of the class that will be used to persist the Page State. + /// + /// A System.Web.UI.PageStatePersister. + /// ----------------------------------------------------------------------------- + protected override PageStatePersister PageStatePersister + { + get + { + // Set ViewState Persister to default (as defined in Base Class) + if (this._persister == null) + { + this._persister = base.PageStatePersister; + + if (Globals.Status == Globals.UpgradeStatus.None) + { + switch (Host.PageStatePersister) + { + case "M": + this._persister = new CachePageStatePersister(this); + break; + case "D": + this._persister = new DiskPageStatePersister(this); + break; + } + } + } + + return this._persister; + } + } /// /// RemoveKeyAttribute remove the key attribute from the control. If this isn't done, then the HTML output will have @@ -160,7 +160,7 @@ public static void RemoveKeyAttribute(ArrayList affectedControls) { return; } - + int i; for (i = 0; i <= affectedControls.Count - 1; i++) { @@ -170,8 +170,8 @@ public static void RemoveKeyAttribute(ArrayList affectedControls) ac.Remove(IconController.IconSizeName); ac.Remove(IconController.IconStyleName); } - } - + } + /// /// GetControlAttribute looks a the type of control and does it's best to find an AttributeCollection. /// @@ -220,12 +220,12 @@ internal static string GetControlAttribute(Control control, ArrayList affectedCo } } } - + if (key != null && affectedControls != null) { affectedControls.Add(attributeCollection); } - + return key; } @@ -238,12 +238,12 @@ internal static string GetControlAttribute(Control control, ArrayList affectedCo /// 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 + if (!control.Visible) + { + return; + } + + // Perform the substitution if a key was found var key = GetControlAttribute(control, affectedControls, Localization.KeyName); if (!string.IsNullOrEmpty(key)) { @@ -268,14 +268,14 @@ internal void ProcessControl(Control control, ArrayList affectedControls, bool i listControl.Items[i].Text = value; } } - + if (key != null && affectedControls != null) { affectedControls.Add(attributeCollection); } } } - + // UrlRewriting Issue - ResolveClientUrl gets called instead of ResolveUrl // Manual Override to ResolveUrl var image = control as Image; @@ -325,7 +325,7 @@ internal void ProcessControl(Control control, ArrayList affectedControls, bool i { ctrl.NavigateUrl = this.Page.ResolveUrl(ctrl.NavigateUrl); } - + if (ctrl.ImageUrl.IndexOf("~", StringComparison.Ordinal) != -1) { ctrl.ImageUrl = this.Page.ResolveUrl(ctrl.ImageUrl); @@ -342,11 +342,11 @@ internal void ProcessControl(Control control, ArrayList affectedControls, bool i } // Process child controls - if (!includeChildren || !control.HasControls()) - { - return; - } - + if (!includeChildren || !control.HasControls()) + { + return; + } + var objModuleControl = control as IModuleControl; if (objModuleControl == null) { @@ -372,7 +372,7 @@ internal void ProcessControl(Control control, ArrayList affectedControls, bool i this.IterateControls(control.Controls, affectedControls, objModuleControl.LocalResourceFile); } } - + protected virtual void RegisterAjaxScript() { if (ServicesFrameworkInternal.Instance.IsAjaxScriptSupportRequired) @@ -422,55 +422,6 @@ protected override void OnError(EventArgs e) strURL = this.GetErrorUrl(strURL, exc); Exceptions.ProcessPageLoadException(exc, strURL); } - - 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) - { - 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) { @@ -536,15 +487,64 @@ protected override void Render(HtmlTextWriter writer) base.Render(writer); this.LogDnnTrace("PageBase.Render", "End", $"{this.Page.Request.Url.AbsoluteUri}"); - } + } + + 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) + { + 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})"); + } + } private void LocalizeControl(Control control, string value) { - if (string.IsNullOrEmpty(value)) - { - return; - } - + if (string.IsNullOrEmpty(value)) + { + return; + } + var validator = control as BaseValidator; if (validator != null) { @@ -566,21 +566,21 @@ private void LocalizeControl(Control control, string value) var imgMatches = LinkItemMatchRegex.Matches(value); foreach (Match match in imgMatches) { - if (match.Groups[match.Groups.Count - 2].Value.IndexOf("~", StringComparison.Ordinal) == -1) - { - continue; - } - + 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; } diff --git a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs index 582924b8790..711f9256c89 100644 --- a/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs +++ b/DNN Platform/Library/Framework/Providers/ProviderConfigurationHandler.cs @@ -9,12 +9,12 @@ namespace DotNetNuke.Framework.Providers [Obsolete("This class is obsolete. It is no longer used to load provider configurations, as there are medium trust issues. Scheduled removal in v11.0.0.")] internal class ProviderConfigurationHandler : IConfigurationSectionHandler - { + { public virtual object Create(object parent, object context, XmlNode node) { var objProviderConfiguration = new ProviderConfiguration(); objProviderConfiguration.LoadValuesFromConfigurationXml(node); return objProviderConfiguration; - } + } } } diff --git a/DNN Platform/Library/Framework/Reflection.cs b/DNN Platform/Library/Framework/Reflection.cs index d16e4a46cae..bc9ec0893fd 100644 --- a/DNN Platform/Library/Framework/Reflection.cs +++ b/DNN Platform/Library/Framework/Reflection.cs @@ -25,8 +25,8 @@ namespace DotNetNuke.Framework /// ----------------------------------------------------------------------------- public class Reflection { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Reflection)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Reflection)); + /// ----------------------------------------------------------------------------- /// /// Creates an object. @@ -187,7 +187,7 @@ public static object CreateObject(string ObjectProviderType, string ObjectProvid } } } - + return CreateObject(TypeName, TypeName, UseCache); } @@ -267,7 +267,7 @@ public static Type CreateType(string TypeName, string CacheKey, bool UseCache, b { CacheKey = TypeName; } - + Type type = null; // use the cache for performance @@ -297,7 +297,7 @@ public static Type CreateType(string TypeName, string CacheKey, bool UseCache, b } } } - + return type; } @@ -366,6 +366,6 @@ internal static object CreateObjectNotCached(string ObjectProviderType) // dynamically create the object return Activator.CreateInstance(objType); - } + } } } diff --git a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs index 7c953f2719e..a2dd21f7d86 100644 --- a/DNN Platform/Library/Framework/Reflections/TypeLocator.cs +++ b/DNN Platform/Library/Framework/Reflections/TypeLocator.cs @@ -16,24 +16,24 @@ public class TypeLocator : ITypeLocator, IAssemblyLocator { private IAssemblyLocator _assemblyLocator; + internal IAssemblyLocator AssemblyLocator + { + get { return this._assemblyLocator ?? (this._assemblyLocator = this); } + set { this._assemblyLocator = value; } + } + 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) + 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); } - set { this._assemblyLocator = value; } - } - public IEnumerable GetAllMatchingTypes(Predicate predicate) { foreach (var assembly in this.AssemblyLocator.Assemblies) diff --git a/DNN Platform/Library/Framework/SecurityPolicy.cs b/DNN Platform/Library/Framework/SecurityPolicy.cs index d4e8828da8e..91c27389d19 100644 --- a/DNN Platform/Library/Framework/SecurityPolicy.cs +++ b/DNN Platform/Library/Framework/SecurityPolicy.cs @@ -62,66 +62,6 @@ public static bool HasReflectionPermission() return m_ReflectionPermission; } - private static void GetPermissions() - { - if (!m_Initialized) - { - // test RelectionPermission - CodeAccessPermission securityTest; - try - { - securityTest = new ReflectionPermission(PermissionState.Unrestricted); - securityTest.Demand(); - m_ReflectionPermission = true; - } - catch - { - // code access security error - m_ReflectionPermission = false; - } - - // test WebPermission - try - { - securityTest = new WebPermission(PermissionState.Unrestricted); - securityTest.Demand(); - m_WebPermission = true; - } - catch - { - // code access security error - m_WebPermission = false; - } - - // test WebHosting Permission (Full Trust) - try - { - securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted); - securityTest.Demand(); - m_AspNetHostingPermission = true; - } - catch - { - // code access security error - m_AspNetHostingPermission = false; - } - - m_Initialized = true; - - // Test for Unmanaged Code permission - try - { - securityTest = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); - securityTest.Demand(); - m_UnManagedCodePermission = true; - } - catch (Exception) - { - m_UnManagedCodePermission = false; - } - } - } - public static bool HasWebPermission() { GetPermissions(); @@ -188,5 +128,65 @@ public static bool HasRelectionPermission() GetPermissions(); return m_ReflectionPermission; } + + private static void GetPermissions() + { + if (!m_Initialized) + { + // test RelectionPermission + CodeAccessPermission securityTest; + try + { + securityTest = new ReflectionPermission(PermissionState.Unrestricted); + securityTest.Demand(); + m_ReflectionPermission = true; + } + catch + { + // code access security error + m_ReflectionPermission = false; + } + + // test WebPermission + try + { + securityTest = new WebPermission(PermissionState.Unrestricted); + securityTest.Demand(); + m_WebPermission = true; + } + catch + { + // code access security error + m_WebPermission = false; + } + + // test WebHosting Permission (Full Trust) + try + { + securityTest = new AspNetHostingPermission(AspNetHostingPermissionLevel.Unrestricted); + securityTest.Demand(); + m_AspNetHostingPermission = true; + } + catch + { + // code access security error + m_AspNetHostingPermission = false; + } + + m_Initialized = true; + + // Test for Unmanaged Code permission + try + { + securityTest = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); + securityTest.Demand(); + m_UnManagedCodePermission = true; + } + catch (Exception) + { + m_UnManagedCodePermission = false; + } + } + } } } diff --git a/DNN Platform/Library/Framework/ServiceLocator.cs b/DNN Platform/Library/Framework/ServiceLocator.cs index 4e1e6fae109..b98149d03e1 100644 --- a/DNN Platform/Library/Framework/ServiceLocator.cs +++ b/DNN Platform/Library/Framework/ServiceLocator.cs @@ -13,32 +13,7 @@ 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 restore InconsistentNaming - private static TContract _testableInstance; - private static bool _useTestable; - - /// - /// Gets a singleton of T. - /// - public static TContract Instance - { - get - { - if (_useTestable) - { - return _testableInstance; - } - - return _instance.Value; - } - } - - // ReSharper restore StaticFieldInGenericType + { protected static Func Factory { get; set; } /// @@ -63,6 +38,8 @@ public static void ClearInstance() _instance = new Lazy(InitInstance, true); } + protected abstract Func GetFactory(); + private static TContract InitInstance() { if (Factory == null) @@ -74,6 +51,30 @@ private static TContract InitInstance() return Factory(); } - protected abstract Func GetFactory(); + // ReSharper disable StaticFieldInGenericType + // ReSharper disable InconsistentNaming + private static Lazy _instance = new Lazy(InitInstance, true); + + // ReSharper restore InconsistentNaming + private static TContract _testableInstance; + private static bool _useTestable; + + /// + /// Gets a singleton of T. + /// + public static TContract Instance + { + get + { + if (_useTestable) + { + return _testableInstance; + } + + return _instance.Value; + } + } + + // ReSharper restore StaticFieldInGenericType } } diff --git a/DNN Platform/Library/Framework/ServicesFramework.cs b/DNN Platform/Library/Framework/ServicesFramework.cs index f68a1f7a429..067dcc516db 100644 --- a/DNN Platform/Library/Framework/ServicesFramework.cs +++ b/DNN Platform/Library/Framework/ServicesFramework.cs @@ -17,29 +17,29 @@ public class ServicesFramework : ServiceLocator 0) { path = path.Substring(index); - if (!path.EndsWith("/")) - { - path += "/"; - } + if (!path.EndsWith("/")) + { + path += "/"; + } } - else - { - path = "/"; - } - + else + { + path = "/"; + } + return path; } - + protected override Func GetFactory() { return () => new ServicesFrameworkImpl(); diff --git a/DNN Platform/Library/Framework/UserControlBase.cs b/DNN Platform/Library/Framework/UserControlBase.cs index fecaa509d6e..c3d697fe215 100644 --- a/DNN Platform/Library/Framework/UserControlBase.cs +++ b/DNN Platform/Library/Framework/UserControlBase.cs @@ -26,7 +26,7 @@ public bool IsHostMenu } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { diff --git a/DNN Platform/Library/Framework/jQuery.cs b/DNN Platform/Library/Framework/jQuery.cs index 51bceb5c3d0..93cd979c969 100644 --- a/DNN Platform/Library/Framework/jQuery.cs +++ b/DNN Platform/Library/Framework/jQuery.cs @@ -34,8 +34,8 @@ 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"; + + 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"; @@ -47,12 +47,12 @@ public class jQuery private const string jQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js"; private const string jQueryUIVersionKey = "jQueryUIVersionKey"; private const string jQueryUIVersionMatch = "(?<=version:\\s\")(.*)(?=\")"; - + /// /// Gets the HostSetting for the URL of the hosted version of the jQuery script. /// - /// - /// The HostSetting for the URL of the hosted version of the jQuery script. + /// + /// The HostSetting for the URL of the hosted version of the jQuery script. /// /// /// This is a simple wrapper around the Host.jQueryUrl property. @@ -73,8 +73,8 @@ public static string HostedUrl /// /// Gets the HostSetting for the URL of the hosted version of the jQuery migrated script. /// - /// - /// The HostSetting for the URL of the hosted version of the jQuery migrated script. + /// + /// The HostSetting for the URL of the hosted version of the jQuery migrated script. /// /// /// This is a simple wrapper around the Host.jQueryUrl property. @@ -95,8 +95,8 @@ public static string HostedMigrateUrl /// /// Gets the HostSetting for the URL of the hosted version of the jQuery UI script. /// - /// - /// The HostSetting for the URL of the hosted version of the jQuery UI script. + /// + /// The HostSetting for the URL of the hosted version of the jQuery UI script. /// /// /// This is a simple wrapper around the Host.jQueryUIUrl property. @@ -149,7 +149,7 @@ public static bool IsUIInstalled return File.Exists(minFile) || File.Exists(dbgFile); } } - + public static bool IsRequested { get @@ -185,8 +185,8 @@ public static bool IsHoverIntentRequested /// /// Gets a value indicating whether gets the HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. /// - /// - /// The HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. + /// + /// The HostSetting to determine if we should use the standard jQuery script or the minified jQuery script. /// /// /// This is a simple wrapper around the Host.jQueryDebug property. @@ -207,8 +207,8 @@ public static bool UseDebugScript /// /// Gets a value indicating whether gets the HostSetting to determine if we should use a hosted version of the jQuery script. /// - /// - /// The HostSetting to determine if we should use a hosted version of the jQuery script. + /// + /// The HostSetting to determine if we should use a hosted version of the jQuery script. /// /// /// This is a simple wrapper around the Host.jQueryHosted property. @@ -229,8 +229,8 @@ public static bool UseHostedScript /// /// Gets the version string for the local jQuery script. /// - /// - /// The version string for the local jQuery script + /// + /// The version string for the local jQuery script /// /// /// @@ -257,7 +257,7 @@ public static string Version ver = Localization.GetString("jQuery.NotInstalled.Text"); } } - + return ver; } } @@ -265,8 +265,8 @@ public static string Version /// /// Gets the version string for the local jQuery UI script. /// - /// - /// The version string for the local jQuery UI script + /// + /// The version string for the local jQuery UI script /// /// /// @@ -293,11 +293,11 @@ public static string UIVersion ver = Localization.GetString("jQueryUI.NotInstalled.Text"); } } - + return ver; } - } - + } + [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryFileMapPath(bool getMinFile) { @@ -309,25 +309,6 @@ public static string JQueryUIFileMapPath(bool getMinFile) { return HttpContext.Current.Server.MapPath(JQueryUIFile(getMinFile)); } - - private static bool GetSettingAsBoolean(string key, bool defaultValue) - { - bool retValue = defaultValue; - try - { - object setting = HttpContext.Current.Items[key]; - if (setting != null) - { - retValue = Convert.ToBoolean(setting); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } - - return retValue; - } [Obsolete("This is managed through the JavaScript Library package. Scheduled removal in v10.0.0.")] public static string JQueryFile(bool getMinFile) @@ -337,7 +318,7 @@ public static string JQueryFile(bool getMinFile) { jfile = jQueryMinFile; } - + return jfile; } @@ -349,7 +330,7 @@ public static string JQueryMigrateFile(bool getMinFile) { jfile = jQueryMigrateMinFile; } - + return jfile; } @@ -361,7 +342,7 @@ public static string JQueryUIFile(bool getMinFile) { jfile = jQueryUIMinFile; } - + return jfile; } @@ -373,7 +354,7 @@ public static string GetJQueryScriptReference() { scriptsrc = JQueryFile(!UseDebugScript); } - + return scriptsrc; } @@ -385,7 +366,7 @@ public static string GetJQueryMigrateScriptReference() { scriptsrc = JQueryMigrateFile(!UseDebugScript); } - + return scriptsrc; } @@ -397,10 +378,10 @@ public static string GetJQueryUIScriptReference() { scriptsrc = JQueryUIFile(!UseDebugScript); } - + return scriptsrc; } - + /// /// Active the page with keep alive, so that authentication will not expire. /// @@ -417,14 +398,14 @@ public static void KeepAlive(Page page) { cookieTimeout = 5; // ping server in 5 minutes to make sure the server is not IDLE. } - + JavaScript.RequestRegistration(CommonJs.jQuery); var seconds = ((cookieTimeout * 60) - 30) * 1000; // ping server 30 seconds before cookie is time out. var scriptBlock = string.Format("(function($){{setInterval(function(){{$.get(location.href)}}, {1});}}(jQuery));", Globals.ApplicationPath, seconds); ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "PageKeepAlive", scriptBlock, true); - } - + } + [Obsolete("Obsoleted in 7.2.0 - registration occurs automatically during page load. Scheduled removal in v10.0.0.")] public static void RegisterJQuery(Page page) { @@ -481,7 +462,26 @@ public static void RequestDnnPluginsRegistration() public static void RequestHoverIntentRegistration() { JavaScript.RequestRegistration(CommonJs.HoverIntent); - } + } + + private static bool GetSettingAsBoolean(string key, bool defaultValue) + { + bool retValue = defaultValue; + try + { + object setting = HttpContext.Current.Items[key]; + if (setting != null) + { + retValue = Convert.ToBoolean(setting); + } + } + catch (Exception ex) + { + Exceptions.LogException(ex); + } + + return retValue; + } } #pragma warning restore 618 } diff --git a/DNN Platform/Library/Modules/HtmlEditorProvider.cs b/DNN Platform/Library/Modules/HtmlEditorProvider.cs index 6042cba16e0..1e468c62c1f 100644 --- a/DNN Platform/Library/Modules/HtmlEditorProvider.cs +++ b/DNN Platform/Library/Modules/HtmlEditorProvider.cs @@ -13,17 +13,17 @@ namespace DotNetNuke.Modules.HTMLEditorProvider public abstract class HtmlEditorProvider : UserControlBase { public abstract Control HtmlEditorControl { get; } - + public abstract ArrayList AdditionalToolbars { get; set; } - + public abstract string ControlID { get; set; } - + public abstract string RootImageDirectory { get; set; } - + public abstract string Text { get; set; } - + public abstract Unit Width { get; set; } - + public abstract Unit Height { get; set; } // return the provider diff --git a/DNN Platform/Library/Modules/NavigationProvider.cs b/DNN Platform/Library/Modules/NavigationProvider.cs index e64163d15da..1c5044aa663 100644 --- a/DNN Platform/Library/Modules/NavigationProvider.cs +++ b/DNN Platform/Library/Modules/NavigationProvider.cs @@ -11,55 +11,55 @@ namespace DotNetNuke.Modules.NavigationProvider using DotNetNuke.UI.WebControls; public abstract class NavigationProvider : UserControlBase - { + { public delegate void NodeClickEventHandler(NavigationEventArgs args); - public delegate void PopulateOnDemandEventHandler(NavigationEventArgs args); - + public delegate void PopulateOnDemandEventHandler(NavigationEventArgs args); + public event NodeClickEventHandler NodeClick; - + public event PopulateOnDemandEventHandler PopulateOnDemand; - + public enum Alignment { Left, Right, Center, Justify, - } - + } + public enum HoverAction { Expand, None, - } - + } + public enum HoverDisplay { Highlight, Outset, None, - } - + } + public enum Orientation { Horizontal, Vertical, - } - + } + public abstract Control NavigationControl { get; } - - public abstract string ControlID { get; set; } - + public abstract bool SupportsPopulateOnDemand { get; } + public abstract string ControlID { get; set; } + public virtual string PathImage { get { return string.Empty; } - + set { } @@ -71,7 +71,7 @@ public virtual string PathSystemImage { return string.Empty; } - + set { } @@ -83,7 +83,7 @@ public virtual string PathSystemScript { return string.Empty; } - + set { } @@ -95,7 +95,7 @@ public virtual string WorkImage { return string.Empty; } - + set { } @@ -107,7 +107,7 @@ public virtual string IndicateChildImageSub { return string.Empty; } - + set { } @@ -119,7 +119,7 @@ public virtual string IndicateChildImageRoot { return string.Empty; } - + set { } @@ -131,7 +131,7 @@ public virtual string IndicateChildImageExpandedSub { return string.Empty; } - + set { } @@ -143,7 +143,7 @@ public virtual string IndicateChildImageExpandedRoot { return string.Empty; } - + set { } @@ -157,7 +157,7 @@ public virtual string CSSContainerRoot { return string.Empty; } - + set { } @@ -169,7 +169,7 @@ public virtual string CSSContainerSub { return string.Empty; } - + set { } @@ -181,7 +181,7 @@ public virtual string CSSNode { return string.Empty; } - + set { } @@ -193,7 +193,7 @@ public virtual string CSSNodeRoot { return string.Empty; } - + set { } @@ -205,7 +205,7 @@ public virtual string CSSIcon { return string.Empty; } - + set { } @@ -217,7 +217,7 @@ public virtual string CSSNodeHover { return string.Empty; } - + set { } @@ -229,7 +229,7 @@ public virtual string CSSNodeHoverSub { return string.Empty; } - + set { } @@ -241,7 +241,7 @@ public virtual string CSSNodeHoverRoot { return string.Empty; } - + set { } @@ -253,7 +253,7 @@ public virtual string CSSBreak { return string.Empty; } - + set { } @@ -265,7 +265,7 @@ public virtual string CSSIndicateChildSub { return string.Empty; } - + set { } @@ -277,7 +277,7 @@ public virtual string CSSIndicateChildRoot { return string.Empty; } - + set { } @@ -289,7 +289,7 @@ public virtual string CSSBreadCrumbSub { return string.Empty; } - + set { } @@ -301,7 +301,7 @@ public virtual string CSSBreadCrumbRoot { return string.Empty; } - + set { } @@ -313,7 +313,7 @@ public virtual string CSSNodeSelectedSub { return string.Empty; } - + set { } @@ -325,7 +325,7 @@ public virtual string CSSNodeSelectedRoot { return string.Empty; } - + set { } @@ -337,7 +337,7 @@ public virtual string CSSSeparator { return string.Empty; } - + set { } @@ -349,7 +349,7 @@ public virtual string CSSLeftSeparator { return string.Empty; } - + set { } @@ -361,7 +361,7 @@ public virtual string CSSRightSeparator { return string.Empty; } - + set { } @@ -373,7 +373,7 @@ public virtual string CSSLeftSeparatorSelection { return string.Empty; } - + set { } @@ -385,7 +385,7 @@ public virtual string CSSRightSeparatorSelection { return string.Empty; } - + set { } @@ -397,7 +397,7 @@ public virtual string CSSLeftSeparatorBreadCrumb { return string.Empty; } - + set { } @@ -409,7 +409,7 @@ public virtual string CSSRightSeparatorBreadCrumb { return string.Empty; } - + set { } @@ -421,7 +421,7 @@ public virtual string StyleBackColor { return string.Empty; } - + set { } @@ -433,7 +433,7 @@ public virtual string StyleForeColor { return string.Empty; } - + set { } @@ -445,7 +445,7 @@ public virtual string StyleHighlightColor { return string.Empty; } - + set { } @@ -457,7 +457,7 @@ public virtual string StyleIconBackColor { return string.Empty; } - + set { } @@ -469,7 +469,7 @@ public virtual string StyleSelectionBorderColor { return string.Empty; } - + set { } @@ -481,7 +481,7 @@ public virtual string StyleSelectionColor { return string.Empty; } - + set { } @@ -493,7 +493,7 @@ public virtual string StyleSelectionForeColor { return string.Empty; } - + set { } @@ -505,7 +505,7 @@ public virtual decimal StyleControlHeight { return 25; } - + set { } @@ -517,7 +517,7 @@ public virtual decimal StyleBorderWidth { return 0; } - + set { } @@ -529,7 +529,7 @@ public virtual decimal StyleNodeHeight { return 25; } - + set { } @@ -541,7 +541,7 @@ public virtual decimal StyleIconWidth { return 0; } - + set { } @@ -553,7 +553,7 @@ public virtual string StyleFontNames { return string.Empty; } - + set { } @@ -565,7 +565,7 @@ public virtual decimal StyleFontSize { return 0; } - + set { } @@ -577,7 +577,7 @@ public virtual string StyleFontBold { return "False"; } - + set { } @@ -589,7 +589,7 @@ public virtual string StyleRoot { return string.Empty; } - + set { } @@ -601,7 +601,7 @@ public virtual string StyleSub { return string.Empty; } - + set { } @@ -613,7 +613,7 @@ public virtual string EffectsStyle { return string.Empty; } - + set { } @@ -625,7 +625,7 @@ public virtual string EffectsTransition { return "'"; } - + set { } @@ -637,7 +637,7 @@ public virtual double EffectsDuration { return -1; } - + set { } @@ -649,7 +649,7 @@ public virtual string EffectsShadowColor { return string.Empty; } - + set { } @@ -661,7 +661,7 @@ public virtual string EffectsShadowDirection { return string.Empty; } - + set { } @@ -673,7 +673,7 @@ public virtual int EffectsShadowStrength { return -1; } - + set { } @@ -685,7 +685,7 @@ public virtual Orientation ControlOrientation { return Orientation.Horizontal; } - + set { } @@ -697,7 +697,7 @@ public virtual Alignment ControlAlignment { return Alignment.Left; } - + set { } @@ -709,7 +709,7 @@ public virtual string ForceDownLevel { return false.ToString(); } - + set { } @@ -721,7 +721,7 @@ public virtual decimal MouseOutHideDelay { return -1; } - + set { } @@ -733,7 +733,7 @@ public virtual HoverDisplay MouseOverDisplay { return HoverDisplay.Highlight; } - + set { } @@ -745,7 +745,7 @@ public virtual HoverAction MouseOverAction { return HoverAction.Expand; } - + set { } @@ -757,7 +757,7 @@ public virtual string ForceCrawlerDisplay { return "False"; } - + set { } @@ -769,7 +769,7 @@ public virtual bool IndicateChildren { return true; } - + set { } @@ -781,7 +781,7 @@ public virtual string SeparatorHTML { return string.Empty; } - + set { } @@ -793,7 +793,7 @@ public virtual string SeparatorLeftHTML { return string.Empty; } - + set { } @@ -805,7 +805,7 @@ public virtual string SeparatorRightHTML { return string.Empty; } - + set { } @@ -817,7 +817,7 @@ public virtual string SeparatorLeftHTMLActive { return string.Empty; } - + set { } @@ -829,7 +829,7 @@ public virtual string SeparatorRightHTMLActive { return string.Empty; } - + set { } @@ -841,7 +841,7 @@ public virtual string SeparatorLeftHTMLBreadCrumb { return string.Empty; } - + set { } @@ -853,7 +853,7 @@ public virtual string SeparatorRightHTMLBreadCrumb { return string.Empty; } - + set { } @@ -865,7 +865,7 @@ public virtual string NodeLeftHTMLSub { return string.Empty; } - + set { } @@ -877,7 +877,7 @@ public virtual string NodeLeftHTMLRoot { return string.Empty; } - + set { } @@ -889,7 +889,7 @@ public virtual string NodeRightHTMLSub { return string.Empty; } - + set { } @@ -901,7 +901,7 @@ public virtual string NodeRightHTMLRoot { return string.Empty; } - + set { } @@ -913,7 +913,7 @@ public virtual string NodeLeftHTMLBreadCrumbSub { return string.Empty; } - + set { } @@ -925,7 +925,7 @@ public virtual string NodeRightHTMLBreadCrumbSub { return string.Empty; } - + set { } @@ -937,7 +937,7 @@ public virtual string NodeLeftHTMLBreadCrumbRoot { return string.Empty; } - + set { } @@ -949,7 +949,7 @@ public virtual string NodeRightHTMLBreadCrumbRoot { return string.Empty; } - + set { } @@ -961,7 +961,7 @@ public virtual bool PopulateNodesFromClient { return false; } - + set { } @@ -973,11 +973,11 @@ public virtual List CustomAttributes { return null; } - + set { } - } + } public static NavigationProvider Instance(string FriendlyName) { @@ -1022,7 +1022,7 @@ protected void RaiseEvent_PopulateOnDemand(string strID) { this.PopulateOnDemand(new NavigationEventArgs(strID, null)); } - } + } } public class NavigationEventArgs diff --git a/DNN Platform/Library/Obsolete/CBO.cs b/DNN Platform/Library/Obsolete/CBO.cs index e613be6f835..f8f4ae564c1 100644 --- a/DNN Platform/Library/Obsolete/CBO.cs +++ b/DNN Platform/Library/Obsolete/CBO.cs @@ -43,16 +43,16 @@ public static object CreateObject(Type objType, bool initialise) [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr) - where TItem : IHydratable + public static IDictionary FillDictionary(IDataReader dr) + where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, new Dictionary(), true); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Obsolete in DotNetNuke 7.3. Use FillDictionary(string keyField, IDataReader dr, IDictionary objDictionary). Scheduled removal in v10.0.0.")] - public static IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) - where TItem : IHydratable + public static IDictionary FillDictionary(IDataReader dr, ref IDictionary objToFill) + where TItem : IHydratable { return FillDictionaryFromReader("KeyID", dr, objToFill, true); } diff --git a/DNN Platform/Library/Obsolete/ModuleController.cs b/DNN Platform/Library/Obsolete/ModuleController.cs index d4a2ee97c8d..aba120d5782 100644 --- a/DNN Platform/Library/Obsolete/ModuleController.cs +++ b/DNN Platform/Library/Obsolete/ModuleController.cs @@ -72,7 +72,7 @@ public void DeleteTabModuleSettings(int tabModuleId) { dataProvider.DeleteTabModuleSettings(tabModuleId); UpdateTabModuleVersion(tabModuleId); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "TabModuleID", tabModuleId.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -111,7 +111,7 @@ public Hashtable GetModuleSettings(int ModuleId) // Ensure DataReader is closed CBO.CloseDataReader(dr, true); } - + return settings; } @@ -158,7 +158,7 @@ public Hashtable GetTabModuleSettings(int TabModuleId) { CBO.CloseDataReader(dr, true); } - + return settings; } } diff --git a/DNN Platform/Library/Obsolete/PortalAliasController.cs b/DNN Platform/Library/Obsolete/PortalAliasController.cs index e60ce140b61..2ba9318334f 100644 --- a/DNN Platform/Library/Obsolete/PortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/PortalAliasController.cs @@ -37,14 +37,21 @@ public static PortalAliasCollection GetPortalAliasLookup() 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) + { + return Instance.GetPortalAlias(httpAlias); + } + [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) { DataProvider.Instance().DeletePortalAlias(portalAliasId); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PortalAliasID", portalAliasId.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -75,13 +82,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 GetPortalAliasLookup(string httpAlias) - { - return Instance.GetPortalAlias(httpAlias); - } - [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in version 7.1. Replaced by PortalAliasController.Instance.UpdatePortalAlias. Scheduled removal in v10.0.0.")] public void UpdatePortalAliasInfo(PortalAliasInfo portalAlias) diff --git a/DNN Platform/Library/Obsolete/PortalController.cs b/DNN Platform/Library/Obsolete/PortalController.cs index 1015ad4d53a..32c38b793f7 100644 --- a/DNN Platform/Library/Obsolete/PortalController.cs +++ b/DNN Platform/Library/Obsolete/PortalController.cs @@ -36,14 +36,14 @@ 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, diff --git a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs index 3241202279d..be46863391e 100644 --- a/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs +++ b/DNN Platform/Library/Obsolete/PortalTemplateIOImpl.cs @@ -15,7 +15,7 @@ namespace DotNetNuke.Entities.Portals.Internal [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Deprecated in DotNetNuke 7.3.0. Use PortalTemplateIO. Scheduled removal in v10.0.0.")] public class PortalTemplateIOImpl : IPortalTemplateIO - { + { public IEnumerable EnumerateTemplates() { string path = Globals.HostMapPath; @@ -61,6 +61,6 @@ private static string CheckFilePath(string path) } return string.Empty; - } + } } } diff --git a/DNN Platform/Library/Obsolete/RoleController.cs b/DNN Platform/Library/Obsolete/RoleController.cs index 11f918160f0..0566474978e 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/TabController.cs b/DNN Platform/Library/Obsolete/TabController.cs index 227a9c568fb..4b167204821 100644 --- a/DNN Platform/Library/Obsolete/TabController.cs +++ b/DNN Platform/Library/Obsolete/TabController.cs @@ -132,7 +132,7 @@ public void MoveTab(TabInfo tab, TabMoveType type) this.MoveTabToParent(tab, siblingTabs.ElementAt(tabIndex - 1).TabID); break; } - + this.ClearCache(tab.PortalID); } } diff --git a/DNN Platform/Library/Obsolete/TestableModuleController.cs b/DNN Platform/Library/Obsolete/TestableModuleController.cs index 4370da78661..c2240bfa55a 100644 --- a/DNN Platform/Library/Obsolete/TestableModuleController.cs +++ b/DNN Platform/Library/Obsolete/TestableModuleController.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 DotNetNuke.Entities.Modules.Internal { using System; @@ -14,24 +13,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 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 UpdateModuleSetting(int moduleId, string settingName, string settingValue) + { + ModuleController.Instance.UpdateModuleSetting(moduleId, settingName, settingValue); } - - protected override Func GetFactory() + + public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) { - return () => new TestableModuleController(); + ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); } - public void UpdateTabModuleSetting(int tabModuleId, string settingName, string settingValue) - { - ModuleController.Instance.UpdateTabModuleSetting(tabModuleId, settingName, settingValue); + protected override Func GetFactory() + { + return () => new TestableModuleController(); } } } diff --git a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs index 3578b537a3f..09302f0c748 100644 --- a/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs +++ b/DNN Platform/Library/Obsolete/TestablePortalAliasController.cs @@ -23,11 +23,6 @@ public void DeletePortalAlias(PortalAliasInfo portalAlias) { PortalAliasController.Instance.DeletePortalAlias(portalAlias); } - - protected override Func GetFactory() - { - return () => new TestablePortalAliasController(); - } public PortalAliasInfo GetPortalAlias(string alias) { @@ -49,5 +44,10 @@ public void UpdatePortalAlias(PortalAliasInfo portalAlias) { PortalAliasController.Instance.UpdatePortalAlias(portalAlias); } + + protected override Func GetFactory() + { + return () => new TestablePortalAliasController(); + } } } diff --git a/DNN Platform/Library/Obsolete/TestableRoleController.cs b/DNN Platform/Library/Obsolete/TestableRoleController.cs index 9f31cd0f437..401441dade9 100644 --- a/DNN Platform/Library/Obsolete/TestableRoleController.cs +++ b/DNN Platform/Library/Obsolete/TestableRoleController.cs @@ -23,11 +23,6 @@ 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) { @@ -78,5 +73,10 @@ public void ClearRoleCache(int portalId) { RoleController.Instance.ClearRoleCache(portalId); } + + protected override Func GetFactory() + { + return () => new TestableRoleController(); + } } } diff --git a/DNN Platform/Library/Obsolete/TestableTabController.cs b/DNN Platform/Library/Obsolete/TestableTabController.cs index 89756458e56..6b3fb9a1e89 100644 --- a/DNN Platform/Library/Obsolete/TestableTabController.cs +++ b/DNN Platform/Library/Obsolete/TestableTabController.cs @@ -24,11 +24,6 @@ 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) { @@ -49,5 +44,10 @@ public void SaveTabUrl(TabUrlInfo tabUrl, int portalId, bool clearCache) { TabController.Instance.SaveTabUrl(tabUrl, portalId, clearCache); } + + protected override Func GetFactory() + { + return () => new TestableTabController(); + } } } diff --git a/DNN Platform/Library/Obsolete/TestableUserController.cs b/DNN Platform/Library/Obsolete/TestableUserController.cs index d0ed78714e8..ce30642b527 100644 --- a/DNN Platform/Library/Obsolete/TestableUserController.cs +++ b/DNN Platform/Library/Obsolete/TestableUserController.cs @@ -22,11 +22,6 @@ 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, @@ -41,5 +36,10 @@ public IList GetUsersBasicSearch(int portalId, int pageIndex, int page { return UserController.Instance.GetUsersBasicSearch(portalId, pageIndex, pageSize, sortColumn, sortAscending, propertyName, propertyValue); } + + protected override Func GetFactory() + { + return () => new TestableUserController(); + } } } diff --git a/DNN Platform/Library/Obsolete/UserController.cs b/DNN Platform/Library/Obsolete/UserController.cs index 0876bc8a48a..ff0bd4cbdcc 100644 --- a/DNN Platform/Library/Obsolete/UserController.cs +++ b/DNN Platform/Library/Obsolete/UserController.cs @@ -95,7 +95,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData } } } - + if (bContinue) { objUserInfo = new UserInfo @@ -121,7 +121,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData { objUserInfo.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); } - + if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) { objUserInfo.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); @@ -138,7 +138,7 @@ public static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeData { CBO.CloseDataReader(dr, closeDataReader); } - + return objUserInfo; } } diff --git a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs index 4c99f73016d..61365da2ca0 100644 --- a/DNN Platform/Library/Security/Cookies/AuthCookieController.cs +++ b/DNN Platform/Library/Security/Cookies/AuthCookieController.cs @@ -18,41 +18,36 @@ public class AuthCookieController : ServiceLocator( new CacheItemArgs(GetKey(cookieValue), (int)FormsAuthentication.Timeout.TotalMinutes, CacheItemPriority.AboveNormal), _ => CBO.Instance.FillObject(this._dataProvider.FindAuthCookie(cookieValue)), false); } - protected override Func GetFactory() - { - return () => new AuthCookieController(); - } - public void DeleteByValue(string cookieValue) { - if (string.IsNullOrEmpty(cookieValue)) - { - return; - } - - // keep in cache so hacking tries don't hit the database; it will expire automatically - // DataCache.ClearCache(GetKey(cookieValue)); + if (string.IsNullOrEmpty(cookieValue)) + { + return; + } + + // keep in cache so hacking tries don't hit the database; it will expire automatically + // DataCache.ClearCache(GetKey(cookieValue)); this._dataProvider.DeleteAuthCookie(cookieValue); } @@ -61,6 +56,11 @@ public void DeleteExpired(DateTime utcExpiredBefore) this._dataProvider.DeleteExpiredAuthCookies(utcExpiredBefore); } + protected override Func GetFactory() + { + return () => new AuthCookieController(); + } + private static string GetKey(string cookieValue) { return $"AuthCookie:{cookieValue}"; diff --git a/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs b/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs index 6d0b2156cd8..35c21329979 100644 --- a/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs +++ b/DNN Platform/Library/Security/Cookies/IAuthCookieController.cs @@ -9,11 +9,11 @@ namespace DotNetNuke.Security.Cookies public interface IAuthCookieController { void Update(string cookieValue, DateTime utcExpiry, int userId); - + PersistedAuthCookie Find(string cookieValue); - + void DeleteByValue(string cookieValue); - + void DeleteExpired(DateTime utcExpiredBefore); } } diff --git a/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs b/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs index c668f4c3084..14cbde1172a 100644 --- a/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs +++ b/DNN Platform/Library/Security/Cookies/PersistedAuthCookie.cs @@ -18,9 +18,9 @@ namespace DotNetNuke.Security.Cookies public class PersistedAuthCookie : IHydratable { public int CookieId { get; private set; } - + public string CookieValue { get; private set; } - + public DateTime ExpiresOn { get; private set; } // UTC public int KeyID diff --git a/DNN Platform/Library/Security/FIPSCompliant.cs b/DNN Platform/Library/Security/FIPSCompliant.cs index 448b502365f..ce872cd7960 100644 --- a/DNN Platform/Library/Security/FIPSCompliant.cs +++ b/DNN Platform/Library/Security/FIPSCompliant.cs @@ -108,17 +108,17 @@ 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."); - } + 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 fc055df9930..c0e35713111 100644 --- a/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/AspNetMembershipProvider.cs @@ -42,12 +42,12 @@ namespace DotNetNuke.Security.Membership /// ----------------------------------------------------------------------------- public class AspNetMembershipProvider : MembershipProvider { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetMembershipProvider)); + 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" }; - + private readonly IEnumerable _socialAuthProviders = new List() { "Facebook", "Google", "Twitter", "LiveID" }; + public override bool CanEditProviderProperties { get { return false; } @@ -56,7 +56,7 @@ public override bool CanEditProviderProperties public override int MaxInvalidPasswordAttempts { get { return System.Web.Security.Membership.MaxInvalidPasswordAttempts; } - + set { throw new NotSupportedException( @@ -67,7 +67,7 @@ public override int MaxInvalidPasswordAttempts public override int MinNonAlphanumericCharacters { get { return System.Web.Security.Membership.MinRequiredNonAlphanumericCharacters; } - + set { throw new NotSupportedException( @@ -78,7 +78,7 @@ public override int MinNonAlphanumericCharacters public override int MinPasswordLength { get { return System.Web.Security.Membership.MinRequiredPasswordLength; } - + set { throw new NotSupportedException( @@ -89,7 +89,7 @@ public override int MinPasswordLength public override int PasswordAttemptWindow { get { return System.Web.Security.Membership.PasswordAttemptWindow; } - + set { throw new NotSupportedException( @@ -111,7 +111,7 @@ public override PasswordFormat PasswordFormat return PasswordFormat.Clear; } } - + set { throw new NotSupportedException( @@ -122,7 +122,7 @@ public override PasswordFormat PasswordFormat public override bool PasswordResetEnabled { get { return System.Web.Security.Membership.EnablePasswordReset; } - + set { throw new NotSupportedException( @@ -133,7 +133,7 @@ public override bool PasswordResetEnabled public override bool PasswordRetrievalEnabled { get { return System.Web.Security.Membership.EnablePasswordRetrieval; } - + set { throw new NotSupportedException( @@ -144,7 +144,7 @@ public override bool PasswordRetrievalEnabled public override string PasswordStrengthRegularExpression { get { return System.Web.Security.Membership.PasswordStrengthRegularExpression; } - + set { throw new NotSupportedException( @@ -155,7 +155,7 @@ public override string PasswordStrengthRegularExpression public override bool RequiresQuestionAndAnswer { get { return System.Web.Security.Membership.RequiresQuestionAndAnswer; } - + set { throw new NotSupportedException( @@ -166,14 +166,14 @@ public override bool RequiresQuestionAndAnswer public override bool RequiresUniqueEmail { get { return System.Web.Security.Membership.Provider.RequiresUniqueEmail; } - + set { throw new NotSupportedException( "Provider properties for AspNetMembershipProvider must be set in web.config"); } - } - + } + public static ArrayList FillUserCollection(int portalId, IDataReader dr) { // Note: the DataReader returned from this method should contain 2 result sets. The first set @@ -186,7 +186,7 @@ public static ArrayList FillUserCollection(int portalId, IDataReader dr) { // fill business object UserInfo user = FillUserInfo(portalId, dr, false); - + // add to collection arrUsers.Add(user); } @@ -200,17 +200,17 @@ public static ArrayList FillUserCollection(int portalId, IDataReader dr) // close datareader CBO.CloseDataReader(dr, true); } - + 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). /// @@ -233,7 +233,7 @@ public override void ChangeUsername(int userId, string newUsername) Requires.NotNull("userId", userId); Requires.NotNullOrEmpty("newUsername", newUsername); - var userName = PortalSecurity.Instance.InputFilter( + var userName = PortalSecurity.Instance.InputFilter( newUsername, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | @@ -272,7 +272,7 @@ public override void ChangeUsername(int userId, string newUsername) this._dataProvider.ChangeUsername(userId, userName); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "userId", userId.ToString(), portalSettings, @@ -281,1719 +281,1719 @@ public override void ChangeUsername(int userId, string newUsername) DataCache.ClearCache(); } - - private static bool AutoUnlockUser(MembershipUser aspNetUser) - { - if (Host.AutoAccountUnlockDuration != 0) - { - if (aspNetUser.LastLockoutDate < DateTime.Now.AddMinutes(-1 * Host.AutoAccountUnlockDuration)) - { - // Unlock user in Data Store - if (aspNetUser.UnlockUser()) - { - return true; - } - } - } - - return false; - } - private static UserCreateStatus CreateMemberhipUser(UserInfo user) + /// ----------------------------------------------------------------------------- + /// + /// ChangePassword attempts to change the users password. + /// + /// + /// + /// The user to update. + /// The old password. + /// The new password. + /// A Boolean indicating success or failure. + /// ----------------------------------------------------------------------------- + public override bool ChangePassword(UserInfo user, string oldPassword, string newPassword) { - var portalSecurity = PortalSecurity.Instance; - string userName = portalSecurity.InputFilter( - user.Username, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - string email = portalSecurity.InputFilter( - user.Email, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - MembershipCreateStatus status; - if (MembershipProviderConfig.RequiresQuestionAndAnswer) + MembershipUser aspnetUser = GetMembershipUser(user); + + var m = new MembershipPasswordController(); + if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword)) { - System.Web.Security.Membership.CreateUser( - userName, - user.Membership.Password, - email, - user.Membership.PasswordQuestion, - user.Membership.PasswordAnswer, - true, - out status); + return false; } - else + + if (string.IsNullOrEmpty(oldPassword)) { - System.Web.Security.Membership.CreateUser( - userName, - user.Membership.Password, - email, - null, - null, - true, - out status); + aspnetUser.UnlockUser(); + oldPassword = aspnetUser.GetPassword(); } - - var createStatus = UserCreateStatus.Success; - switch (status) + + bool retValue = aspnetUser.ChangePassword(oldPassword, newPassword); + if (retValue && this.PasswordRetrievalEnabled && !this.RequiresQuestionAndAnswer) { - case MembershipCreateStatus.DuplicateEmail: - createStatus = UserCreateStatus.DuplicateEmail; - break; - case MembershipCreateStatus.DuplicateProviderUserKey: - createStatus = UserCreateStatus.DuplicateProviderUserKey; - break; - case MembershipCreateStatus.DuplicateUserName: - createStatus = UserCreateStatus.DuplicateUserName; - break; - case MembershipCreateStatus.InvalidAnswer: - createStatus = UserCreateStatus.InvalidAnswer; - break; - case MembershipCreateStatus.InvalidEmail: - createStatus = UserCreateStatus.InvalidEmail; - break; - case MembershipCreateStatus.InvalidPassword: - createStatus = UserCreateStatus.InvalidPassword; - break; - case MembershipCreateStatus.InvalidProviderUserKey: - createStatus = UserCreateStatus.InvalidProviderUserKey; - break; - case MembershipCreateStatus.InvalidQuestion: - createStatus = UserCreateStatus.InvalidQuestion; - break; - case MembershipCreateStatus.InvalidUserName: - createStatus = UserCreateStatus.InvalidUserName; - break; - case MembershipCreateStatus.ProviderError: - createStatus = UserCreateStatus.ProviderError; - break; - case MembershipCreateStatus.UserRejected: - createStatus = UserCreateStatus.UserRejected; - break; + string confirmPassword = aspnetUser.GetPassword(); + if (confirmPassword == newPassword) + { + user.Membership.Password = confirmPassword; + } + else + { + retValue = false; + } } - - return createStatus; + + return retValue; } - private static void DeleteMembershipUser(UserInfo user) + /// ----------------------------------------------------------------------------- + /// + /// ChangePasswordQuestionAndAnswer attempts to change the users password Question + /// and PasswordAnswer. + /// + /// + /// + /// The user to update. + /// The password. + /// The new password question. + /// The new password answer. + /// A Boolean indicating success or failure. + /// ----------------------------------------------------------------------------- + public override bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, + string passwordAnswer) { - try - { - System.Web.Security.Membership.DeleteUser(user.Username, true); - } - catch (Exception exc) + MembershipUser aspnetUser = GetMembershipUser(user); + if (password == Null.NullString) { - Logger.Error(exc); + password = aspnetUser.GetPassword(); } + + return aspnetUser.ChangePasswordQuestionAndAnswer(password, passwordQuestion, passwordAnswer); } - private UserCreateStatus CreateDNNUser(ref UserInfo user) + /// ----------------------------------------------------------------------------- + /// + /// CreateUser persists a User to the Data Store. + /// + /// + /// + /// The user to persist to the Data Store. + /// A UserCreateStatus enumeration indicating success or reason for failure. + /// ----------------------------------------------------------------------------- + public override UserCreateStatus CreateUser(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)); + UserCreateStatus createStatus = this.ValidateForProfanity(user); + string service = HttpContext.Current != null ? HttpContext.Current.Request.Params["state"] : string.Empty; - // Save the user password history - new MembershipPasswordController().IsPasswordInHistory(user.UserID, user.PortalID, user.Membership.Password); - } - catch (Exception ex) + if (createStatus == UserCreateStatus.AddUser) { - // Clear User (duplicate User information) - Exceptions.LogException(ex); - user = null; - createStatus = UserCreateStatus.ProviderError; + this.ValidateForDuplicateDisplayName(user, ref createStatus); } - - 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 - // contains the TotalRecords, that satisfy the filter, the second contains the page - // of data - var arrUsers = new ArrayList(); - try + if (createStatus == UserCreateStatus.AddUser) { - while (dr.Read()) + try { - // fill business object - UserInfo user = FillUserInfo(portalId, dr, false); - - // add to collection - arrUsers.Add(user); - } - - // Get the next result (containing the total) - dr.NextResult(); - - // Get the total no of records from the second result - totalRecords = Globals.GetTotalRecords(ref dr); - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); + // check if username exists in database for any portal + UserInfo objVerifyUser = this.GetUserByUserName(Null.NullInteger, user.Username); + if (objVerifyUser != null) + { + // DNN-4016 + // the username exists so we should now verify the password, DNN-4016 or check for oauth user authentication. + if (ValidateUser(user.Username, user.Membership.Password)) + { + // check if user exists for the portal specified + objVerifyUser = this.GetUserByUserName(user.PortalID, user.Username); + if (objVerifyUser != null) + { + if (objVerifyUser.PortalID == user.PortalID && (!user.IsSuperUser || user.PortalID == Null.NullInteger)) + { + createStatus = UserCreateStatus.UserAlreadyRegistered; + } + else + { + // SuperUser who is not part of portal + createStatus = UserCreateStatus.AddUserToPortal; + } + } + else + { + createStatus = UserCreateStatus.AddUserToPortal; + } + } + else + { + // not the same person - prevent registration + createStatus = UserCreateStatus.UsernameAlreadyExists; + } + } + else + { + // the user does not exist + createStatus = UserCreateStatus.AddUser; + } + + // If new user - add to aspnet membership + if (createStatus == UserCreateStatus.AddUser) + { + createStatus = CreateMemberhipUser(user); + } + + // If asp user has been successfully created or we are adding a existing user + // to a new portal + if (createStatus == UserCreateStatus.Success || createStatus == UserCreateStatus.AddUserToPortal) + { + // Create the DNN User Record + createStatus = this.CreateDNNUser(ref user); + if (createStatus == UserCreateStatus.Success) + { + // Persist the Profile to the Data Store + ProfileController.UpdateUserProfile(user); + } + } + } + catch (Exception exc) // an unexpected error occurred + { + Exceptions.LogException(exc); + createStatus = UserCreateStatus.UnexpectedError; + } } - - return arrUsers; + + return createStatus; } - private static IList FillUserList(int portalId, IDataReader dr) + /// ----------------------------------------------------------------------------- + /// + /// DeleteUser deletes a single User from the Data Store. + /// + /// + /// + /// The user to delete from the Data Store. + /// A Boolean indicating success or failure. + /// ----------------------------------------------------------------------------- + public override bool DeleteUser(UserInfo user) { - var users = new List(); + bool retValue = true; try { - while (dr.Read()) - { - // fill business object - UserInfo user = FillUserAndProfile(portalId, dr); - - // add to collection - users.Add(user); - } - } - catch (Exception exc) - { - Exceptions.LogException(exc); + this._dataProvider.DeleteUserFromPortal(user.UserID, user.PortalID); } - finally + catch (Exception ex) { - // close datareader - CBO.CloseDataReader(dr, true); + Exceptions.LogException(ex); + retValue = false; } - - return users; + + return retValue; } - private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) + /// ----------------------------------------------------------------------------- + /// + /// Deletes all UserOnline inof from the database that has activity outside of the + /// time window. + /// + /// + /// + /// Time Window in Minutes. + /// ----------------------------------------------------------------------------- + [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 override void DeleteUsersOnline(int timeWindow) { - UserInfo user = null; - bool bContinue = string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase); + this._dataProvider.DeleteUsersOnline(timeWindow); + } - // Ensure the data reader returned is valid - if (bContinue) - { - user = new UserInfo - { - PortalID = Null.SetNullInteger(dr["PortalID"]), - IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), - IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]), - UserID = Null.SetNullInteger(dr["UserID"]), - DisplayName = Null.SetNullString(dr["DisplayName"]), - Username = Null.SetNullString(dr["Username"]), - Email = Null.SetNullString(dr["Email"]), - AffiliateID = Null.SetNullInteger(dr["AffiliateID"]), - }; - user.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], user.AffiliateID)); + /// ----------------------------------------------------------------------------- + /// + /// Generates a new random password (Length = Minimum Length + 4). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public override string GeneratePassword() + { + return this.GeneratePassword(this.MinPasswordLength + 4); + } - UserController.GetUserMembership(user); - user.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); - if (!user.IsSuperUser) - { - user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); - } - - if (user.PortalID == Null.NullInteger) - { - user.PortalID = portalId; - } + /// ----------------------------------------------------------------------------- + /// + /// Generates a new random password. + /// + /// The length of password to generate. + /// A String. + /// ----------------------------------------------------------------------------- + public override string GeneratePassword(int length) + { + return System.Web.Security.Membership.GeneratePassword(length, this.MinNonAlphanumericCharacters); + } - var userProfile = new UserProfile(user); - userProfile.InitialiseProfile(portalId); + public override ArrayList GetDeletedUsers(int portalId) + { + return FillUserCollection(portalId, this._dataProvider.GetDeletedUsers(portalId)); + } - for (int i = 0; i < dr.FieldCount; i++) - { - switch (dr.GetName(i)) - { - case "PortalID": - case "IsSuperUser": - case "IsDeleted": - case "UserID": - case "DisplayName": - case "Username": - case "Email": - case "AffiliateID": - case "UpdatePassword": - case "Authorised": - case "CreateDate": - case "LastActivityDate": - case "LastLockoutDate": - case "LastLoginDate": - case "LastPasswordChangedDate": - case "IsLockedOut": - case "PasswordQuestion": - case "IsApproved": - case "PasswordResetToken": - case "PasswordResetExpiration": - break; - default: - // Probably a profile property - string name = dr.GetName(i); - userProfile.SetProfileProperty(name, Null.SetNullString(dr[name])); - break; - } - } + /// ----------------------------------------------------------------------------- + /// + /// Gets a collection of Online Users. + /// + /// The Id of the Portal. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + [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 override ArrayList GetOnlineUsers(int portalId) + { + int totalRecords = 0; + return FillUserCollection(portalId, this._dataProvider.GetOnlineUsers(portalId), ref totalRecords); + } - user.Profile = userProfile; + /// ----------------------------------------------------------------------------- + /// + /// Gets the Current Password Information for the User. + /// + /// + /// + /// The user to delete from the Data Store. + /// The answer to the Password Question, ues to confirm the user + /// has the right to obtain the password. + /// A String. + /// ----------------------------------------------------------------------------- + public override string GetPassword(UserInfo user, string passwordAnswer) + { + MembershipUser aspnetUser = GetMembershipUser(user); + if (aspnetUser.IsLockedOut) + { + AutoUnlockUser(aspnetUser); } - - return user; + + return this.RequiresQuestionAndAnswer ? aspnetUser.GetPassword(passwordAnswer) : aspnetUser.GetPassword(); } - private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDataReader) + public override ArrayList GetUnAuthorizedUsers(int portalId) { - UserInfo user = null; - try - { - // read datareader - bool bContinue = true; - if (closeDataReader) - { - bContinue = false; - if (dr.Read()) - { - // Ensure the data reader returned is valid - if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) - { - bContinue = true; - } - } - } - - if (bContinue) - { - user = new UserInfo - { - PortalID = Null.SetNullInteger(dr["PortalID"]), - IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), - UserID = Null.SetNullInteger(dr["UserID"]), - DisplayName = Null.SetNullString(dr["DisplayName"]), - LastIPAddress = Null.SetNullString(dr["LastIPAddress"]), - }; - - var schema = dr.GetSchemaTable(); - if (schema != null) - { - if (schema.Select("ColumnName = 'IsDeleted'").Length > 0) - { - user.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); - } - - if (schema.Select("ColumnName = 'VanityUrl'").Length > 0) - { - user.VanityUrl = Null.SetNullString(dr["VanityUrl"]); - } - - if (schema.Select("ColumnName = 'HasAgreedToTerms'").Length > 0) - { - user.HasAgreedToTerms = Null.SetNullBoolean(dr["HasAgreedToTerms"]); - } - - if (schema.Select("ColumnName = 'HasAgreedToTermsOn'").Length > 0) - { - user.HasAgreedToTermsOn = Null.SetNullDateTime(dr["HasAgreedToTermsOn"]); - } - else - { - user.HasAgreedToTermsOn = Null.NullDate; - } - - if (schema.Select("ColumnName = 'RequestsRemoval'").Length > 0) - { - user.RequestsRemoval = Null.SetNullBoolean(dr["RequestsRemoval"]); - } - - if (schema.Select("ColumnName = 'PasswordResetExpiration'").Length > 0) - { - user.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); - } - - if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) - { - user.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); - } - } - - user.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], user.AffiliateID)); - user.Username = Null.SetNullString(dr["Username"]); - UserController.GetUserMembership(user); - user.Email = Null.SetNullString(dr["Email"]); - user.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); - - if (!user.IsSuperUser) - { - user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); - } - - if (user.PortalID == Null.NullInteger) - { - user.PortalID = portalId; - } - - user.FillBaseProperties(dr); - } - } - finally - { - CBO.CloseDataReader(dr, closeDataReader); - } - - return user; + return this.GetUnAuthorizedUsers(portalId, false, false); } - private static void FillUserMembership(MembershipUser aspNetUser, UserInfo user) + public override ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) { - // Fill Membership Property - if (aspNetUser != null) - { - if (user.Membership == null) - { - user.Membership = new UserMembership(user); - } - - user.Membership.CreatedDate = aspNetUser.CreationDate; - user.Membership.LastActivityDate = aspNetUser.LastActivityDate; - user.Membership.LastLockoutDate = aspNetUser.LastLockoutDate; - user.Membership.LastLoginDate = aspNetUser.LastLoginDate; - user.Membership.LastPasswordChangeDate = aspNetUser.LastPasswordChangedDate; - user.Membership.LockedOut = aspNetUser.IsLockedOut; - user.Membership.PasswordQuestion = aspNetUser.PasswordQuestion; - user.Membership.IsDeleted = user.IsDeleted; - - if (user.IsSuperUser) - { - // For superusers the Approved info is stored in aspnet membership - user.Membership.Approved = aspNetUser.IsApproved; - } - } + return FillUserCollection( + portalId, + this._dataProvider.GetUnAuthorizedUsers(portalId, includeDeleted, superUsersOnly)); } - private static MembershipUser GetMembershipUser(UserInfo user) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByUserName 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 override UserInfo GetUser(int portalId, int userId) { - return GetMembershipUser(user.Username); + IDataReader dr = this._dataProvider.GetUser(portalId, userId); + UserInfo objUserInfo = FillUserInfo(portalId, dr, true); + return objUserInfo; } - private static MembershipUser GetMembershipUser(string userName) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByDisplayName retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The displayName of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public override UserInfo GetUserByDisplayName(int portalId, string displayName) { - return - CBO.GetCachedObject( - new CacheItemArgs(GetCacheKey(userName), DataCache.UserCacheTimeOut, DataCache.UserCachePriority, - userName), GetMembershipUserCallBack); + IDataReader dr = this._dataProvider.GetUserByDisplayName(portalId, displayName); + UserInfo objUserInfo = FillUserInfo(portalId, dr, true); + return objUserInfo; } - private static MembershipUser GetMembershipUserByUserKey(string userKey) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByUserName retrieves a User from the DataStore. Supports user caching in memory cache. + /// + /// + /// + /// The Id of the Portal. + /// The username of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public override UserInfo GetUserByUserName(int portalId, string username) { - return - CBO.GetCachedObject( - new CacheItemArgs(GetCacheKey(userKey), DataCache.UserCacheTimeOut, DataCache.UserCachePriority, - userKey), GetMembershipUserByUserKeyCallBack); + var objUserInfo = CBO.GetCachedObject( + new CacheItemArgs( + string.Format(DataCache.UserCacheKey, portalId, username), + DataCache.UserCacheTimeOut, DataCache.UserCachePriority), + _ => + { + return this.GetUserByUserNameFromDataStore(portalId, username); + }); + return objUserInfo; } - private static string GetCacheKey(string cacheKey) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByVanityUrl retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The vanityUrl of the user being retrieved from the Data Store. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public override UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) { - return $"MembershipUser_{cacheKey}"; + UserInfo user = null; + if (!string.IsNullOrEmpty(vanityUrl)) + { + IDataReader dr = this._dataProvider.GetUserByVanityUrl(portalId, vanityUrl); + user = FillUserInfo(portalId, dr, true); + } + + return user; } - private static object GetMembershipUserCallBack(CacheItemArgs cacheItemArgs) + /// ----------------------------------------------------------------------------- + /// + /// GetUserByPasswordResetToken retrieves a User from the DataStore. + /// + /// + /// + /// The Id of the Portal. + /// The password reset token. + /// The User as a UserInfo object. + /// ----------------------------------------------------------------------------- + public override UserInfo GetUserByPasswordResetToken(int portalId, string resetToken) { - string userName = cacheItemArgs.ParamList[0].ToString(); + UserInfo user = null; + if (!string.IsNullOrEmpty(resetToken)) + { + IDataReader dr = this._dataProvider.GetUserByPasswordResetToken(portalId, resetToken); + user = FillUserInfo(portalId, dr, true); + } - return System.Web.Security.Membership.GetUser(userName); + return user; } - private static object GetMembershipUserByUserKeyCallBack(CacheItemArgs cacheItemArgs) + public override string GetProviderUserKey(UserInfo user) { - string userKey = cacheItemArgs.ParamList[0].ToString(); - - return System.Web.Security.Membership.GetUser(new Guid(userKey)); + return GetMembershipUser(user).ProviderUserKey?.ToString().Replace("-", string.Empty) ?? string.Empty; } - private static void UpdateUserMembership(UserInfo user) + public override UserInfo GetUserByProviderUserKey(int portalId, string providerUserKey) { - var portalSecurity = PortalSecurity.Instance; - string email = portalSecurity.InputFilter( - user.Email, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - - // Persist the Membership Properties to the AspNet Data Store - MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); - membershipUser.Email = email; - membershipUser.LastActivityDate = DateTime.Now; - if (user.IsSuperUser) - { - membershipUser.IsApproved = user.Membership.Approved; - } - - try - { - System.Web.Security.Membership.UpdateUser(membershipUser); - } - catch (ProviderException ex) + var userName = GetMembershipUserByUserKey(providerUserKey)?.UserName ?? string.Empty; + if (string.IsNullOrEmpty(userName)) { - throw new Exception(Localization.GetExceptionMessage("UpdateUserMembershipFailed", "Asp.net membership update user failed."), ex); + return null; } - DataCache.RemoveCache(GetCacheKey(user.Username)); + return this.GetUserByUserName(portalId, userName); } - private static UserLoginStatus ValidateLogin(string username, string authType, UserInfo user, - UserLoginStatus loginStatus, string password, ref bool bValid, - int portalId) - { - if (loginStatus != UserLoginStatus.LOGIN_USERLOCKEDOUT && - (loginStatus != UserLoginStatus.LOGIN_USERNOTAPPROVED || user.IsInRole("Unverified Users"))) - { - if (authType == "DNN") - { - if (user.IsSuperUser) - { - if (ValidateUser(username, password)) - { - loginStatus = UserLoginStatus.LOGIN_SUPERUSER; - bValid = true; - } - } - else - { - if (ValidateUser(username, password)) - { - loginStatus = UserLoginStatus.LOGIN_SUCCESS; - bValid = true; - } - } - } - else - { - if (user.IsSuperUser) - { - loginStatus = UserLoginStatus.LOGIN_SUPERUSER; - bValid = true; - } - else - { - loginStatus = UserLoginStatus.LOGIN_SUCCESS; - bValid = true; - } - } - } - - return loginStatus; - } - - private static bool ValidateUser(string username, string password) - { - return System.Web.Security.Membership.ValidateUser(username, password); - } - - private string GetStringSetting(Hashtable settings, string settingKey) - { - return settings[settingKey] == null ? string.Empty : settings[settingKey].ToString(); - } - /// ----------------------------------------------------------------------------- /// - /// ChangePassword attempts to change the users password. + /// GetUserCountByPortal gets the number of users in the portal. /// /// /// - /// The user to update. - /// The old password. - /// The new password. - /// A Boolean indicating success or failure. + /// The Id of the Portal. + /// The no of users. /// ----------------------------------------------------------------------------- - public override bool ChangePassword(UserInfo user, string oldPassword, string newPassword) + public override int GetUserCountByPortal(int portalId) { - MembershipUser aspnetUser = GetMembershipUser(user); - - var m = new MembershipPasswordController(); - if (m.IsPasswordInHistory(user.UserID, user.PortalID, newPassword)) - { - return false; - } - - if (string.IsNullOrEmpty(oldPassword)) - { - aspnetUser.UnlockUser(); - oldPassword = aspnetUser.GetPassword(); - } - - bool retValue = aspnetUser.ChangePassword(oldPassword, newPassword); - if (retValue && this.PasswordRetrievalEnabled && !this.RequiresQuestionAndAnswer) - { - string confirmPassword = aspnetUser.GetPassword(); - if (confirmPassword == newPassword) - { - user.Membership.Password = confirmPassword; - } - else - { - retValue = false; - } - } - - return retValue; + return this._dataProvider.GetUserCountByPortal(portalId); } /// ----------------------------------------------------------------------------- /// - /// ChangePasswordQuestionAndAnswer attempts to change the users password Question - /// and PasswordAnswer. + /// GetUserMembership retrieves the UserMembership information from the Data Store. /// /// /// - /// The user to update. - /// The password. - /// The new password question. - /// The new password answer. - /// A Boolean indicating success or failure. + /// The user whose Membership information we are retrieving. /// ----------------------------------------------------------------------------- - public override bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, - string passwordAnswer) + public override void GetUserMembership(ref UserInfo user) { + // Get AspNet MembershipUser MembershipUser aspnetUser = GetMembershipUser(user); - if (password == Null.NullString) - { - password = aspnetUser.GetPassword(); - } - - return aspnetUser.ChangePasswordQuestionAndAnswer(password, passwordQuestion, passwordAnswer); + + // Fill Membership Property + FillUserMembership(aspnetUser, user); + + // Get Online Status + user.Membership.IsOnLine = this.IsUserOnline(user); } /// ----------------------------------------------------------------------------- /// - /// CreateUser persists a User to the Data Store. + /// GetUsers gets all the users of the portal. /// - /// - /// - /// The user to persist to the Data Store. - /// A UserCreateStatus enumeration indicating success or reason for failure. + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override UserCreateStatus CreateUser(ref UserInfo user) + public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords) { - UserCreateStatus createStatus = this.ValidateForProfanity(user); - string service = HttpContext.Current != null ? HttpContext.Current.Request.Params["state"] : string.Empty; - - if (createStatus == UserCreateStatus.AddUser) - { - this.ValidateForDuplicateDisplayName(user, ref createStatus); - } - - if (createStatus == UserCreateStatus.AddUser) - { - try - { - // check if username exists in database for any portal - UserInfo objVerifyUser = this.GetUserByUserName(Null.NullInteger, user.Username); - if (objVerifyUser != null) - { - // DNN-4016 - // the username exists so we should now verify the password, DNN-4016 or check for oauth user authentication. - if (ValidateUser(user.Username, user.Membership.Password)) - { - // check if user exists for the portal specified - objVerifyUser = this.GetUserByUserName(user.PortalID, user.Username); - if (objVerifyUser != null) - { - if (objVerifyUser.PortalID == user.PortalID && (!user.IsSuperUser || user.PortalID == Null.NullInteger)) - { - createStatus = UserCreateStatus.UserAlreadyRegistered; - } - else - { - // SuperUser who is not part of portal - createStatus = UserCreateStatus.AddUserToPortal; - } - } - else - { - createStatus = UserCreateStatus.AddUserToPortal; - } - } - else - { - // not the same person - prevent registration - createStatus = UserCreateStatus.UsernameAlreadyExists; - } - } - else - { - // the user does not exist - createStatus = UserCreateStatus.AddUser; - } - - // If new user - add to aspnet membership - if (createStatus == UserCreateStatus.AddUser) - { - createStatus = CreateMemberhipUser(user); - } - - // If asp user has been successfully created or we are adding a existing user - // to a new portal - if (createStatus == UserCreateStatus.Success || createStatus == UserCreateStatus.AddUserToPortal) - { - // Create the DNN User Record - createStatus = this.CreateDNNUser(ref user); - if (createStatus == UserCreateStatus.Success) - { - // Persist the Profile to the Data Store - ProfileController.UpdateUserProfile(user); - } - } - } - catch (Exception exc) // an unexpected error occurred - { - Exceptions.LogException(exc); - createStatus = UserCreateStatus.UnexpectedError; - } - } - - return createStatus; + return this.GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// DeleteUser deletes a single User from the Data Store. + /// GetUsers gets all the users of the portal. /// - /// - /// - /// The user to delete from the Data Store. - /// A Boolean indicating success or failure. + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include deleted users. + /// Only select super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override bool DeleteUser(UserInfo user) + public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords, + bool includeDeleted, bool superUsersOnly) { - bool retValue = true; - try - { - this._dataProvider.DeleteUserFromPortal(user.UserID, user.PortalID); - } - catch (Exception ex) + if (pageIndex == -1) { - Exceptions.LogException(ex); - retValue = false; + pageIndex = 0; + pageSize = int.MaxValue; } - - 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"]); + return FillUserCollection(portalId, this._dataProvider.GetAllUsers(portalId, pageIndex, pageSize, includeDeleted, + superUsersOnly), ref totalRecords); + } - // 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) + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public override IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, + int filterRoleId, int relationshipTypeId, + bool isAdmin, int pageIndex, int pageSize, + string sortColumn, + bool sortAscending, string propertyNames, + string propertyValues) { - 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; - } - } + return FillUserList( + portalId, + this._dataProvider.GetUsersAdvancedSearch(portalId, userId, filterUserId, filterRoleId, + relationshipTypeId, isAdmin, pageIndex, pageSize, + sortColumn, sortAscending, propertyNames, + propertyValues)); } - /// ----------------------------------------------------------------------------- /// - /// Deletes all UserOnline inof from the database that has activity outside of the - /// time window. + /// /// - /// - /// - /// Time Window in Minutes. - /// ----------------------------------------------------------------------------- - [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 override void DeleteUsersOnline(int timeWindow) + /// + /// + /// + /// + /// + /// + /// + /// + public override IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, + bool sortAscending, string propertyName, + string propertyValue) { - this._dataProvider.DeleteUsersOnline(timeWindow); + return FillUserList(portalId, this._dataProvider.GetUsersBasicSearch(portalId, pageIndex, pageSize, + sortColumn, sortAscending, propertyName, + propertyValue)); } /// ----------------------------------------------------------------------------- /// - /// Generates a new random password (Length = Minimum Length + 4). + /// GetUsersByEmail gets all the users of the portal whose email matches a provided + /// filter expression. /// - /// A String. + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The email address to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override string GeneratePassword() + public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, + ref int totalRecords) { - return this.GeneratePassword(this.MinPasswordLength + 4); + return this.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// Generates a new random password. + /// GetUsersByEmail gets all the users of the portal whose email matches a provided + /// filter expression. /// - /// The length of password to generate. - /// A String. + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The email address to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include deleted users. + /// Only select super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override string GeneratePassword(int length) + public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, + ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - return System.Web.Security.Membership.GeneratePassword(length, this.MinNonAlphanumericCharacters); - } + if (pageIndex == -1) + { + pageIndex = 0; + pageSize = int.MaxValue; + } - public override ArrayList GetDeletedUsers(int portalId) - { - return FillUserCollection(portalId, this._dataProvider.GetDeletedUsers(portalId)); + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, + includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// - /// Gets a collection of Online Users. + /// GetUsersByUserName gets all the users of the portal whose username matches a provided + /// filter expression. /// + /// If all records are required, (ie no paging) set pageSize = -1. /// The Id of the Portal. + /// The username to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - [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 override ArrayList GetOnlineUsers(int portalId) + public override ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, + ref int totalRecords) { - int totalRecords = 0; - return FillUserCollection(portalId, this._dataProvider.GetOnlineUsers(portalId), ref totalRecords); + return this.GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// Gets the Current Password Information for the User. + /// GetUsersByUserName gets all the users of the portal whose username matches a provided + /// filter expression. /// - /// - /// - /// The user to delete from the Data Store. - /// The answer to the Password Question, ues to confirm the user - /// has the right to obtain the password. - /// A String. + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The username to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include deleted users. + /// Only select super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override string GetPassword(UserInfo user, string passwordAnswer) + public override ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, + ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - MembershipUser aspnetUser = GetMembershipUser(user); - if (aspnetUser.IsLockedOut) + if (pageIndex == -1) { - AutoUnlockUser(aspnetUser); + pageIndex = 0; + pageSize = int.MaxValue; } - - return this.RequiresQuestionAndAnswer ? aspnetUser.GetPassword(passwordAnswer) : aspnetUser.GetPassword(); - } - public override ArrayList GetUnAuthorizedUsers(int portalId) - { - return this.GetUnAuthorizedUsers(portalId, false, false); + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByUsername(portalId, userNameToMatch, pageIndex, pageSize, + includeDeleted, superUsersOnly), ref totalRecords); } - public override ArrayList GetUnAuthorizedUsers(int portalId, bool includeDeleted, bool superUsersOnly) + /// ----------------------------------------------------------------------------- + /// + /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided + /// filter expression. + /// + /// If all records are required, (ie no paging) set pageSize = -1. + /// The Id of the Portal. + /// The display name to use to find a match. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include deleted users. + /// Only select super users. + /// An ArrayList of UserInfo objects. + /// ----------------------------------------------------------------------------- + public override ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, + ref int totalRecords, bool includeDeleted, bool superUsersOnly) { - return FillUserCollection( + if (pageIndex == -1) + { + pageIndex = 0; + pageSize = int.MaxValue; + } + + return FillUserCollection( portalId, - this._dataProvider.GetUnAuthorizedUsers(portalId, includeDeleted, superUsersOnly)); + this._dataProvider.GetUsersByDisplayname(portalId, nameToMatch, pageIndex, pageSize, + includeDeleted, superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore. + /// GetUsersByProfileProperty gets all the users of the portal whose profile matches + /// the profile property pased as a parameter. /// /// /// /// The Id of the Portal. - /// The id of the user being retrieved from the Data Store. - /// The User as a UserInfo object. + /// The name of the property being matched. + /// The value of the property being matched. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override UserInfo GetUser(int portalId, int userId) + public override ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, + int pageIndex, int pageSize, ref int totalRecords) { - IDataReader dr = this._dataProvider.GetUser(portalId, userId); - UserInfo objUserInfo = FillUserInfo(portalId, dr, true); - return objUserInfo; + return this.GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, + ref totalRecords, false, false); } /// ----------------------------------------------------------------------------- /// - /// GetUserByDisplayName retrieves a User from the DataStore. + /// GetUsersByProfileProperty gets all the users of the portal whose profile matches + /// the profile property pased as a parameter. /// /// /// /// The Id of the Portal. - /// The displayName of the user being retrieved from the Data Store. - /// The User as a UserInfo object. + /// The name of the property being matched. + /// The value of the property being matched. + /// The page of records to return. + /// The size of the page. + /// The total no of records that satisfy the criteria. + /// Include deleted users. + /// Only select super users. + /// An ArrayList of UserInfo objects. /// ----------------------------------------------------------------------------- - public override UserInfo GetUserByDisplayName(int portalId, string displayName) + public override ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, + int pageIndex, int pageSize, ref int totalRecords, + bool includeDeleted, bool superUsersOnly) { - IDataReader dr = this._dataProvider.GetUserByDisplayName(portalId, displayName); - UserInfo objUserInfo = FillUserInfo(portalId, dr, true); - return objUserInfo; + if (pageIndex == -1) + { + pageIndex = 0; + pageSize = int.MaxValue; + } + + return FillUserCollection( + portalId, + this._dataProvider.GetUsersByProfileProperty(portalId, propertyName, propertyValue, + pageIndex, pageSize, includeDeleted, + superUsersOnly), ref totalRecords); } /// ----------------------------------------------------------------------------- /// - /// GetUserByUserName retrieves a User from the DataStore. Supports user caching in memory cache. + /// Gets whether the user in question is online. /// /// /// - /// The Id of the Portal. - /// The username of the user being retrieved from the Data Store. - /// The User as a UserInfo object. + /// The user. + /// A Boolean indicating whether the user is online. /// ----------------------------------------------------------------------------- - public override UserInfo GetUserByUserName(int portalId, string username) + [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 override bool IsUserOnline(UserInfo user) { - var objUserInfo = CBO.GetCachedObject( - new CacheItemArgs( - string.Format(DataCache.UserCacheKey, portalId, username), - DataCache.UserCacheTimeOut, DataCache.UserCachePriority), - _ => + bool isOnline = false; + var objUsersOnline = new UserOnlineController(); + if (objUsersOnline.IsEnabled()) + { + Hashtable userList = objUsersOnline.GetUserList(); + var onlineUser = (OnlineUserInfo)userList[user.UserID.ToString()]; + if (onlineUser != null) { - return this.GetUserByUserNameFromDataStore(portalId, username); - }); - return objUserInfo; + isOnline = true; + } + else + { + // Next try the Database + onlineUser = CBO.FillObject(this._dataProvider.GetOnlineUser(user.UserID)); + if (onlineUser != null) + { + isOnline = true; + } + } + } + + return isOnline; } - /// ----------------------------------------------------------------------------- - /// - /// GetUserByVanityUrl retrieves a User from the DataStore. - /// - /// - /// - /// The Id of the Portal. - /// The vanityUrl of the user being retrieved from the Data Store. - /// The User as a UserInfo object. - /// ----------------------------------------------------------------------------- - public override UserInfo GetUserByVanityUrl(int portalId, string vanityUrl) + public override bool RemoveUser(UserInfo user) { - UserInfo user = null; - if (!string.IsNullOrEmpty(vanityUrl)) + bool retValue = true; + + try { - IDataReader dr = this._dataProvider.GetUserByVanityUrl(portalId, vanityUrl); - user = FillUserInfo(portalId, dr, true); + foreach (var relationship in user.Social.UserRelationships) + { + RelationshipController.Instance.DeleteUserRelationship(relationship); + } + + this._dataProvider.RemoveUser(user.UserID, user.PortalID); + + // Prior to removing membership, ensure user is not present in any other portal + UserInfo otherUser = this.GetUserByUserNameFromDataStore(Null.NullInteger, user.Username); + if (otherUser == null) + { + DeleteMembershipUser(user); + } } - - return user; + catch (Exception ex) + { + Exceptions.LogException(ex); + retValue = false; + } + + return retValue; } /// ----------------------------------------------------------------------------- /// - /// GetUserByPasswordResetToken retrieves a User from the DataStore. + /// ResetPassword resets a user's password and returns the newly created password. /// /// /// - /// The Id of the Portal. - /// The password reset token. - /// The User as a UserInfo object. + /// The user to update. + /// The answer to the user's password Question. + /// The new Password. /// ----------------------------------------------------------------------------- - public override UserInfo GetUserByPasswordResetToken(int portalId, string resetToken) + public override string ResetPassword(UserInfo user, string passwordAnswer) { - UserInfo user = null; - if (!string.IsNullOrEmpty(resetToken)) - { - IDataReader dr = this._dataProvider.GetUserByPasswordResetToken(portalId, resetToken); - user = FillUserInfo(portalId, dr, true); - } - - return user; + // Get AspNet MembershipUser + MembershipUser aspnetUser = GetMembershipUser(user); + + return this.RequiresQuestionAndAnswer ? aspnetUser.ResetPassword(passwordAnswer) : aspnetUser.ResetPassword(); } - public override string GetProviderUserKey(UserInfo user) + /// + /// function sets user specific password reset token and timeout + /// works for all PasswordFormats as it resets and then changes the password + /// so old password is not required + /// method does not support RequiresQuestionAndAnswer. + /// + /// + /// + public override bool ResetAndChangePassword(UserInfo user, string newPassword) { - return GetMembershipUser(user).ProviderUserKey?.ToString().Replace("-", string.Empty) ?? string.Empty; + return this.ResetAndChangePassword(user, newPassword, string.Empty); } - public override UserInfo GetUserByProviderUserKey(int portalId, string providerUserKey) + public override bool ResetAndChangePassword(UserInfo user, string newPassword, string answer) { - var userName = GetMembershipUserByUserKey(providerUserKey)?.UserName ?? string.Empty; - if (string.IsNullOrEmpty(userName)) + if (this.RequiresQuestionAndAnswer && string.IsNullOrEmpty(answer)) { - return null; + return false; } - return this.GetUserByUserName(portalId, userName); + // Get AspNet MembershipUser + MembershipUser aspnetUser = GetMembershipUser(user); + if (aspnetUser.IsLockedOut) + { + aspnetUser.UnlockUser(); + } + + string resetPassword = this.ResetPassword(user, answer); + return aspnetUser.ChangePassword(resetPassword, newPassword); } - /// ----------------------------------------------------------------------------- - /// - /// GetUserCountByPortal gets the number of users in the portal. - /// - /// - /// - /// The Id of the Portal. - /// The no of users. - /// ----------------------------------------------------------------------------- - public override int GetUserCountByPortal(int portalId) + public override bool RestoreUser(UserInfo user) { - return this._dataProvider.GetUserCountByPortal(portalId); + bool retValue = true; + + try + { + this._dataProvider.RestoreUser(user.UserID, user.PortalID); + } + catch (Exception ex) + { + Exceptions.LogException(ex); + retValue = false; + } + + return retValue; } /// ----------------------------------------------------------------------------- /// - /// GetUserMembership retrieves the UserMembership information from the Data Store. + /// Unlocks the User's Account. /// /// /// - /// The user whose Membership information we are retrieving. + /// The user whose account is being Unlocked. + /// True if successful, False if unsuccessful. /// ----------------------------------------------------------------------------- - public override void GetUserMembership(ref UserInfo user) + public override bool UnLockUser(UserInfo user) { - // Get AspNet MembershipUser - MembershipUser aspnetUser = GetMembershipUser(user); - - // Fill Membership Property - FillUserMembership(aspnetUser, user); + MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); + bool retValue = false; + if (membershipUser != null) + { + retValue = membershipUser.UnlockUser(); + } - // Get Online Status - user.Membership.IsOnLine = this.IsUserOnline(user); + DataCache.RemoveCache(GetCacheKey(user.Username)); + return retValue; } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal. + /// User has agreed to terms and conditions for the portal. /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. + /// + /// + /// The agreeing user. /// ----------------------------------------------------------------------------- - public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords) + public override void UserAgreedToTerms(UserInfo user) { - return this.GetUsers(portalId, pageIndex, pageSize, ref totalRecords, false, false); + this._dataProvider.UserAgreedToTerms(PortalController.GetEffectivePortalId(user.PortalID), user.UserID); } /// ----------------------------------------------------------------------------- /// - /// GetUsers gets all the users of the portal. + /// Reset all agreements on portal so all users need to agree again at next login. /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include deleted users. - /// Only select super users. - /// An ArrayList of UserInfo objects. + /// + /// + /// Portal for which to reset agreements. /// ----------------------------------------------------------------------------- - public override ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords, - bool includeDeleted, bool superUsersOnly) + public override void ResetTermsAgreement(int portalId) { - if (pageIndex == -1) - { - pageIndex = 0; - pageSize = int.MaxValue; - } - - return FillUserCollection(portalId, this._dataProvider.GetAllUsers(portalId, pageIndex, pageSize, includeDeleted, - superUsersOnly), ref totalRecords); + this._dataProvider.ResetTermsAgreement(portalId); } /// - /// + /// Sets a boolean on the user portal to indicate this user has requested that their account be deleted. /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override IList GetUsersAdvancedSearch(int portalId, int userId, int filterUserId, - int filterRoleId, int relationshipTypeId, - bool isAdmin, int pageIndex, int pageSize, - string sortColumn, - bool sortAscending, string propertyNames, - string propertyValues) + /// User requesting removal. + /// True if user requests removal, false if the value needs to be reset. + public override void UserRequestsRemoval(UserInfo user, bool remove) { - return FillUserList( - portalId, - this._dataProvider.GetUsersAdvancedSearch(portalId, userId, filterUserId, filterRoleId, - relationshipTypeId, isAdmin, pageIndex, pageSize, - sortColumn, sortAscending, propertyNames, - propertyValues)); + this._dataProvider.UserRequestsRemoval(user.PortalID, user.UserID, remove); } + /// ----------------------------------------------------------------------------- /// - /// + /// UpdateUser persists a user to the Data Store. /// - /// - /// - /// - /// - /// - /// - /// - /// - public override IList GetUsersBasicSearch(int portalId, int pageIndex, int pageSize, string sortColumn, - bool sortAscending, string propertyName, - string propertyValue) - { - return FillUserList(portalId, this._dataProvider.GetUsersBasicSearch(portalId, pageIndex, pageSize, - sortColumn, sortAscending, propertyName, - propertyValue)); + /// + /// + /// The user to persist to the Data Store. + /// ----------------------------------------------------------------------------- + public override void UpdateUser(UserInfo user) + { + var objSecurity = PortalSecurity.Instance; + string firstName = objSecurity.InputFilter( + user.FirstName, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + string lastName = objSecurity.InputFilter( + user.LastName, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + string email = objSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + string displayName = objSecurity.InputFilter( + user.DisplayName, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + if (displayName.Contains("<")) + { + displayName = HttpUtility.HtmlEncode(displayName); + } + + if (!firstName.Equals(user.FirstName)) + { + user.FirstName = firstName; + } + + if (!lastName.Equals(user.LastName)) + { + user.LastName = lastName; + } + + bool updatePassword = user.Membership.UpdatePassword; + bool isApproved = user.Membership.Approved; + if (string.IsNullOrEmpty(displayName)) + { + displayName = firstName + " " + lastName; + } + + // Persist the Membership to the Data Store + UpdateUserMembership(user); + + // Persist the DNN User to the Database + this._dataProvider.UpdateUser( + user.UserID, + user.PortalID, + firstName, + lastName, + user.IsSuperUser, + email, + displayName, + user.VanityUrl, + updatePassword, + isApproved, + false, + user.LastIPAddress, + user.PasswordResetToken, + user.PasswordResetExpiration, + user.IsDeleted, + UserController.Instance.GetCurrentUserInfo().UserID); + + // Persist the Profile to the Data Store + ProfileController.UpdateUserProfile(user); } /// ----------------------------------------------------------------------------- /// - /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression. + /// Updates UserOnline info + /// time window. /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The email address to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. + /// List of users to update. /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, - ref int totalRecords) + [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 override void UpdateUsersOnline(Hashtable userList) { - return this.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, ref totalRecords, false, false); + this._dataProvider.UpdateUsersOnline(userList); } /// ----------------------------------------------------------------------------- /// - /// GetUsersByEmail gets all the users of the portal whose email matches a provided - /// filter expression. + /// UserLogin attempts to log the user in, and returns the User if successful. /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The email address to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include deleted users. - /// Only select super users. - /// An ArrayList of UserInfo objects. + /// + /// + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in. + /// The verification code of the User attempting to log in. + /// An enumerated value indicating the login status. + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, - ref int totalRecords, bool includeDeleted, bool superUsersOnly) + public override UserInfo UserLogin(int portalId, string username, string password, string verificationCode, + ref UserLoginStatus loginStatus) { - if (pageIndex == -1) - { - pageIndex = 0; - pageSize = int.MaxValue; - } - - return FillUserCollection( - portalId, - this._dataProvider.GetUsersByEmail(portalId, emailToMatch, pageIndex, pageSize, - includeDeleted, superUsersOnly), ref totalRecords); + return this.UserLogin(portalId, username, password, "DNN", verificationCode, ref loginStatus); } /// ----------------------------------------------------------------------------- /// - /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression. + /// UserLogin attempts to log the user in, and returns the User if successful. /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The username to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. + /// + /// + /// The Id of the Portal the user belongs to. + /// The user name of the User attempting to log in. + /// The password of the User attempting to log in (may not be used by all Auth types). + /// The type of Authentication Used. + /// The verification code of the User attempting to log in. + /// An enumerated value indicating the login status. + /// The User as a UserInfo object. /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, - ref int totalRecords) + public override UserInfo UserLogin(int portalId, string username, string password, string authType, + string verificationCode, ref UserLoginStatus loginStatus) { - return this.GetUsersByUserName(portalId, userNameToMatch, pageIndex, pageSize, ref totalRecords, false, false); + // For now, we are going to ignore the possibility that the User may exist in the + // Global Data Store but not in the Local DataStore ie. A shared Global Data Store + + // Initialise Login Status to Failure + loginStatus = UserLoginStatus.LOGIN_FAILURE; + + DataCache.ClearUserCache(portalId, username); + DataCache.ClearCache(GetCacheKey(username)); + + // Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary + UserInfo user = (authType == "DNN") + ? this.GetUserByUserName(portalId, username) + : this.GetUserByAuthToken(portalId, verificationCode, authType); + if (user != null && !user.IsDeleted) + { + // Get AspNet MembershipUser + MembershipUser aspnetUser = GetMembershipUser(user); + + // Fill Membership Property from AspNet MembershipUser + FillUserMembership(aspnetUser, user); + + // Check if the User is Locked Out (and unlock if AutoUnlock has expired) + if (aspnetUser.IsLockedOut) + { + if (AutoUnlockUser(aspnetUser)) + { + // Unlock User + user.Membership.LockedOut = false; + } + else + { + loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT; + } + } + + // Check in a verified situation whether the user is Approved + if (user.Membership.Approved == false && user.IsSuperUser == false) + { + // Check Verification code (skip for FB, Google, Twitter, LiveID as it has no verification code) + if (this._socialAuthProviders.Contains(authType) && string.IsNullOrEmpty(verificationCode)) + { + if (PortalController.Instance.GetCurrentPortalSettings().UserRegistration == + (int)Globals.PortalRegistrationType.PublicRegistration) + { + user.Membership.Approved = true; + UserController.UpdateUser(portalId, user); + UserController.ApproveUser(user); + } + else + { + loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; + } + } + else + { + var ps = PortalSecurity.Instance; + if (verificationCode == ps.Encrypt(Config.GetDecryptionkey(), portalId + "-" + user.UserID)) + { + UserController.ApproveUser(user); + } + else + { + loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; + } + } + } + + // Verify User Credentials + bool bValid = false; + loginStatus = ValidateLogin(username, authType, user, loginStatus, password, ref bValid, portalId); + if (!bValid) + { + // Clear the user object + user = null; + + // Clear cache for user so that locked out & other status could be updated + DataCache.ClearUserCache(portalId, username); + DataCache.ClearCache(GetCacheKey(username)); + + aspnetUser = System.Web.Security.Membership.GetUser(username); + + // If user has been locked out for current invalid attempt + // return locked out status + if (aspnetUser.IsLockedOut) + { + loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT; + } + } + } + else + { + // Clear the user object + user = null; + } + + return user; } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByUserName gets all the users of the portal whose username matches a provided - /// filter expression. - /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The username to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include deleted users. - /// Only select super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, - ref int totalRecords, bool includeDeleted, bool superUsersOnly) + private static bool AutoUnlockUser(MembershipUser aspNetUser) { - if (pageIndex == -1) + if (Host.AutoAccountUnlockDuration != 0) + { + if (aspNetUser.LastLockoutDate < DateTime.Now.AddMinutes(-1 * Host.AutoAccountUnlockDuration)) + { + // Unlock user in Data Store + if (aspNetUser.UnlockUser()) + { + return true; + } + } + } + + return false; + } + + private static UserCreateStatus CreateMemberhipUser(UserInfo user) + { + var portalSecurity = PortalSecurity.Instance; + string userName = portalSecurity.InputFilter( + user.Username, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + string email = portalSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + MembershipCreateStatus status; + if (MembershipProviderConfig.RequiresQuestionAndAnswer) + { + System.Web.Security.Membership.CreateUser( + userName, + user.Membership.Password, + email, + user.Membership.PasswordQuestion, + user.Membership.PasswordAnswer, + true, + out status); + } + else + { + System.Web.Security.Membership.CreateUser( + userName, + user.Membership.Password, + email, + null, + null, + true, + out status); + } + + var createStatus = UserCreateStatus.Success; + switch (status) + { + case MembershipCreateStatus.DuplicateEmail: + createStatus = UserCreateStatus.DuplicateEmail; + break; + case MembershipCreateStatus.DuplicateProviderUserKey: + createStatus = UserCreateStatus.DuplicateProviderUserKey; + break; + case MembershipCreateStatus.DuplicateUserName: + createStatus = UserCreateStatus.DuplicateUserName; + break; + case MembershipCreateStatus.InvalidAnswer: + createStatus = UserCreateStatus.InvalidAnswer; + break; + case MembershipCreateStatus.InvalidEmail: + createStatus = UserCreateStatus.InvalidEmail; + break; + case MembershipCreateStatus.InvalidPassword: + createStatus = UserCreateStatus.InvalidPassword; + break; + case MembershipCreateStatus.InvalidProviderUserKey: + createStatus = UserCreateStatus.InvalidProviderUserKey; + break; + case MembershipCreateStatus.InvalidQuestion: + createStatus = UserCreateStatus.InvalidQuestion; + break; + case MembershipCreateStatus.InvalidUserName: + createStatus = UserCreateStatus.InvalidUserName; + break; + case MembershipCreateStatus.ProviderError: + createStatus = UserCreateStatus.ProviderError; + break; + case MembershipCreateStatus.UserRejected: + createStatus = UserCreateStatus.UserRejected; + break; + } + + return createStatus; + } + + private static void DeleteMembershipUser(UserInfo user) + { + try + { + System.Web.Security.Membership.DeleteUser(user.Username, true); + } + catch (Exception exc) + { + Logger.Error(exc); + } + } + + 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 + // 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); + } + + // Get the next result (containing the total) + dr.NextResult(); + + // Get the total no of records from the second result + totalRecords = Globals.GetTotalRecords(ref dr); + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally { - pageIndex = 0; - pageSize = int.MaxValue; + // close datareader + CBO.CloseDataReader(dr, true); } - return FillUserCollection( - portalId, - this._dataProvider.GetUsersByUsername(portalId, userNameToMatch, pageIndex, pageSize, - includeDeleted, superUsersOnly), ref totalRecords); + return arrUsers; } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByDisplayName gets all the users of the portal whose display name matches a provided - /// filter expression. - /// - /// If all records are required, (ie no paging) set pageSize = -1. - /// The Id of the Portal. - /// The display name to use to find a match. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include deleted users. - /// Only select super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByDisplayName(int portalId, string nameToMatch, int pageIndex, int pageSize, - ref int totalRecords, bool includeDeleted, bool superUsersOnly) + private static IList FillUserList(int portalId, IDataReader dr) { - if (pageIndex == -1) + var users = new List(); + try { - pageIndex = 0; - pageSize = int.MaxValue; + while (dr.Read()) + { + // fill business object + UserInfo user = FillUserAndProfile(portalId, dr); + + // add to collection + users.Add(user); + } + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); } - return FillUserCollection( - portalId, - this._dataProvider.GetUsersByDisplayname(portalId, nameToMatch, pageIndex, pageSize, - includeDeleted, superUsersOnly), ref totalRecords); + return users; } - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter. - /// - /// - /// - /// The Id of the Portal. - /// The name of the property being matched. - /// The value of the property being matched. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, - int pageIndex, int pageSize, ref int totalRecords) + private static UserInfo FillUserAndProfile(int portalId, IDataReader dr) { - return this.GetUsersByProfileProperty(portalId, propertyName, propertyValue, pageIndex, pageSize, - ref totalRecords, false, false); - } + UserInfo user = null; + bool bContinue = string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase); - /// ----------------------------------------------------------------------------- - /// - /// GetUsersByProfileProperty gets all the users of the portal whose profile matches - /// the profile property pased as a parameter. - /// - /// - /// - /// The Id of the Portal. - /// The name of the property being matched. - /// The value of the property being matched. - /// The page of records to return. - /// The size of the page. - /// The total no of records that satisfy the criteria. - /// Include deleted users. - /// Only select super users. - /// An ArrayList of UserInfo objects. - /// ----------------------------------------------------------------------------- - public override ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, - int pageIndex, int pageSize, ref int totalRecords, - bool includeDeleted, bool superUsersOnly) - { - if (pageIndex == -1) + // Ensure the data reader returned is valid + if (bContinue) { - pageIndex = 0; - pageSize = int.MaxValue; - } + user = new UserInfo + { + PortalID = Null.SetNullInteger(dr["PortalID"]), + IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), + IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]), + UserID = Null.SetNullInteger(dr["UserID"]), + DisplayName = Null.SetNullString(dr["DisplayName"]), + Username = Null.SetNullString(dr["Username"]), + Email = Null.SetNullString(dr["Email"]), + AffiliateID = Null.SetNullInteger(dr["AffiliateID"]), + }; + user.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], user.AffiliateID)); - return FillUserCollection( - portalId, - this._dataProvider.GetUsersByProfileProperty(portalId, propertyName, propertyValue, - pageIndex, pageSize, includeDeleted, - superUsersOnly), ref totalRecords); - } + UserController.GetUserMembership(user); + user.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); + if (!user.IsSuperUser) + { + user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); + } - /// ----------------------------------------------------------------------------- - /// - /// Gets whether the user in question is online. - /// - /// - /// - /// The user. - /// A Boolean indicating whether the user is online. - /// ----------------------------------------------------------------------------- - [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 override bool IsUserOnline(UserInfo user) - { - bool isOnline = false; - var objUsersOnline = new UserOnlineController(); - if (objUsersOnline.IsEnabled()) - { - Hashtable userList = objUsersOnline.GetUserList(); - var onlineUser = (OnlineUserInfo)userList[user.UserID.ToString()]; - if (onlineUser != null) + if (user.PortalID == Null.NullInteger) { - isOnline = true; + user.PortalID = portalId; } - else + + var userProfile = new UserProfile(user); + userProfile.InitialiseProfile(portalId); + + for (int i = 0; i < dr.FieldCount; i++) { - // Next try the Database - onlineUser = CBO.FillObject(this._dataProvider.GetOnlineUser(user.UserID)); - if (onlineUser != null) + switch (dr.GetName(i)) { - isOnline = true; + case "PortalID": + case "IsSuperUser": + case "IsDeleted": + case "UserID": + case "DisplayName": + case "Username": + case "Email": + case "AffiliateID": + case "UpdatePassword": + case "Authorised": + case "CreateDate": + case "LastActivityDate": + case "LastLockoutDate": + case "LastLoginDate": + case "LastPasswordChangedDate": + case "IsLockedOut": + case "PasswordQuestion": + case "IsApproved": + case "PasswordResetToken": + case "PasswordResetExpiration": + break; + default: + // Probably a profile property + string name = dr.GetName(i); + userProfile.SetProfileProperty(name, Null.SetNullString(dr[name])); + break; } } + + user.Profile = userProfile; } - - return isOnline; + + return user; } - public override bool RemoveUser(UserInfo user) + private static UserInfo FillUserInfo(int portalId, IDataReader dr, bool closeDataReader) { - bool retValue = true; - + UserInfo user = null; try { - foreach (var relationship in user.Social.UserRelationships) + // read datareader + bool bContinue = true; + if (closeDataReader) { - RelationshipController.Instance.DeleteUserRelationship(relationship); + bContinue = false; + if (dr.Read()) + { + // Ensure the data reader returned is valid + if (string.Equals(dr.GetName(0), "UserID", StringComparison.InvariantCultureIgnoreCase)) + { + bContinue = true; + } + } } - this._dataProvider.RemoveUser(user.UserID, user.PortalID); - - // Prior to removing membership, ensure user is not present in any other portal - UserInfo otherUser = this.GetUserByUserNameFromDataStore(Null.NullInteger, user.Username); - if (otherUser == null) + if (bContinue) { - DeleteMembershipUser(user); - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - retValue = false; - } + user = new UserInfo + { + PortalID = Null.SetNullInteger(dr["PortalID"]), + IsSuperUser = Null.SetNullBoolean(dr["IsSuperUser"]), + UserID = Null.SetNullInteger(dr["UserID"]), + DisplayName = Null.SetNullString(dr["DisplayName"]), + LastIPAddress = Null.SetNullString(dr["LastIPAddress"]), + }; - return retValue; - } + var schema = dr.GetSchemaTable(); + if (schema != null) + { + if (schema.Select("ColumnName = 'IsDeleted'").Length > 0) + { + user.IsDeleted = Null.SetNullBoolean(dr["IsDeleted"]); + } - /// ----------------------------------------------------------------------------- - /// - /// ResetPassword resets a user's password and returns the newly created password. - /// - /// - /// - /// The user to update. - /// The answer to the user's password Question. - /// The new Password. - /// ----------------------------------------------------------------------------- - public override string ResetPassword(UserInfo user, string passwordAnswer) - { - // Get AspNet MembershipUser - MembershipUser aspnetUser = GetMembershipUser(user); + if (schema.Select("ColumnName = 'VanityUrl'").Length > 0) + { + user.VanityUrl = Null.SetNullString(dr["VanityUrl"]); + } - return this.RequiresQuestionAndAnswer ? aspnetUser.ResetPassword(passwordAnswer) : aspnetUser.ResetPassword(); - } + if (schema.Select("ColumnName = 'HasAgreedToTerms'").Length > 0) + { + user.HasAgreedToTerms = Null.SetNullBoolean(dr["HasAgreedToTerms"]); + } - /// - /// function sets user specific password reset token and timeout - /// works for all PasswordFormats as it resets and then changes the password - /// so old password is not required - /// method does not support RequiresQuestionAndAnswer. - /// - /// - /// - public override bool ResetAndChangePassword(UserInfo user, string newPassword) - { - return this.ResetAndChangePassword(user, newPassword, string.Empty); - } + if (schema.Select("ColumnName = 'HasAgreedToTermsOn'").Length > 0) + { + user.HasAgreedToTermsOn = Null.SetNullDateTime(dr["HasAgreedToTermsOn"]); + } + else + { + user.HasAgreedToTermsOn = Null.NullDate; + } - public override bool ResetAndChangePassword(UserInfo user, string newPassword, string answer) - { - if (this.RequiresQuestionAndAnswer && string.IsNullOrEmpty(answer)) - { - return false; - } + if (schema.Select("ColumnName = 'RequestsRemoval'").Length > 0) + { + user.RequestsRemoval = Null.SetNullBoolean(dr["RequestsRemoval"]); + } - // Get AspNet MembershipUser - MembershipUser aspnetUser = GetMembershipUser(user); - if (aspnetUser.IsLockedOut) - { - aspnetUser.UnlockUser(); - } + if (schema.Select("ColumnName = 'PasswordResetExpiration'").Length > 0) + { + user.PasswordResetExpiration = Null.SetNullDateTime(dr["PasswordResetExpiration"]); + } - string resetPassword = this.ResetPassword(user, answer); - return aspnetUser.ChangePassword(resetPassword, newPassword); - } + if (schema.Select("ColumnName = 'PasswordResetToken'").Length > 0) + { + user.PasswordResetToken = Null.SetNullGuid(dr["PasswordResetToken"]); + } + } - public override bool RestoreUser(UserInfo user) - { - bool retValue = true; + user.AffiliateID = Null.SetNullInteger(Null.SetNull(dr["AffiliateID"], user.AffiliateID)); + user.Username = Null.SetNullString(dr["Username"]); + UserController.GetUserMembership(user); + user.Email = Null.SetNullString(dr["Email"]); + user.Membership.UpdatePassword = Null.SetNullBoolean(dr["UpdatePassword"]); - try - { - this._dataProvider.RestoreUser(user.UserID, user.PortalID); + if (!user.IsSuperUser) + { + user.Membership.Approved = Null.SetNullBoolean(dr["Authorised"]); + } + + if (user.PortalID == Null.NullInteger) + { + user.PortalID = portalId; + } + + user.FillBaseProperties(dr); + } } - catch (Exception ex) + finally { - Exceptions.LogException(ex); - retValue = false; + CBO.CloseDataReader(dr, closeDataReader); } - return retValue; + return user; } - /// ----------------------------------------------------------------------------- - /// - /// Unlocks the User's Account. - /// - /// - /// - /// The user whose account is being Unlocked. - /// True if successful, False if unsuccessful. - /// ----------------------------------------------------------------------------- - public override bool UnLockUser(UserInfo user) + private static void FillUserMembership(MembershipUser aspNetUser, UserInfo user) { - MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); - bool retValue = false; - if (membershipUser != null) + // Fill Membership Property + if (aspNetUser != null) { - retValue = membershipUser.UnlockUser(); - } - - DataCache.RemoveCache(GetCacheKey(user.Username)); - return retValue; - } + if (user.Membership == null) + { + user.Membership = new UserMembership(user); + } - /// ----------------------------------------------------------------------------- - /// - /// User has agreed to terms and conditions for the portal. - /// - /// - /// - /// The agreeing user. - /// ----------------------------------------------------------------------------- - public override void UserAgreedToTerms(UserInfo user) - { - this._dataProvider.UserAgreedToTerms(PortalController.GetEffectivePortalId(user.PortalID), user.UserID); - } + user.Membership.CreatedDate = aspNetUser.CreationDate; + user.Membership.LastActivityDate = aspNetUser.LastActivityDate; + user.Membership.LastLockoutDate = aspNetUser.LastLockoutDate; + user.Membership.LastLoginDate = aspNetUser.LastLoginDate; + user.Membership.LastPasswordChangeDate = aspNetUser.LastPasswordChangedDate; + user.Membership.LockedOut = aspNetUser.IsLockedOut; + user.Membership.PasswordQuestion = aspNetUser.PasswordQuestion; + user.Membership.IsDeleted = user.IsDeleted; - /// ----------------------------------------------------------------------------- - /// - /// Reset all agreements on portal so all users need to agree again at next login. - /// - /// - /// - /// Portal for which to reset agreements. - /// ----------------------------------------------------------------------------- - public override void ResetTermsAgreement(int portalId) - { - this._dataProvider.ResetTermsAgreement(portalId); + if (user.IsSuperUser) + { + // For superusers the Approved info is stored in aspnet membership + user.Membership.Approved = aspNetUser.IsApproved; + } + } } - /// - /// Sets a boolean on the user portal to indicate this user has requested that their account be deleted. - /// - /// User requesting removal. - /// True if user requests removal, false if the value needs to be reset. - public override void UserRequestsRemoval(UserInfo user, bool remove) + private static MembershipUser GetMembershipUser(UserInfo user) { - this._dataProvider.UserRequestsRemoval(user.PortalID, user.UserID, remove); + return GetMembershipUser(user.Username); } - /// ----------------------------------------------------------------------------- - /// - /// UpdateUser persists a user to the Data Store. - /// - /// - /// - /// The user to persist to the Data Store. - /// ----------------------------------------------------------------------------- - public override void UpdateUser(UserInfo user) + private static MembershipUser GetMembershipUser(string userName) { - var objSecurity = PortalSecurity.Instance; - string firstName = objSecurity.InputFilter( - user.FirstName, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - string lastName = objSecurity.InputFilter( - user.LastName, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - string email = objSecurity.InputFilter( - user.Email, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - string displayName = objSecurity.InputFilter( - user.DisplayName, - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); - if (displayName.Contains("<")) - { - displayName = HttpUtility.HtmlEncode(displayName); - } - - if (!firstName.Equals(user.FirstName)) - { - user.FirstName = firstName; - } - - if (!lastName.Equals(user.LastName)) - { - user.LastName = lastName; - } - - bool updatePassword = user.Membership.UpdatePassword; - bool isApproved = user.Membership.Approved; - if (string.IsNullOrEmpty(displayName)) - { - displayName = firstName + " " + lastName; - } - - // Persist the Membership to the Data Store - UpdateUserMembership(user); - - // Persist the DNN User to the Database - this._dataProvider.UpdateUser( - user.UserID, - user.PortalID, - firstName, - lastName, - user.IsSuperUser, - email, - displayName, - user.VanityUrl, - updatePassword, - isApproved, - false, - user.LastIPAddress, - user.PasswordResetToken, - user.PasswordResetExpiration, - user.IsDeleted, - UserController.Instance.GetCurrentUserInfo().UserID); - - // Persist the Profile to the Data Store - ProfileController.UpdateUserProfile(user); + return + CBO.GetCachedObject( + new CacheItemArgs(GetCacheKey(userName), DataCache.UserCacheTimeOut, DataCache.UserCachePriority, + userName), GetMembershipUserCallBack); } - - private string RandomString(int length) + + private static MembershipUser GetMembershipUserByUserKey(string userKey) { - const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - return new string(Enumerable.Repeat(chars, length) - .Select(s => s[random.Next(s.Length)]).ToArray()); + return + CBO.GetCachedObject( + new CacheItemArgs(GetCacheKey(userKey), DataCache.UserCacheTimeOut, DataCache.UserCachePriority, + userKey), GetMembershipUserByUserKeyCallBack); } - /// ----------------------------------------------------------------------------- - /// - /// Updates UserOnline info - /// time window. - /// - /// List of users to update. - /// ----------------------------------------------------------------------------- - [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 override void UpdateUsersOnline(Hashtable userList) + private static string GetCacheKey(string cacheKey) { - this._dataProvider.UpdateUsersOnline(userList); + return $"MembershipUser_{cacheKey}"; } - /// ----------------------------------------------------------------------------- - /// - /// UserLogin attempts to log the user in, and returns the User if successful. - /// - /// - /// - /// The Id of the Portal the user belongs to. - /// The user name of the User attempting to log in. - /// The password of the User attempting to log in. - /// The verification code of the User attempting to log in. - /// An enumerated value indicating the login status. - /// The User as a UserInfo object. - /// ----------------------------------------------------------------------------- - public override UserInfo UserLogin(int portalId, string username, string password, string verificationCode, - ref UserLoginStatus loginStatus) + private static object GetMembershipUserCallBack(CacheItemArgs cacheItemArgs) { - return this.UserLogin(portalId, username, password, "DNN", verificationCode, ref loginStatus); + string userName = cacheItemArgs.ParamList[0].ToString(); + + return System.Web.Security.Membership.GetUser(userName); } - /// ----------------------------------------------------------------------------- - /// - /// UserLogin attempts to log the user in, and returns the User if successful. - /// - /// - /// - /// The Id of the Portal the user belongs to. - /// The user name of the User attempting to log in. - /// The password of the User attempting to log in (may not be used by all Auth types). - /// The type of Authentication Used. - /// The verification code of the User attempting to log in. - /// An enumerated value indicating the login status. - /// The User as a UserInfo object. - /// ----------------------------------------------------------------------------- - public override UserInfo UserLogin(int portalId, string username, string password, string authType, - string verificationCode, ref UserLoginStatus loginStatus) + private static object GetMembershipUserByUserKeyCallBack(CacheItemArgs cacheItemArgs) { - // For now, we are going to ignore the possibility that the User may exist in the - // Global Data Store but not in the Local DataStore ie. A shared Global Data Store + string userKey = cacheItemArgs.ParamList[0].ToString(); - // Initialise Login Status to Failure - loginStatus = UserLoginStatus.LOGIN_FAILURE; + return System.Web.Security.Membership.GetUser(new Guid(userKey)); + } - DataCache.ClearUserCache(portalId, username); - DataCache.ClearCache(GetCacheKey(username)); + private static void UpdateUserMembership(UserInfo user) + { + var portalSecurity = PortalSecurity.Instance; + string email = portalSecurity.InputFilter( + user.Email, + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); - // Get a light-weight (unhydrated) DNN User from the Database, we will hydrate it later if neccessary - UserInfo user = (authType == "DNN") - ? this.GetUserByUserName(portalId, username) - : this.GetUserByAuthToken(portalId, verificationCode, authType); - if (user != null && !user.IsDeleted) + // Persist the Membership Properties to the AspNet Data Store + MembershipUser membershipUser = System.Web.Security.Membership.GetUser(user.Username); + membershipUser.Email = email; + membershipUser.LastActivityDate = DateTime.Now; + if (user.IsSuperUser) { - // Get AspNet MembershipUser - MembershipUser aspnetUser = GetMembershipUser(user); + membershipUser.IsApproved = user.Membership.Approved; + } - // Fill Membership Property from AspNet MembershipUser - FillUserMembership(aspnetUser, user); + try + { + System.Web.Security.Membership.UpdateUser(membershipUser); + } + catch (ProviderException ex) + { + throw new Exception(Localization.GetExceptionMessage("UpdateUserMembershipFailed", "Asp.net membership update user failed."), ex); + } - // Check if the User is Locked Out (and unlock if AutoUnlock has expired) - if (aspnetUser.IsLockedOut) + DataCache.RemoveCache(GetCacheKey(user.Username)); + } + + private static UserLoginStatus ValidateLogin(string username, string authType, UserInfo user, + UserLoginStatus loginStatus, string password, ref bool bValid, + int portalId) + { + if (loginStatus != UserLoginStatus.LOGIN_USERLOCKEDOUT && + (loginStatus != UserLoginStatus.LOGIN_USERNOTAPPROVED || user.IsInRole("Unverified Users"))) + { + if (authType == "DNN") { - if (AutoUnlockUser(aspnetUser)) + if (user.IsSuperUser) { - // Unlock User - user.Membership.LockedOut = false; + if (ValidateUser(username, password)) + { + loginStatus = UserLoginStatus.LOGIN_SUPERUSER; + bValid = true; + } } else { - loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT; + if (ValidateUser(username, password)) + { + loginStatus = UserLoginStatus.LOGIN_SUCCESS; + bValid = true; + } } } - - // Check in a verified situation whether the user is Approved - if (user.Membership.Approved == false && user.IsSuperUser == false) + else { - // Check Verification code (skip for FB, Google, Twitter, LiveID as it has no verification code) - if (this._socialAuthProviders.Contains(authType) && string.IsNullOrEmpty(verificationCode)) + if (user.IsSuperUser) { - if (PortalController.Instance.GetCurrentPortalSettings().UserRegistration == - (int)Globals.PortalRegistrationType.PublicRegistration) - { - user.Membership.Approved = true; - UserController.UpdateUser(portalId, user); - UserController.ApproveUser(user); - } - else - { - loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; - } + loginStatus = UserLoginStatus.LOGIN_SUPERUSER; + bValid = true; } else { - var ps = PortalSecurity.Instance; - if (verificationCode == ps.Encrypt(Config.GetDecryptionkey(), portalId + "-" + user.UserID)) - { - UserController.ApproveUser(user); - } - else - { - loginStatus = UserLoginStatus.LOGIN_USERNOTAPPROVED; - } + loginStatus = UserLoginStatus.LOGIN_SUCCESS; + bValid = true; } } + } - // Verify User Credentials - bool bValid = false; - loginStatus = ValidateLogin(username, authType, user, loginStatus, password, ref bValid, portalId); - if (!bValid) - { - // Clear the user object - user = null; + return loginStatus; + } - // Clear cache for user so that locked out & other status could be updated - DataCache.ClearUserCache(portalId, username); - DataCache.ClearCache(GetCacheKey(username)); + private static bool ValidateUser(string username, string password) + { + return System.Web.Security.Membership.ValidateUser(username, password); + } - aspnetUser = System.Web.Security.Membership.GetUser(username); + 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); + } - // If user has been locked out for current invalid attempt - // return locked out status - if (aspnetUser.IsLockedOut) + 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 string GetStringSetting(Hashtable settings, string settingKey) + { + return settings[settingKey] == null ? string.Empty : settings[settingKey].ToString(); + } + + 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)) { - loginStatus = UserLoginStatus.LOGIN_USERLOCKEDOUT; + createStatus = UserCreateStatus.InvalidDisplayName; } } } - else + + 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) { - // Clear the user object - user = null; + UserInfo duplicateUser = this.GetUserByDisplayName(user.PortalID, user.DisplayName); + if (duplicateUser != null) + { + createStatus = UserCreateStatus.DuplicateDisplayName; + } } - - return 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()); + } /// ----------------------------------------------------------------------------- /// diff --git a/DNN Platform/Library/Security/Membership/MembershipProvider.cs b/DNN Platform/Library/Security/Membership/MembershipProvider.cs index ba8c9942378..b2eb8b3fa05 100644 --- a/DNN Platform/Library/Security/Membership/MembershipProvider.cs +++ b/DNN Platform/Library/Security/Membership/MembershipProvider.cs @@ -11,84 +11,84 @@ namespace DotNetNuke.Security.Membership using DotNetNuke.Entities.Users; public abstract class MembershipProvider - { + { public abstract bool CanEditProviderProperties { get; } - + public abstract int MaxInvalidPasswordAttempts { get; set; } - + public abstract int MinPasswordLength { get; set; } - + public abstract int MinNonAlphanumericCharacters { get; set; } - + public abstract int PasswordAttemptWindow { get; set; } - + public abstract PasswordFormat PasswordFormat { get; set; } - + public abstract bool PasswordResetEnabled { get; set; } - + public abstract bool PasswordRetrievalEnabled { get; set; } - + public abstract string PasswordStrengthRegularExpression { get; set; } - + public abstract bool RequiresQuestionAndAnswer { get; set; } - - public abstract bool RequiresUniqueEmail { get; set; } - - // return the provider + + public abstract bool RequiresUniqueEmail { get; set; } + + // return the provider public static MembershipProvider Instance() { return ComponentFactory.GetComponent(); - } - - // Users + } + + // Users public abstract bool ChangePassword(UserInfo user, string oldPassword, string newPassword); - + public abstract bool ChangePasswordQuestionAndAnswer(UserInfo user, string password, string passwordQuestion, string passwordAnswer); - + public abstract UserCreateStatus CreateUser(ref UserInfo user); - + public abstract bool DeleteUser(UserInfo user); - + public abstract bool RestoreUser(UserInfo user); - + public abstract bool RemoveUser(UserInfo user); - + public abstract string GeneratePassword(); - + public abstract string GeneratePassword(int length); - + public abstract string GetPassword(UserInfo user, string passwordAnswer); - + public abstract int GetUserCountByPortal(int portalId); - + public abstract void GetUserMembership(ref UserInfo user); - + public abstract string ResetPassword(UserInfo user, string passwordAnswer); - + public abstract bool UnLockUser(UserInfo user); - + public abstract void UserAgreedToTerms(UserInfo user); - + public abstract void ResetTermsAgreement(int portalId); - + public abstract void UserRequestsRemoval(UserInfo user, bool remove); - + public abstract void UpdateUser(UserInfo user); - + public abstract UserInfo UserLogin(int portalId, string username, string password, string verificationCode, ref UserLoginStatus loginStatus); - + public abstract UserInfo UserLogin(int portalId, string username, string password, string authType, string verificationCode, ref UserLoginStatus loginStatus); // Users Online [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 abstract void DeleteUsersOnline(int TimeWindow); - + [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 abstract ArrayList GetOnlineUsers(int PortalId); - + [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 abstract bool IsUserOnline(UserInfo 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 abstract void UpdateUsersOnline(Hashtable UserList); @@ -99,21 +99,21 @@ public virtual void TransferUsersToMembershipProvider() // Get Users public abstract UserInfo GetUser(int portalId, int userId); - + public abstract UserInfo GetUserByUserName(int portalId, string username); - + public abstract ArrayList GetUnAuthorizedUsers(int portalId); - + public abstract ArrayList GetDeletedUsers(int portalId); - + public abstract ArrayList GetUsers(int portalId, int pageIndex, int pageSize, ref int totalRecords); - + public abstract ArrayList GetUsersByEmail(int portalId, string emailToMatch, int pageIndex, int pageSize, ref int totalRecords); - + public abstract ArrayList GetUsersByUserName(int portalId, string userNameToMatch, int pageIndex, int pageSize, ref int totalRecords); - - public abstract ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords); - + + public abstract ArrayList GetUsersByProfileProperty(int portalId, string propertyName, string propertyValue, int pageIndex, int pageSize, ref int totalRecords); + public virtual UserInfo GetUserByDisplayName(int portalId, string displayName) { return null; @@ -196,7 +196,7 @@ public virtual bool ResetAndChangePassword(UserInfo user, string newPassword, st { throw new NotImplementedException(); } - + public virtual void ChangeUsername(int userId, string newUsername) { throw new NotImplementedException(); @@ -205,6 +205,6 @@ public virtual void ChangeUsername(int userId, string newUsername) public virtual void AddUserPortal(int portalId, int userId) { throw new NotImplementedException(); - } + } } } diff --git a/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs b/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs index 650a9a0d694..ef35cb765aa 100644 --- a/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs +++ b/DNN Platform/Library/Security/Membership/MembershipProviderConfig.cs @@ -20,9 +20,9 @@ namespace DotNetNuke.Security.Membership /// /// ----------------------------------------------------------------------------- public class MembershipProviderConfig - { - private static readonly MembershipProvider memberProvider = MembershipProvider.Instance(); - + { + private static readonly MembershipProvider memberProvider = MembershipProvider.Instance(); + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the Provider Properties can be edited. @@ -44,7 +44,7 @@ public static bool CanEditProviderProperties /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(8)] + [SortOrder(8)] [Category("Password")] public static int MaxInvalidPasswordAttempts { @@ -52,7 +52,7 @@ public static int MaxInvalidPasswordAttempts { return memberProvider.MaxInvalidPasswordAttempts; } - + set { memberProvider.MaxInvalidPasswordAttempts = value; @@ -65,7 +65,7 @@ public static int MaxInvalidPasswordAttempts /// /// An Integer. /// ----------------------------------------------------------------------------- - [SortOrder(5)] + [SortOrder(5)] [Category("Password")] public static int MinNonAlphanumericCharacters { @@ -73,7 +73,7 @@ public static int MinNonAlphanumericCharacters { return memberProvider.MinNonAlphanumericCharacters; } - + set { memberProvider.MinNonAlphanumericCharacters = value; @@ -86,7 +86,7 @@ public static int MinNonAlphanumericCharacters /// /// An Integer. /// ----------------------------------------------------------------------------- - [SortOrder(4)] + [SortOrder(4)] [Category("Password")] public static int MinPasswordLength { @@ -94,7 +94,7 @@ public static int MinPasswordLength { return memberProvider.MinPasswordLength; } - + set { memberProvider.MinPasswordLength = value; @@ -107,7 +107,7 @@ public static int MinPasswordLength /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(9)] + [SortOrder(9)] [Category("Password")] public static int PasswordAttemptWindow { @@ -115,7 +115,7 @@ public static int PasswordAttemptWindow { return memberProvider.PasswordAttemptWindow; } - + set { memberProvider.PasswordAttemptWindow = value; @@ -128,7 +128,7 @@ public static int PasswordAttemptWindow /// /// A PasswordFormat enumeration. /// ----------------------------------------------------------------------------- - [SortOrder(1)] + [SortOrder(1)] [Category("Password")] public static PasswordFormat PasswordFormat { @@ -136,7 +136,7 @@ public static PasswordFormat PasswordFormat { return memberProvider.PasswordFormat; } - + set { memberProvider.PasswordFormat = value; @@ -149,7 +149,7 @@ public static PasswordFormat PasswordFormat /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(3)] + [SortOrder(3)] [Category("Password")] public static bool PasswordResetEnabled { @@ -157,7 +157,7 @@ public static bool PasswordResetEnabled { return memberProvider.PasswordResetEnabled; } - + set { memberProvider.PasswordResetEnabled = value; @@ -170,7 +170,7 @@ public static bool PasswordResetEnabled /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(2)] + [SortOrder(2)] [Category("Password")] public static bool PasswordRetrievalEnabled { @@ -183,10 +183,10 @@ public static bool PasswordRetrievalEnabled { enabled = false; } - + return enabled; } - + set { memberProvider.PasswordRetrievalEnabled = value; @@ -199,7 +199,7 @@ public static bool PasswordRetrievalEnabled /// /// A String. /// ----------------------------------------------------------------------------- - [SortOrder(7)] + [SortOrder(7)] [Category("Password")] public static string PasswordStrengthRegularExpression { @@ -207,7 +207,7 @@ public static string PasswordStrengthRegularExpression { return memberProvider.PasswordStrengthRegularExpression; } - + set { memberProvider.PasswordStrengthRegularExpression = value; @@ -220,7 +220,7 @@ public static string PasswordStrengthRegularExpression /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(6)] + [SortOrder(6)] [Category("Password")] public static bool RequiresQuestionAndAnswer { @@ -228,7 +228,7 @@ public static bool RequiresQuestionAndAnswer { return memberProvider.RequiresQuestionAndAnswer; } - + set { memberProvider.RequiresQuestionAndAnswer = value; @@ -241,7 +241,7 @@ public static bool RequiresQuestionAndAnswer /// /// A Boolean. /// ----------------------------------------------------------------------------- - [SortOrder(0)] + [SortOrder(0)] [Category("User")] public static bool RequiresUniqueEmail { @@ -249,11 +249,11 @@ public static bool RequiresUniqueEmail { return memberProvider.RequiresUniqueEmail; } - + set { memberProvider.RequiresUniqueEmail = value; - } + } } } } diff --git a/DNN Platform/Library/Security/Membership/PasswordConfig.cs b/DNN Platform/Library/Security/Membership/PasswordConfig.cs index fbe95d7456c..4911d73d890 100644 --- a/DNN Platform/Library/Security/Membership/PasswordConfig.cs +++ b/DNN Platform/Library/Security/Membership/PasswordConfig.cs @@ -28,7 +28,7 @@ public class PasswordConfig /// /// An integer. /// ----------------------------------------------------------------------------- - [SortOrder(0)] + [SortOrder(0)] [Category("Password")] public static int PasswordExpiry { @@ -36,7 +36,7 @@ public static int PasswordExpiry { return Host.PasswordExpiry; } - + set { HostController.Instance.Update("PasswordExpiry", value.ToString()); @@ -50,7 +50,7 @@ public static int PasswordExpiry /// /// An integer. /// ----------------------------------------------------------------------------- - [SortOrder(1)] + [SortOrder(1)] [Category("Password")] public static int PasswordExpiryReminder { @@ -58,7 +58,7 @@ public static int PasswordExpiryReminder { return Host.PasswordExpiryReminder; } - + set { HostController.Instance.Update("PasswordExpiryReminder", value.ToString()); diff --git a/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs b/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs index bbee31214ce..5c07ab51548 100644 --- a/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareDesktopModulePermissions.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Security.Permissions ///
    /// ----------------------------------------------------------------------------- internal class CompareDesktopModulePermissions : IComparer - { + { public int Compare(object x, object y) { return ((DesktopModulePermissionInfo)x).DesktopModulePermissionID.CompareTo(((DesktopModulePermissionInfo)y).DesktopModulePermissionID); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs b/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs index 41ebb8aa594..9c48c49b06e 100644 --- a/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareFolderPermissions.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Security.Permissions ///
    /// ----------------------------------------------------------------------------- internal class CompareFolderPermissions : IComparer - { + { public int Compare(object x, object y) { return ((FolderPermissionInfo)x).FolderPermissionID.CompareTo(((FolderPermissionInfo)y).FolderPermissionID); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs b/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs index 1765e696a26..f46d0af9629 100644 --- a/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareModulePermissions.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Security.Permissions ///
    /// ----------------------------------------------------------------------------- internal class CompareModulePermissions : IComparer - { + { public int Compare(object x, object y) { return ((ModulePermissionInfo)x).ModulePermissionID.CompareTo(((ModulePermissionInfo)y).ModulePermissionID); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs b/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs index 4fa5ca8f11e..ad9267a118e 100644 --- a/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs +++ b/DNN Platform/Library/Security/Permissions/CompareTabPermissions.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Security.Permissions ///
    /// ----------------------------------------------------------------------------- internal class CompareTabPermissions : IComparer - { + { public int Compare(object x, object y) { return ((TabPermissionInfo)x).TabPermissionID.CompareTo(((TabPermissionInfo)y).TabPermissionID); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs index 1884d249a53..6a85082c6f7 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/DesktopModulePermissionsGrid.cs @@ -15,11 +15,11 @@ namespace DotNetNuke.Security.Permissions.Controls using DotNetNuke.Security.Roles; public class DesktopModulePermissionsGrid : PermissionsGrid - { + { private DesktopModulePermissionCollection _DesktopModulePermissions; private List _PermissionsList; - private int _PortalDesktopModuleID = -1; - + private int _PortalDesktopModuleID = -1; + /// ----------------------------------------------------------------------------- /// /// Gets the Permissions Collection. @@ -48,7 +48,7 @@ public int PortalDesktopModuleID { return this._PortalDesktopModuleID; } - + set { int oldValue = this._PortalDesktopModuleID; @@ -58,8 +58,8 @@ public int PortalDesktopModuleID this.GetDesktopModulePermissions(); } } - } - + } + protected override List PermissionsList { get @@ -68,11 +68,11 @@ protected override List PermissionsList { this._PermissionsList = this._DesktopModulePermissions.ToList(); } - + return this._PermissionsList; } - } - + } + public void ResetPermissions() { this.GetDesktopModulePermissions(); @@ -81,8 +81,8 @@ public void ResetPermissions() public override void GenerateDataGrid() { - } - + } + protected override void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) { var objPermission = new DesktopModulePermissionInfo(permission); @@ -130,41 +130,6 @@ 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; - } /// ----------------------------------------------------------------------------- /// @@ -194,7 +159,7 @@ protected override void AddPermission(ArrayList permissions, RoleInfo role) /// ----------------------------------------------------------------------------- /// /// Gets the permissions from the Database. - /// + /// /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() @@ -249,7 +214,7 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { this._DesktopModulePermissions.Remove(permissionID, roleID, userID); - + // Clear Permission List this._PermissionsList = null; } @@ -257,7 +222,7 @@ protected override void RemovePermission(int permissionID, int roleID, int userI /// ----------------------------------------------------------------------------- /// /// Saves the ViewState. - /// + /// /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() @@ -285,8 +250,8 @@ protected override object SaveViewState() { addDelimiter = true; } - - sb.Append(this.BuildKey( + + sb.Append(this.BuildKey( objDesktopModulePermission.AllowAccess, objDesktopModulePermission.PermissionID, objDesktopModulePermission.DesktopModulePermissionID, @@ -296,7 +261,7 @@ protected override object SaveViewState() objDesktopModulePermission.DisplayName)); } } - + allStates[2] = sb.ToString(); return allStates; } @@ -304,12 +269,47 @@ protected override object SaveViewState() /// ----------------------------------------------------------------------------- /// /// returns whether or not the derived grid supports Deny permissions. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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; + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs index 34008a0b45e..96c86981bb1 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/FolderPermissionsGrid.cs @@ -19,50 +19,50 @@ namespace DotNetNuke.Security.Permissions.Controls using DotNetNuke.Security.Roles; public class FolderPermissionsGrid : PermissionsGrid - { + { protected FolderPermissionCollection FolderPermissions; private string _folderPath = string.Empty; private List _permissionsList; private bool _refreshGrid; - private IList _systemFolderPermissions; - + private IList _systemFolderPermissions; + /// ----------------------------------------------------------------------------- /// - /// Gets or sets and Sets the path of the Folder. + /// Gets the Permission Collection. /// /// ----------------------------------------------------------------------------- - public string FolderPath + public FolderPermissionCollection Permissions { get { - return this._folderPath; - } - - set - { - this._folderPath = value; - this._refreshGrid = true; - this.GetFolderPermissions(); + // First Update Permissions in case they have been changed + this.UpdatePermissions(); + + // Return the FolderPermissions + return this.FolderPermissions; } } /// ----------------------------------------------------------------------------- /// - /// Gets the Permission Collection. + /// Gets or sets and Sets the path of the Folder. /// /// ----------------------------------------------------------------------------- - public FolderPermissionCollection Permissions + public string FolderPath { get { - // First Update Permissions in case they have been changed - this.UpdatePermissions(); + return this._folderPath; + } - // Return the FolderPermissions - return this.FolderPermissions; + set + { + this._folderPath = value; + this._refreshGrid = true; + this.GetFolderPermissions(); } - } - + } + protected override List PermissionsList { get @@ -71,7 +71,7 @@ protected override List PermissionsList { this._permissionsList = this.FolderPermissions.ToList(); } - + return this._permissionsList; } } @@ -82,8 +82,8 @@ protected override bool RefreshGrid { return this._refreshGrid; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Overrides the Base method to Generate the Data Grid. @@ -91,8 +91,8 @@ protected override bool RefreshGrid /// ----------------------------------------------------------------------------- public override void GenerateDataGrid() { - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the TabPermissions from the Data Store. @@ -103,7 +103,7 @@ protected virtual void GetFolderPermissions() this.FolderPermissions = new FolderPermissionCollection(FolderPermissionController.GetFolderPermissionsCollectionByFolder(this.PortalId, this.FolderPath)); this._permissionsList = null; } - + protected override void CreateChildControls() { base.CreateChildControls(); @@ -127,49 +127,6 @@ protected override void AddPermission(PermissionInfo permission, int roleId, str this._permissionsList = null; } - /// ----------------------------------------------------------------------------- - /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState. - /// - /// A string array of settings. - /// ----------------------------------------------------------------------------- - private FolderPermissionInfo ParseKeys(string[] settings) - { - var objFolderPermission = new FolderPermissionInfo(); - - // Call base class to load base properties - this.ParsePermissionKeys(objFolderPermission, settings); - if (string.IsNullOrEmpty(settings[2])) - { - objFolderPermission.FolderPermissionID = -1; - } - else - { - objFolderPermission.FolderPermissionID = Convert.ToInt32(settings[2]); - } - - objFolderPermission.FolderPath = this.FolderPath; - return objFolderPermission; - } - - private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) - { - var item = e.Item; - - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) - { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) - { - actionImage.Visible = false; - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// Updates a Permission. @@ -233,7 +190,7 @@ protected override void AddPermission(ArrayList permissions, RoleInfo role) /// /// The permission being loaded. /// The role. - /// The column of the Grid. + /// The column of the Grid. /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) @@ -263,7 +220,7 @@ protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, i // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, role, column, defaultState); } - + return permission; } @@ -280,7 +237,7 @@ protected override bool IsViewPermisison(PermissionInfo permissionInfo) /// ----------------------------------------------------------------------------- /// /// Gets the permissions from the Database. - /// + /// /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() @@ -334,25 +291,10 @@ 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); - + // Clear Permission List this._permissionsList = null; } @@ -360,7 +302,7 @@ protected override void RemovePermission(int permissionID, int roleID, int userI /// ----------------------------------------------------------------------------- /// /// Saves the ViewState. - /// + /// /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() @@ -388,8 +330,8 @@ protected override object SaveViewState() { addDelimiter = true; } - - sb.Append(this.BuildKey( + + sb.Append(this.BuildKey( objFolderPermission.AllowAccess, objFolderPermission.PermissionID, objFolderPermission.FolderPermissionID, @@ -399,7 +341,7 @@ protected override object SaveViewState() objFolderPermission.DisplayName)); } } - + allStates[2] = sb.ToString(); return allStates; } @@ -407,12 +349,70 @@ protected override object SaveViewState() /// ----------------------------------------------------------------------------- /// /// returns whether or not the derived grid supports Deny permissions. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return this.IsSystemFolderPermission(permissionInfo); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. + /// ----------------------------------------------------------------------------- + private FolderPermissionInfo ParseKeys(string[] settings) + { + var objFolderPermission = new FolderPermissionInfo(); + + // Call base class to load base properties + this.ParsePermissionKeys(objFolderPermission, settings); + if (string.IsNullOrEmpty(settings[2])) + { + objFolderPermission.FolderPermissionID = -1; + } + else + { + objFolderPermission.FolderPermissionID = Convert.ToInt32(settings[2]); + } + + objFolderPermission.FolderPath = this.FolderPath; + return objFolderPermission; + } + + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + { + var item = e.Item; + + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + { + var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; + if (actionImage != null) + { + actionImage.Visible = false; + } + } + } + } + + private bool IsPermissionAlwaysGrantedToAdmin(PermissionInfo permissionInfo) + { + return this.IsSystemFolderPermission(permissionInfo); + } + + private bool IsSystemFolderPermission(PermissionInfo permissionInfo) + { + 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); + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs index 62d6e10b4da..42a700b502f 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/ModulePermissionsGrid.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Security.Permissions.Controls using DotNetNuke.Security.Roles; public class ModulePermissionsGrid : PermissionsGrid - { + { private bool _InheritViewPermissionsFromTab; private int _ModuleID = -1; private ModulePermissionCollection _ModulePermissions; @@ -30,8 +30,25 @@ public class ModulePermissionsGrid : PermissionsGrid public ModulePermissionsGrid() { this.TabId = -1; - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ModulePermission Collection. + /// + /// ----------------------------------------------------------------------------- + public ModulePermissionCollection Permissions + { + get + { + // First Update Permissions in case they have been changed + this.UpdatePermissions(); + + // Return the ModulePermissions + return this._ModulePermissions; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and Sets whether the Module inherits the Page's(Tab's) permissions. @@ -43,7 +60,7 @@ public bool InheritViewPermissionsFromTab { return this._InheritViewPermissionsFromTab; } - + set { this._InheritViewPermissionsFromTab = value; @@ -62,7 +79,7 @@ public int ModuleID { return this._ModuleID; } - + set { this._ModuleID = value; @@ -72,19 +89,6 @@ public int ModuleID } } } - - protected override List PermissionsList - { - get - { - if (this._PermissionsList == null && this._ModulePermissions != null) - { - this._PermissionsList = this._ModulePermissions.ToList(); - } - - return this._PermissionsList; - } - } /// ----------------------------------------------------------------------------- /// @@ -93,23 +97,19 @@ protected override List PermissionsList /// ----------------------------------------------------------------------------- public int TabId { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the ModulePermission Collection. - /// - /// ----------------------------------------------------------------------------- - public ModulePermissionCollection Permissions + protected override List PermissionsList { get { - // First Update Permissions in case they have been changed - this.UpdatePermissions(); + if (this._PermissionsList == null && this._ModulePermissions != null) + { + this._PermissionsList = this._ModulePermissions.ToList(); + } - // Return the ModulePermissions - return this._ModulePermissions; + return this._PermissionsList; } } - + /// ----------------------------------------------------------------------------- /// /// Overrides the Base method to Generate the Data Grid. @@ -117,8 +117,8 @@ public ModulePermissionCollection Permissions /// ----------------------------------------------------------------------------- public override void GenerateDataGrid() { - } - + } + protected override void CreateChildControls() { base.CreateChildControls(); @@ -150,70 +150,6 @@ protected override void AddPermission(ArrayList permissions, UserInfo user) } } - /// ----------------------------------------------------------------------------- - /// - /// Check if a role is implicit for Module Permissions. - /// - /// ----------------------------------------------------------------------------- - private bool IsImplicitRole(int portalId, int roleId) - { - return ModulePermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the ModulePermissions from the Data Store. - /// - /// ----------------------------------------------------------------------------- - private void GetModulePermissions() - { - this._ModulePermissions = new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabId)); - this._PermissionsList = null; - } - - /// ----------------------------------------------------------------------------- - /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState. - /// - /// A string array of settings. - /// ----------------------------------------------------------------------------- - private ModulePermissionInfo ParseKeys(string[] Settings) - { - var objModulePermission = new ModulePermissionInfo(); - - // Call base class to load base properties - this.ParsePermissionKeys(objModulePermission, Settings); - if (string.IsNullOrEmpty(Settings[2])) - { - objModulePermission.ModulePermissionID = -1; - } - else - { - objModulePermission.ModulePermissionID = Convert.ToInt32(Settings[2]); - } - - objModulePermission.ModuleID = this.ModuleID; - return objModulePermission; - } - - private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) - { - var item = e.Item; - - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) - { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) - { - actionImage.Visible = false; - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// Updates a Permission. @@ -242,14 +178,14 @@ 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); @@ -263,7 +199,7 @@ protected override void UpdatePermission(PermissionInfo permission, int roleId, { return; } - + base.UpdatePermission(permission, roleId, roleName, stateKey); } @@ -273,7 +209,7 @@ protected override void UpdatePermission(PermissionInfo permission, string displ { return; } - + base.UpdatePermission(permission, displayName, userId, stateKey); } @@ -283,7 +219,7 @@ protected override void UpdatePermission(PermissionInfo permission, string displ /// /// The permission being loaded. /// The role. - /// The column of the Grid. + /// The column of the Grid. /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) @@ -297,7 +233,7 @@ protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int co { enabled = !this.IsImplicitRole(role.PortalID, role.RoleID); } - + return enabled; } @@ -307,7 +243,7 @@ protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int co /// /// The permission being loaded. /// The user. - /// The column of the Grid. + /// The column of the Grid. /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) @@ -321,7 +257,7 @@ protected override bool GetEnabled(PermissionInfo objPerm, UserInfo user, int co { enabled = true; } - + return enabled; } @@ -348,7 +284,7 @@ protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, i ? PermissionTypeGrant : base.GetPermission(objPerm, role, column, defaultState); } - + return permission; } @@ -374,14 +310,14 @@ protected override string GetPermission(PermissionInfo objPerm, UserInfo user, i // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, user, column, defaultState); } - + return permission; } /// ----------------------------------------------------------------------------- /// /// Gets the Permissions from the Data Store. - /// + /// /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() @@ -408,7 +344,7 @@ protected override ArrayList GetPermissions() } } } - + return permissionList; } @@ -481,7 +417,7 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { this._ModulePermissions.Remove(permissionID, roleID, userID); - + // Clear Permission List this._PermissionsList = null; } @@ -489,7 +425,7 @@ protected override void RemovePermission(int permissionID, int roleID, int userI /// ----------------------------------------------------------------------------- /// /// Saves the ViewState. - /// + /// /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() @@ -523,8 +459,8 @@ protected override object SaveViewState() { addDelimiter = true; } - - sb.Append(this.BuildKey( + + sb.Append(this.BuildKey( modulePermission.AllowAccess, modulePermission.PermissionID, modulePermission.ModulePermissionID, @@ -534,7 +470,7 @@ protected override object SaveViewState() modulePermission.DisplayName)); } } - + allStates[4] = sb.ToString(); return allStates; } @@ -542,12 +478,76 @@ protected override object SaveViewState() /// ----------------------------------------------------------------------------- /// /// returns whether or not the derived grid supports Deny permissions. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Check if a role is implicit for Module Permissions. + /// + /// ----------------------------------------------------------------------------- + private bool IsImplicitRole(int portalId, int roleId) + { + return ModulePermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ModulePermissions from the Data Store. + /// + /// ----------------------------------------------------------------------------- + private void GetModulePermissions() + { + this._ModulePermissions = new ModulePermissionCollection(ModulePermissionController.GetModulePermissions(this.ModuleID, this.TabId)); + this._PermissionsList = null; + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. + /// ----------------------------------------------------------------------------- + private ModulePermissionInfo ParseKeys(string[] Settings) + { + var objModulePermission = new ModulePermissionInfo(); + + // Call base class to load base properties + this.ParsePermissionKeys(objModulePermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) + { + objModulePermission.ModulePermissionID = -1; + } + else + { + objModulePermission.ModulePermissionID = Convert.ToInt32(Settings[2]); + } + + objModulePermission.ModuleID = this.ModuleID; + return objModulePermission; + } + + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + { + var item = e.Item; + + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + { + var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; + if (actionImage != null) + { + actionImage.Visible = false; + } + } + } + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs index 33b514b4950..ef95926de8b 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/PermissionsGrid.cs @@ -26,12 +26,12 @@ namespace DotNetNuke.Security.Permissions.Controls using Globals = DotNetNuke.Common.Globals; public abstract class PermissionsGrid : Control, INamingContainer - { + { protected const string PermissionTypeGrant = "True"; protected const string PermissionTypeDeny = "False"; - protected const string PermissionTypeNull = "Null"; + protected const string PermissionTypeNull = "Null"; protected DataGrid rolePermissionsGrid; - protected DataGrid userPermissionsGrid; + protected DataGrid userPermissionsGrid; private ArrayList _permissions; private ArrayList _users; private DropDownList cboRoleGroups; @@ -44,18 +44,18 @@ public abstract class PermissionsGrid : Control, INamingContainer private Panel pnlPermissions; private TextBox txtUser; private HiddenField hiddenUserIds; - private HiddenField roleField; - + private HiddenField roleField; + private int unAuthUsersRoleId = int.Parse(Globals.glbRoleUnauthUser); private int allUsersRoleId = int.Parse(Globals.glbRoleAllUsers); - + public PermissionsGrid() { this.dtUserPermissions = new DataTable(); this.dtRolePermissions = new DataTable(); - } - + } + public TableItemStyle AlternatingItemStyle { get @@ -64,156 +64,138 @@ public TableItemStyle AlternatingItemStyle } } - public bool AutoGenerateColumns + public DataGridColumnCollection Columns { get { - return this.rolePermissionsGrid.AutoGenerateColumns; - } - - set - { - this.rolePermissionsGrid.AutoGenerateColumns = value; - this.userPermissionsGrid.AutoGenerateColumns = value; + return this.rolePermissionsGrid.Columns; } } - public int CellSpacing + public TableItemStyle FooterStyle { get { - return this.rolePermissionsGrid.CellSpacing; - } - - set - { - this.rolePermissionsGrid.CellSpacing = value; - this.userPermissionsGrid.CellSpacing = value; + return this.rolePermissionsGrid.FooterStyle; } } - - protected virtual List PermissionsList + + public TableItemStyle HeaderStyle { get { - return null; + return this.rolePermissionsGrid.HeaderStyle; } } - protected virtual bool RefreshGrid + public TableItemStyle ItemStyle { get { - return false; + return this.rolePermissionsGrid.ItemStyle; } - } - - private int UnAuthUsersRoleId - { - get { return this.unAuthUsersRoleId; } } - - private int AllUsersRoleId + + public DataGridItemCollection Items { get { - return this.allUsersRoleId; + return this.rolePermissionsGrid.Items; } - } - - /// - /// 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 + public TableItemStyle SelectedItemStyle { get { - return this.rolePermissionsGrid.Columns; + return this.rolePermissionsGrid.SelectedItemStyle; } } - public TableItemStyle FooterStyle + /// + /// Gets the Id of the Administrator Role. + /// + public int AdministratorRoleId { get { - return this.rolePermissionsGrid.FooterStyle; + return PortalController.Instance.GetCurrentPortalSettings().AdministratorRoleId; } } - public GridLines GridLines + /// + /// Gets the Id of the Registered Users Role. + /// + public int RegisteredUsersRoleId { get { - return this.rolePermissionsGrid.GridLines; - } - - set - { - this.rolePermissionsGrid.GridLines = value; - this.userPermissionsGrid.GridLines = value; + return PortalController.Instance.GetCurrentPortalSettings().RegisteredRoleId; } } - public TableItemStyle HeaderStyle + /// + /// Gets the Id of the Portal. + /// + public int PortalId { get { - return this.rolePermissionsGrid.HeaderStyle; + // Obtain PortalSettings from Current Context + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + int portalID; + if (Globals.IsHostTab(portalSettings.ActiveTab.TabID)) // if we are in host filemanager then we need to pass a null portal id + { + portalID = Null.NullInteger; + } + else + { + portalID = portalSettings.PortalId; + } + + return portalID; } } - public TableItemStyle ItemStyle + public bool AutoGenerateColumns { get { - return this.rolePermissionsGrid.ItemStyle; + return this.rolePermissionsGrid.AutoGenerateColumns; } - } - public DataGridItemCollection Items - { - get + set { - return this.rolePermissionsGrid.Items; + this.rolePermissionsGrid.AutoGenerateColumns = value; + this.userPermissionsGrid.AutoGenerateColumns = value; } } - public TableItemStyle SelectedItemStyle + public int CellSpacing { get { - return this.rolePermissionsGrid.SelectedItemStyle; + return this.rolePermissionsGrid.CellSpacing; } - } - - /// - /// Gets the Id of the Administrator Role. - /// - public int AdministratorRoleId - { - get + + set { - return PortalController.Instance.GetCurrentPortalSettings().AdministratorRoleId; + this.rolePermissionsGrid.CellSpacing = value; + this.userPermissionsGrid.CellSpacing = value; } } - /// - /// Gets the Id of the Registered Users Role. - /// - public int RegisteredUsersRoleId + public GridLines GridLines { get { - return PortalController.Instance.GetCurrentPortalSettings().RegisteredRoleId; + return this.rolePermissionsGrid.GridLines; + } + + set + { + this.rolePermissionsGrid.GridLines = value; + this.userPermissionsGrid.GridLines = value; } } @@ -226,7 +208,7 @@ public bool DynamicColumnAdded { return this.ViewState["ColumnAdded"] != null; } - + set { this.ViewState["ColumnAdded"] = value; @@ -244,43 +226,61 @@ public bool DynamicColumnAdded public DataTable dtUserPermissions { get; private set; } /// - /// Gets the Id of the Portal. + /// Gets or sets and Sets the collection of Roles to display. /// - public int PortalId + public ArrayList Roles { get; set; } + + /// + /// Gets or sets and Sets the ResourceFile to localize permissions. + /// + public string ResourceFile { get; set; } + + protected virtual List PermissionsList { get { - // Obtain PortalSettings from Current Context - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - int portalID; - if (Globals.IsHostTab(portalSettings.ActiveTab.TabID)) // if we are in host filemanager then we need to pass a null portal id - { - portalID = Null.NullInteger; - } - else - { - portalID = portalSettings.PortalId; - } - - return portalID; + return null; } } - /// - /// Gets or sets and Sets the collection of Roles to display. - /// - public ArrayList Roles { get; set; } + protected virtual bool RefreshGrid + { + get + { + return false; + } + } + + private int UnAuthUsersRoleId + { + get { return this.unAuthUsersRoleId; } + } + + private int AllUsersRoleId + { + get + { + return this.allUsersRoleId; + } + } /// - /// Gets or sets and Sets the ResourceFile to localize permissions. + /// Registers the scripts neccesary to make the tri-state controls work inside a RadAjaxPanel. /// - public string ResourceFile { get; set; } - + /// + /// 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); + } + /// /// Generate the Data Grid. /// - public abstract void GenerateDataGrid(); - + public abstract void GenerateDataGrid(); + protected virtual void AddPermission(PermissionInfo permission, int roleId, string roleName, int userId, string displayName, bool allowAccess) { } @@ -293,403 +293,45 @@ protected virtual void AddPermission(PermissionInfo permission, int roleId, stri protected virtual void AddPermission(ArrayList permissions, UserInfo user) { } - - private void BindData() + + /// + /// Updates a Permission. + /// + /// The permissions collection. + /// The role to add. + protected virtual void AddPermission(ArrayList permissions, RoleInfo role) { - this.EnsureChildControls(); - this.BindRolesGrid(); - this.BindUsersGrid(); } - private void BindRolesGrid() + /// + /// Builds the key used to store the "permission" information in the ViewState. + /// + /// The type of permission ( grant / deny ). + /// The Id of the permission. + /// The Id of the object permission. + /// The role id. + /// The role name. + /// + protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName) { - this.dtRolePermissions.Columns.Clear(); - this.dtRolePermissions.Rows.Clear(); - - // Add Roles Column - this.dtRolePermissions.Columns.Add(new DataColumn("RoleId")); - - // Add Roles Column - this.dtRolePermissions.Columns.Add(new DataColumn("RoleName")); + return this.BuildKey(allowAccess, permissionId, objectPermissionId, roleId, roleName, Null.NullInteger, Null.NullString); + } - for (int i = 0; i <= this._permissions.Count - 1; i++) - { - var permissionInfo = (PermissionInfo)this._permissions[i]; - - // Add Enabled Column - this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName + "_Enabled")); - - // Add Permission Column - this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName)); - } - - this.GetRoles(); - - this.UpdateRolePermissions(); - for (int i = 0; i <= this.Roles.Count - 1; i++) - { - var role = (RoleInfo)this.Roles[i]; - var row = this.dtRolePermissions.NewRow(); - row["RoleId"] = role.RoleID; - row["RoleName"] = Localization.LocalizeRole(role.RoleName); - int j; - for (j = 0; j <= this._permissions.Count - 1; j++) - { - PermissionInfo objPerm; - objPerm = (PermissionInfo)this._permissions[j]; - row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, role, j + 1); - if (this.SupportsDenyPermissions(objPerm)) - { - row[objPerm.PermissionName] = this.GetPermission(objPerm, role, j + 1, PermissionTypeNull); - } - else - { - if (this.GetPermission(objPerm, role, j + 1)) - { - row[objPerm.PermissionName] = PermissionTypeGrant; - } - else - { - row[objPerm.PermissionName] = PermissionTypeNull; - } - } - } - - this.dtRolePermissions.Rows.Add(row); - } - - this.rolePermissionsGrid.DataSource = this.dtRolePermissions; - this.rolePermissionsGrid.DataBind(); - } - - private void BindUsersGrid() - { - this.dtUserPermissions.Columns.Clear(); - this.dtUserPermissions.Rows.Clear(); - - // Add Roles Column - var col = new DataColumn("UserId"); - this.dtUserPermissions.Columns.Add(col); - - // Add Roles Column - col = new DataColumn("DisplayName"); - this.dtUserPermissions.Columns.Add(col); - int i; - for (i = 0; i <= this._permissions.Count - 1; i++) - { - PermissionInfo objPerm; - objPerm = (PermissionInfo)this._permissions[i]; - - // Add Enabled Column - col = new DataColumn(objPerm.PermissionName + "_Enabled"); - this.dtUserPermissions.Columns.Add(col); - - // Add Permission Column - col = new DataColumn(objPerm.PermissionName); - this.dtUserPermissions.Columns.Add(col); - } - - if (this.userPermissionsGrid != null) - { - this._users = this.GetUsers(); - - if (this._users.Count != 0) - { - this.userPermissionsGrid.Visible = true; - DataRow row; - for (i = 0; i <= this._users.Count - 1; i++) - { - var user = (UserInfo)this._users[i]; - row = this.dtUserPermissions.NewRow(); - row["UserId"] = user.UserID; - row["DisplayName"] = user.DisplayName; - int j; - for (j = 0; j <= this._permissions.Count - 1; j++) - { - PermissionInfo objPerm; - objPerm = (PermissionInfo)this._permissions[j]; - row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, user, j + 1); - if (this.SupportsDenyPermissions(objPerm)) - { - row[objPerm.PermissionName] = this.GetPermission(objPerm, user, j + 1, PermissionTypeNull); - } - else - { - if (this.GetPermission(objPerm, user, j + 1)) - { - row[objPerm.PermissionName] = PermissionTypeGrant; - } - else - { - row[objPerm.PermissionName] = PermissionTypeNull; - } - } - } - - this.dtUserPermissions.Rows.Add(row); - } - - this.userPermissionsGrid.DataSource = this.dtUserPermissions; - this.userPermissionsGrid.DataBind(); - } - else - { - this.dtUserPermissions.Rows.Clear(); - this.userPermissionsGrid.DataSource = this.dtUserPermissions; - this.userPermissionsGrid.DataBind(); - this.userPermissionsGrid.Visible = false; - } - } - } - - private void EnsureRole(RoleInfo role) - { - if (this.Roles.Cast().All(r => r.RoleID != role.RoleID)) - { - this.Roles.Add(role); - } - } - - private void GetRoles() - { - var checkedRoles = this.GetCheckedRoles(); - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - this.Roles = new ArrayList(RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved && checkedRoles.Contains(r.RoleID)).ToArray()); - - if (checkedRoles.Contains(this.UnAuthUsersRoleId)) - { - this.Roles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); - } - - if (checkedRoles.Contains(this.AllUsersRoleId)) - { - this.Roles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); - } - - // Administrators Role always has implicit permissions, then it should be always in - this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId)); - - // Show also default roles - this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.RegisteredRoleId)); - this.EnsureRole(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); - - this.Roles.Reverse(); - this.Roles.Sort(new RoleComparer()); - } - - private IEnumerable GetCheckedRoles() - { - if (this.PermissionsList == null) - { - return new List(); - } - - return this.PermissionsList.Select(r => r.RoleID).Distinct(); - } - - private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColumnDataField, string permissionHeaderText) - { - grid.Columns.Clear(); - 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, - }; - 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), - }; - templateCol.ItemTemplate = columnTemplate; - - var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) // system permission - : (!string.IsNullOrEmpty(this.ResourceFile) ? Localization.GetString(permission.PermissionName + ".Permission", this.ResourceFile) // custom permission - : string.Empty); - templateCol.HeaderText = !string.IsNullOrEmpty(locName) ? locName : permission.PermissionName; - templateCol.HeaderStyle.Wrap = true; - grid.Columns.Add(templateCol); - } - - var actionsColumn = new ImageCommandColumn - { - CommandName = "Delete/" + nameColumnDataField, - KeyField = idColumnDataField, - IconKey = "Delete", - IconSize = "16x16", - IconStyle = "PermissionGrid", - HeaderText = Localization.GetString("PermissionActionsHeader.Text", PermissionProvider.Instance().LocalResourceFile), - }; - grid.Columns.Add(actionsColumn); - grid.ItemCommand += this.grid_ItemCommand; - } - - private void grid_ItemCommand(object source, DataGridCommandEventArgs e) - { - var entityID = int.Parse(e.CommandArgument.ToString()); - var command = this.GetGridCommand(e.CommandName); - var entityType = this.GetCommandType(e.CommandName); - switch (command) - { - case "DELETE": - if (entityType == "ROLE") - { - this.DeleteRolePermissions(entityID); - } - else if (entityType == "USER") - { - this.DeleteUserPermissions(entityID); - } - - this.BindData(); - break; - } - } - - private void DeleteRolePermissions(int entityID) - { - // PermissionsList.RemoveAll(p => p.RoleID == entityID); - var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityID); - foreach (PermissionInfoBase permission in permissionToDelete) - { - this.RemovePermission(permission.PermissionID, entityID, permission.UserID); - } - } - - private void DeleteUserPermissions(int entityID) - { - var permissionToDelete = this.PermissionsList.Where(p => p.UserID == entityID); - foreach (PermissionInfoBase permission in permissionToDelete) - { - this.RemovePermission(permission.PermissionID, permission.RoleID, entityID); - } - } - - private string GetCommandType(string commandName) - { - var command = commandName.ToLower(CultureInfo.InvariantCulture); - if (command.Contains("rolename")) - { - return "ROLE"; - } - - if (command.Contains("displayname")) - { - return "USER"; - } - - return Null.NullString; - } - - private string GetGridCommand(string commandName) - { - var commandParts = commandName.Split('/'); - return commandParts[0].ToUpper(CultureInfo.InvariantCulture); - } - - private void SetUpRolesGrid() - { - this.SetUpGrid(this.rolePermissionsGrid, "RoleName", "roleid", Localization.GetString("PermissionRoleHeader.Text", PermissionProvider.Instance().LocalResourceFile)); - } - - private void SetUpUsersGrid() - { - if (this.userPermissionsGrid != null) - { - this.SetUpGrid(this.userPermissionsGrid, "DisplayName", "userid", Localization.GetString("PermissionUserHeader.Text", PermissionProvider.Instance().LocalResourceFile)); - } - } - - private void FillSelectRoleComboBox(int selectedRoleGroupId) - { - this.cboSelectRole.Items.Clear(); - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var groupRoles = (selectedRoleGroupId > -2) ? RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == selectedRoleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) - : RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); - - if (selectedRoleGroupId < 0) - { - groupRoles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); - groupRoles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, RoleName = Globals.glbRoleAllUsersName }); - } - - foreach (var role in groupRoles.OrderBy(r => r.RoleName)) - { - this.cboSelectRole.Items.Add(new ListItem(role.RoleName, role.RoleID.ToString(CultureInfo.InvariantCulture))); - } - - int[] defaultRoleIds = { this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId }; - var itemToSelect = this.cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value))); - if (itemToSelect != null) - { - this.cboSelectRole.SelectedValue = itemToSelect.Value; - } - } - - private void SetErrorMessage(string errorKey) - { - this.lblErrorMessage = new Label - { - // TODO Remove DEBUG test - Text = "
    " + (errorKey.StartsWith("DEBUG") ? errorKey : Localization.GetString(errorKey)), - CssClass = "NormalRed", - }; - this.pnlPermissions.Controls.Add(this.lblErrorMessage); - } - - /// - /// Updates a Permission. - /// - /// The permissions collection. - /// The role to add. - protected virtual void AddPermission(ArrayList permissions, RoleInfo role) - { - } - - /// - /// Builds the key used to store the "permission" information in the ViewState. - /// - /// The type of permission ( grant / deny ). - /// The Id of the permission. - /// The Id of the object permission. - /// The role id. - /// The role name. - /// - protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName) - { - return this.BuildKey(allowAccess, permissionId, objectPermissionId, roleId, roleName, Null.NullInteger, Null.NullString); - } - - /// - /// Builds the key used to store the "permission" information in the ViewState. - /// - /// The type of permission ( grant / deny ). - /// The Id of the permission. - /// The Id of the object permission. - /// The role id. - /// The role name. - /// The user id. - /// The user display name. - /// - protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName, int userID, string displayName) - { - string key; - if (allowAccess) + /// + /// Builds the key used to store the "permission" information in the ViewState. + /// + /// The type of permission ( grant / deny ). + /// The Id of the permission. + /// The Id of the object permission. + /// The role id. + /// The role name. + /// The user id. + /// The user display name. + /// + protected string BuildKey(bool allowAccess, int permissionId, int objectPermissionId, int roleId, string roleName, int userID, string displayName) + { + string key; + if (allowAccess) { key = "True"; } @@ -697,14 +339,14 @@ protected string BuildKey(bool allowAccess, int permissionId, int objectPermissi { key = "False"; } - + key += "|" + Convert.ToString(permissionId); key += "|"; if (objectPermissionId > -1) { key += Convert.ToString(objectPermissionId); } - + key += "|" + roleName; key += "|" + roleId; key += "|" + userID; @@ -777,478 +419,836 @@ protected override void CreateChildControls() this.pnlPermissions.Controls.Add(divAddUser); } - - this.Controls.Add(this.pnlPermissions); + + 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; + } + + /// + /// Gets the Value of the permission. + /// + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// + protected virtual bool GetPermission(PermissionInfo objPerm, RoleInfo role, int column) + { + return Convert.ToBoolean(this.GetPermission(objPerm, role, column, PermissionTypeDeny)); + } + + /// + /// Gets the Value of the permission. + /// + /// The permission being loaded. + /// The role. + /// The column of the Grid. + /// Default State. + /// + protected virtual string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) + { + string stateKey = defaultState; + if (this.PermissionsList != null) + { + foreach (PermissionInfoBase permission in this.PermissionsList) + { + if (permission.PermissionID == objPerm.PermissionID && permission.RoleID == role.RoleID) + { + if (permission.AllowAccess) + { + stateKey = PermissionTypeGrant; + } + else + { + stateKey = PermissionTypeDeny; + } + + break; + } + } + } + + return stateKey; + } + + /// + /// Gets the Value of the permission. + /// + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// + protected virtual bool GetPermission(PermissionInfo objPerm, UserInfo user, int column) + { + return Convert.ToBoolean(this.GetPermission(objPerm, user, column, PermissionTypeDeny)); + } + + /// + /// Gets the Value of the permission. + /// + /// The permission being loaded. + /// The user. + /// The column of the Grid. + /// Default State. + /// + protected virtual string GetPermission(PermissionInfo objPerm, UserInfo user, int column, string defaultState) + { + var stateKey = defaultState; + if (this.PermissionsList != null) + { + foreach (var permission in this.PermissionsList) + { + if (permission.PermissionID == objPerm.PermissionID && permission.UserID == user.UserID) + { + if (permission.AllowAccess) + { + stateKey = PermissionTypeGrant; + } + else + { + stateKey = PermissionTypeDeny; + } + + break; + } + } + } + + return stateKey; + } + + /// + /// Gets the permissions from the Database. + /// + /// + protected virtual ArrayList GetPermissions() + { + return null; + } + + /// + /// Gets the users from the Database. + /// + /// + protected virtual ArrayList GetUsers() + { + var arrUsers = new ArrayList(); + UserInfo objUser; + if (this.PermissionsList != null) + { + foreach (var permission in this.PermissionsList) + { + if (!Null.IsNull(permission.UserID)) + { + bool blnExists = false; + foreach (UserInfo user in arrUsers) + { + if (permission.UserID == user.UserID) + { + blnExists = true; + } + } + + if (!blnExists) + { + objUser = new UserInfo(); + objUser.UserID = permission.UserID; + objUser.Username = permission.Username; + objUser.DisplayName = permission.DisplayName; + arrUsers.Add(objUser); + } + } + } + } + + return arrUsers; + } + + protected virtual bool IsFullControl(PermissionInfo permissionInfo) + { + return false; + } + + protected virtual bool IsViewPermisison(PermissionInfo permissionInfo) + { + return false; + } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Components/Tokeninput/jquery.tokeninput.js"); + ClientResourceManager.RegisterScript(this.Page, "~/js/dnn.permissiongrid.js"); + + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/Components/Tokeninput/Themes/token-input-facebook.css", FileOrder.Css.ResourceCss); + } + + /// + /// Overrides the base OnPreRender method to Bind the Grid to the Permissions. + /// + protected override void OnPreRender(EventArgs e) + { + this.BindData(); + + var script = "var pgm = new dnn.permissionGridManager('" + this.ClientID + "');"; + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "PermissionGridManager", script, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "PermissionGridManager", script, true); + } + } + + protected virtual void ParsePermissionKeys(PermissionInfoBase permission, string[] Settings) + { + permission.PermissionID = Convert.ToInt32(Settings[1]); + permission.RoleID = Convert.ToInt32(Settings[4]); + permission.RoleName = Settings[3]; + permission.AllowAccess = Convert.ToBoolean(Settings[0]); + permission.UserID = Convert.ToInt32(Settings[5]); + permission.DisplayName = Settings[6]; + } + + protected virtual void RemovePermission(int permissionID, int roleID, int userID) + { + } + + protected virtual bool SupportsDenyPermissions(PermissionInfo permissionInfo) + { + // to maintain backward compatibility the base implementation must always call the simple parameterless version of this method + return false; + } + + /// + /// Updates a Permission. + /// + /// The permission being updated. + /// Rold Id. + /// The name of the role. + /// The value of the permission. + protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, bool allowAccess) + { + this.UpdatePermission(permission, roleId, roleName, allowAccess ? PermissionTypeGrant : PermissionTypeNull); + } + + /// + /// Updates a Permission. + /// + /// The permission being updated. + /// Role Id. + /// The name of the role. + /// The permission state. + protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, string stateKey) + { + this.RemovePermission(permission.PermissionID, roleId, Null.NullInteger); + switch (stateKey) + { + case PermissionTypeGrant: + this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, true); + break; + case PermissionTypeDeny: + this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, false); + break; + } } /// - /// Gets the Enabled status of the permission. + /// Updates a Permission. /// - /// The permission being loaded. - /// The role. - /// The column of the Grid. - /// - protected virtual bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) + /// The permission being updated. + /// The user's displayname. + /// The user's id. + /// The value of the permission. + protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, bool allowAccess) { - return true; + this.UpdatePermission(permission, displayName, userId, allowAccess ? PermissionTypeGrant : PermissionTypeNull); } /// - /// Gets the Enabled status of the permission. + /// Updates a Permission. /// - /// The permission being loaded. - /// The user. - /// The column of the Grid. - /// - protected virtual bool GetEnabled(PermissionInfo objPerm, UserInfo user, int column) + /// The permission being updated. + /// The user's displayname. + /// The user's id. + /// The permission state. + protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey) { - return true; + this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId); + switch (stateKey) + { + case PermissionTypeGrant: + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true); + break; + case PermissionTypeDeny: + this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false); + break; + } } - private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + /// + /// Updates the permissions. + /// + protected void UpdatePermissions() { - var item = e.Item; + this.EnsureChildControls(); + this.GetRoles(); + this.UpdateRolePermissions(); + this._users = this.GetUsers(); + this.UpdateUserPermissions(); + } - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + /// + /// Updates the permissions. + /// + protected void UpdateRolePermissions() + { + if (this.rolePermissionsGrid != null && !this.RefreshGrid) { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == this.AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId) + var rolesList = this.Roles.Cast().ToList(); + foreach (DataGridItem dgi in this.rolePermissionsGrid.Items) { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) + var roleId = int.Parse(dgi.Cells[1].Text); + if (rolesList.All(r => r.RoleID != roleId)) { - actionImage.Visible = false; + continue; + } + + for (int i = 2; i <= dgi.Cells.Count - 2; i++) + { + // all except first two cells which is role names and role ids and last column is Actions + if (dgi.Cells[i].Controls.Count > 0) + { + var permissionInfo = (PermissionInfo)this._permissions[i - 2]; + var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; + if (this.SupportsDenyPermissions(permissionInfo)) + { + this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value); + } + else + { + this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value == PermissionTypeGrant); + } + } } } } } - private void CreateAddRoleControls() + /// + /// Updates the permissions. + /// + protected void UpdateUserPermissions() { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var arrGroups = RoleController.GetRoleGroups(portalSettings.PortalId); - - var addRoleControls = new Panel { CssClass = "dnnFormItem" }; - var divRoleGroups = new Panel { CssClass = "leftGroup" }; - var divSelectRole = new Panel { CssClass = "rightGroup" }; - - this.lblGroups = new Label { Text = Localization.GetString("RoleGroupFilter") }; - this.cboRoleGroups = new DropDownList { AutoPostBack = true, ID = "cboRoleGroups", ViewStateMode = ViewStateMode.Disabled }; - this.lblGroups.AssociatedControlID = this.cboRoleGroups.ID; - divRoleGroups.Controls.Add(this.lblGroups); - - this.cboRoleGroups.SelectedIndexChanged += this.RoleGroupsSelectedIndexChanged; - this.cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); - var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") { Selected = true }; - this.cboRoleGroups.Items.Add(liItem); - foreach (RoleGroupInfo roleGroup in arrGroups) + if (this.userPermissionsGrid != null && !this.RefreshGrid) { - this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); - } - - divRoleGroups.Controls.Add(this.cboRoleGroups); - addRoleControls.Controls.Add(divRoleGroups); - - this.lblSelectRole = new Label { Text = Localization.GetString("RoleSelect") }; - this.cboSelectRole = new DropDownList { ID = "cboSelectRole", ViewStateMode = ViewStateMode.Disabled }; - this.lblSelectRole.AssociatedControlID = this.cboSelectRole.ID; - divSelectRole.Controls.Add(this.lblSelectRole); - - this.FillSelectRoleComboBox(-1); // Default Role Group is Global Roles - divSelectRole.Controls.Add(this.cboSelectRole); - - this.cmdRole = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; - this.cmdRole.Click += this.AddRole; - divSelectRole.Controls.Add(this.cmdRole); - this.roleField = new HiddenField() { ID = "roleField" }; - addRoleControls.Controls.Add(this.roleField); - - addRoleControls.Controls.Add(divSelectRole); + var usersList = this._users.Cast().ToList(); + foreach (DataGridItem dgi in this.userPermissionsGrid.Items) + { + var userId = int.Parse(dgi.Cells[1].Text); + if (usersList.All(u => u.UserID != userId)) + { + continue; + } - this.pnlPermissions.Controls.Add(addRoleControls); + for (int i = 2; i <= dgi.Cells.Count - 2; i++) + { + // all except first two cells which is displayname and userid and Last column is Actions + if (dgi.Cells[i].Controls.Count > 0) + { + var permissionInfo = (PermissionInfo)this._permissions[i - 2]; + var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; + if (this.SupportsDenyPermissions(permissionInfo)) + { + this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value); + } + else + { + this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value == PermissionTypeGrant); + } + } + } + } + } } /// - /// Gets the Value of the permission. + /// RoleGroupsSelectedIndexChanged runs when the Role Group is changed. /// - /// The permission being loaded. - /// The role. - /// The column of the Grid. - /// - protected virtual bool GetPermission(PermissionInfo objPerm, RoleInfo role, int column) + protected virtual void RoleGroupsSelectedIndexChanged(object sender, EventArgs e) { - return Convert.ToBoolean(this.GetPermission(objPerm, role, column, PermissionTypeDeny)); + this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue)); } /// - /// Gets the Value of the permission. + /// AddUser runs when the Add user linkbutton is clicked. /// - /// The permission being loaded. - /// The role. - /// The column of the Grid. - /// Default State. - /// - protected virtual string GetPermission(PermissionInfo objPerm, RoleInfo role, int column, string defaultState) + protected virtual void AddUser(object sender, EventArgs e) { - string stateKey = defaultState; - if (this.PermissionsList != null) + this.UpdatePermissions(); + if (!string.IsNullOrEmpty(this.hiddenUserIds.Value)) { - foreach (PermissionInfoBase permission in this.PermissionsList) + foreach (var id in this.hiddenUserIds.Value.Split(',')) { - if (permission.PermissionID == objPerm.PermissionID && permission.RoleID == role.RoleID) + var userId = Convert.ToInt32(id); + var user = UserController.GetUserById(this.PortalId, userId); + if (user != null) { - if (permission.AllowAccess) - { - stateKey = PermissionTypeGrant; - } - else - { - stateKey = PermissionTypeDeny; - } - - break; + this.AddPermission(this._permissions, user); + this.BindData(); } } + + this.txtUser.Text = this.hiddenUserIds.Value = string.Empty; } - - return stateKey; } - /// - /// Gets the Value of the permission. - /// - /// The permission being loaded. - /// The user. - /// The column of the Grid. - /// - protected virtual bool GetPermission(PermissionInfo objPerm, UserInfo user, int column) + private void BindData() { - return Convert.ToBoolean(this.GetPermission(objPerm, user, column, PermissionTypeDeny)); + this.EnsureChildControls(); + this.BindRolesGrid(); + this.BindUsersGrid(); } - /// - /// Gets the Value of the permission. - /// - /// The permission being loaded. - /// The user. - /// The column of the Grid. - /// Default State. - /// - protected virtual string GetPermission(PermissionInfo objPerm, UserInfo user, int column, string defaultState) + private void BindRolesGrid() { - var stateKey = defaultState; - if (this.PermissionsList != null) + this.dtRolePermissions.Columns.Clear(); + this.dtRolePermissions.Rows.Clear(); + + // Add Roles Column + this.dtRolePermissions.Columns.Add(new DataColumn("RoleId")); + + // Add Roles Column + this.dtRolePermissions.Columns.Add(new DataColumn("RoleName")); + + for (int i = 0; i <= this._permissions.Count - 1; i++) { - foreach (var permission in this.PermissionsList) + var permissionInfo = (PermissionInfo)this._permissions[i]; + + // Add Enabled Column + this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName + "_Enabled")); + + // Add Permission Column + this.dtRolePermissions.Columns.Add(new DataColumn(permissionInfo.PermissionName)); + } + + this.GetRoles(); + + this.UpdateRolePermissions(); + for (int i = 0; i <= this.Roles.Count - 1; i++) + { + var role = (RoleInfo)this.Roles[i]; + var row = this.dtRolePermissions.NewRow(); + row["RoleId"] = role.RoleID; + row["RoleName"] = Localization.LocalizeRole(role.RoleName); + int j; + for (j = 0; j <= this._permissions.Count - 1; j++) { - if (permission.PermissionID == objPerm.PermissionID && permission.UserID == user.UserID) + PermissionInfo objPerm; + objPerm = (PermissionInfo)this._permissions[j]; + row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, role, j + 1); + if (this.SupportsDenyPermissions(objPerm)) { - if (permission.AllowAccess) + row[objPerm.PermissionName] = this.GetPermission(objPerm, role, j + 1, PermissionTypeNull); + } + else + { + if (this.GetPermission(objPerm, role, j + 1)) { - stateKey = PermissionTypeGrant; + row[objPerm.PermissionName] = PermissionTypeGrant; } else { - stateKey = PermissionTypeDeny; + row[objPerm.PermissionName] = PermissionTypeNull; } - - break; } } + + this.dtRolePermissions.Rows.Add(row); } - - return stateKey; - } - /// - /// Gets the permissions from the Database. - /// - /// - protected virtual ArrayList GetPermissions() - { - return null; + this.rolePermissionsGrid.DataSource = this.dtRolePermissions; + this.rolePermissionsGrid.DataBind(); } - /// - /// Gets the users from the Database. - /// - /// - protected virtual ArrayList GetUsers() + private void BindUsersGrid() { - var arrUsers = new ArrayList(); - UserInfo objUser; - if (this.PermissionsList != null) + this.dtUserPermissions.Columns.Clear(); + this.dtUserPermissions.Rows.Clear(); + + // Add Roles Column + var col = new DataColumn("UserId"); + this.dtUserPermissions.Columns.Add(col); + + // Add Roles Column + col = new DataColumn("DisplayName"); + this.dtUserPermissions.Columns.Add(col); + int i; + for (i = 0; i <= this._permissions.Count - 1; i++) { - foreach (var permission in this.PermissionsList) + PermissionInfo objPerm; + objPerm = (PermissionInfo)this._permissions[i]; + + // Add Enabled Column + col = new DataColumn(objPerm.PermissionName + "_Enabled"); + this.dtUserPermissions.Columns.Add(col); + + // Add Permission Column + col = new DataColumn(objPerm.PermissionName); + this.dtUserPermissions.Columns.Add(col); + } + + if (this.userPermissionsGrid != null) + { + this._users = this.GetUsers(); + + if (this._users.Count != 0) { - if (!Null.IsNull(permission.UserID)) + this.userPermissionsGrid.Visible = true; + DataRow row; + for (i = 0; i <= this._users.Count - 1; i++) { - bool blnExists = false; - foreach (UserInfo user in arrUsers) + var user = (UserInfo)this._users[i]; + row = this.dtUserPermissions.NewRow(); + row["UserId"] = user.UserID; + row["DisplayName"] = user.DisplayName; + int j; + for (j = 0; j <= this._permissions.Count - 1; j++) { - if (permission.UserID == user.UserID) + PermissionInfo objPerm; + objPerm = (PermissionInfo)this._permissions[j]; + row[objPerm.PermissionName + "_Enabled"] = this.GetEnabled(objPerm, user, j + 1); + if (this.SupportsDenyPermissions(objPerm)) { - blnExists = true; + row[objPerm.PermissionName] = this.GetPermission(objPerm, user, j + 1, PermissionTypeNull); + } + else + { + if (this.GetPermission(objPerm, user, j + 1)) + { + row[objPerm.PermissionName] = PermissionTypeGrant; + } + else + { + row[objPerm.PermissionName] = PermissionTypeNull; + } } } - - if (!blnExists) - { - objUser = new UserInfo(); - objUser.UserID = permission.UserID; - objUser.Username = permission.Username; - objUser.DisplayName = permission.DisplayName; - arrUsers.Add(objUser); - } + + this.dtUserPermissions.Rows.Add(row); } + + this.userPermissionsGrid.DataSource = this.dtUserPermissions; + this.userPermissionsGrid.DataBind(); + } + else + { + this.dtUserPermissions.Rows.Clear(); + this.userPermissionsGrid.DataSource = this.dtUserPermissions; + this.userPermissionsGrid.DataBind(); + this.userPermissionsGrid.Visible = false; } } - - return arrUsers; } - protected virtual bool IsFullControl(PermissionInfo permissionInfo) + private void EnsureRole(RoleInfo role) { - return false; + if (this.Roles.Cast().All(r => r.RoleID != role.RoleID)) + { + this.Roles.Add(role); + } } - protected virtual bool IsViewPermisison(PermissionInfo permissionInfo) + private void GetRoles() { - return false; + var checkedRoles = this.GetCheckedRoles(); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + this.Roles = new ArrayList(RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved && checkedRoles.Contains(r.RoleID)).ToArray()); + + if (checkedRoles.Contains(this.UnAuthUsersRoleId)) + { + this.Roles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); + } + + if (checkedRoles.Contains(this.AllUsersRoleId)) + { + this.Roles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); + } + + // Administrators Role always has implicit permissions, then it should be always in + this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.AdministratorRoleId)); + + // Show also default roles + this.EnsureRole(RoleController.Instance.GetRoleById(portalSettings.PortalId, portalSettings.RegisteredRoleId)); + this.EnsureRole(new RoleInfo { RoleID = this.AllUsersRoleId, PortalID = portalSettings.PortalId, RoleName = Globals.glbRoleAllUsersName }); + + this.Roles.Reverse(); + this.Roles.Sort(new RoleComparer()); } - protected override void OnInit(EventArgs e) + private IEnumerable GetCheckedRoles() { - base.OnInit(e); + if (this.PermissionsList == null) + { + return new List(); + } - ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); + return this.PermissionsList.Select(r => r.RoleID).Distinct(); + } - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Components/Tokeninput/jquery.tokeninput.js"); - ClientResourceManager.RegisterScript(this.Page, "~/js/dnn.permissiongrid.js"); + private void SetUpGrid(DataGrid grid, string nameColumnDataField, string idColumnDataField, string permissionHeaderText) + { + grid.Columns.Clear(); + var nameColumn = new BoundColumn + { + HeaderText = permissionHeaderText, + DataField = nameColumnDataField, + }; + nameColumn.ItemStyle.CssClass = "permissionHeader"; + nameColumn.HeaderStyle.CssClass = "permissionHeader"; + grid.Columns.Add(nameColumn); - ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/Components/Tokeninput/Themes/token-input-facebook.css", FileOrder.Css.ResourceCss); + 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), + }; + templateCol.ItemTemplate = columnTemplate; + + var locName = (permission.ModuleDefID <= 0) ? Localization.GetString(permission.PermissionName + ".Permission", PermissionProvider.Instance().LocalResourceFile) // system permission + : (!string.IsNullOrEmpty(this.ResourceFile) ? Localization.GetString(permission.PermissionName + ".Permission", this.ResourceFile) // custom permission + : string.Empty); + templateCol.HeaderText = !string.IsNullOrEmpty(locName) ? locName : permission.PermissionName; + templateCol.HeaderStyle.Wrap = true; + grid.Columns.Add(templateCol); + } + + var actionsColumn = new ImageCommandColumn + { + CommandName = "Delete/" + nameColumnDataField, + KeyField = idColumnDataField, + IconKey = "Delete", + IconSize = "16x16", + IconStyle = "PermissionGrid", + HeaderText = Localization.GetString("PermissionActionsHeader.Text", PermissionProvider.Instance().LocalResourceFile), + }; + grid.Columns.Add(actionsColumn); + grid.ItemCommand += this.grid_ItemCommand; } - /// - /// Overrides the base OnPreRender method to Bind the Grid to the Permissions. - /// - protected override void OnPreRender(EventArgs e) + private void grid_ItemCommand(object source, DataGridCommandEventArgs e) { - this.BindData(); - - var script = "var pgm = new dnn.permissionGridManager('" + this.ClientID + "');"; - if (ScriptManager.GetCurrent(this.Page) != null) + var entityID = int.Parse(e.CommandArgument.ToString()); + var command = this.GetGridCommand(e.CommandName); + var entityType = this.GetCommandType(e.CommandName); + switch (command) { - // respect MS AJAX - ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.ClientID + "PermissionGridManager", script, true); + case "DELETE": + if (entityType == "ROLE") + { + this.DeleteRolePermissions(entityID); + } + else if (entityType == "USER") + { + this.DeleteUserPermissions(entityID); + } + + this.BindData(); + break; } - else + } + + private void DeleteRolePermissions(int entityID) + { + // PermissionsList.RemoveAll(p => p.RoleID == entityID); + var permissionToDelete = this.PermissionsList.Where(p => p.RoleID == entityID); + foreach (PermissionInfoBase permission in permissionToDelete) { - this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID + "PermissionGridManager", script, true); + this.RemovePermission(permission.PermissionID, entityID, permission.UserID); } } - - protected virtual void ParsePermissionKeys(PermissionInfoBase permission, string[] Settings) + + private void DeleteUserPermissions(int entityID) { - permission.PermissionID = Convert.ToInt32(Settings[1]); - permission.RoleID = Convert.ToInt32(Settings[4]); - permission.RoleName = Settings[3]; - permission.AllowAccess = Convert.ToBoolean(Settings[0]); - permission.UserID = Convert.ToInt32(Settings[5]); - permission.DisplayName = Settings[6]; + var permissionToDelete = this.PermissionsList.Where(p => p.UserID == entityID); + foreach (PermissionInfoBase permission in permissionToDelete) + { + this.RemovePermission(permission.PermissionID, permission.RoleID, entityID); + } } - protected virtual void RemovePermission(int permissionID, int roleID, int userID) + private string GetCommandType(string commandName) { + var command = commandName.ToLower(CultureInfo.InvariantCulture); + if (command.Contains("rolename")) + { + return "ROLE"; + } + + if (command.Contains("displayname")) + { + return "USER"; + } + + return Null.NullString; } - protected virtual bool SupportsDenyPermissions(PermissionInfo permissionInfo) + private string GetGridCommand(string commandName) { - // to maintain backward compatibility the base implementation must always call the simple parameterless version of this method - return false; + var commandParts = commandName.Split('/'); + return commandParts[0].ToUpper(CultureInfo.InvariantCulture); } - /// - /// Updates a Permission. - /// - /// The permission being updated. - /// Rold Id. - /// The name of the role. - /// The value of the permission. - protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, bool allowAccess) + private void SetUpRolesGrid() { - this.UpdatePermission(permission, roleId, roleName, allowAccess ? PermissionTypeGrant : PermissionTypeNull); + this.SetUpGrid(this.rolePermissionsGrid, "RoleName", "roleid", Localization.GetString("PermissionRoleHeader.Text", PermissionProvider.Instance().LocalResourceFile)); } - /// - /// Updates a Permission. - /// - /// The permission being updated. - /// Role Id. - /// The name of the role. - /// The permission state. - protected virtual void UpdatePermission(PermissionInfo permission, int roleId, string roleName, string stateKey) + private void SetUpUsersGrid() { - this.RemovePermission(permission.PermissionID, roleId, Null.NullInteger); - switch (stateKey) + if (this.userPermissionsGrid != null) { - case PermissionTypeGrant: - this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, true); - break; - case PermissionTypeDeny: - this.AddPermission(permission, roleId, roleName, Null.NullInteger, Null.NullString, false); - break; + this.SetUpGrid(this.userPermissionsGrid, "DisplayName", "userid", Localization.GetString("PermissionUserHeader.Text", PermissionProvider.Instance().LocalResourceFile)); } } - /// - /// Updates a Permission. - /// - /// The permission being updated. - /// The user's displayname. - /// The user's id. - /// The value of the permission. - protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, bool allowAccess) + private void FillSelectRoleComboBox(int selectedRoleGroupId) { - this.UpdatePermission(permission, displayName, userId, allowAccess ? PermissionTypeGrant : PermissionTypeNull); - } + this.cboSelectRole.Items.Clear(); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var groupRoles = (selectedRoleGroupId > -2) ? RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.RoleGroupID == selectedRoleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) + : RoleController.Instance.GetRoles(portalSettings.PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); - /// - /// Updates a Permission. - /// - /// The permission being updated. - /// The user's displayname. - /// The user's id. - /// The permission state. - protected virtual void UpdatePermission(PermissionInfo permission, string displayName, int userId, string stateKey) - { - this.RemovePermission(permission.PermissionID, int.Parse(Globals.glbRoleNothing), userId); - switch (stateKey) + if (selectedRoleGroupId < 0) { - case PermissionTypeGrant: - this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, true); - break; - case PermissionTypeDeny: - this.AddPermission(permission, int.Parse(Globals.glbRoleNothing), Null.NullString, userId, displayName, false); - break; + groupRoles.Add(new RoleInfo { RoleID = this.UnAuthUsersRoleId, RoleName = Globals.glbRoleUnauthUserName }); + groupRoles.Add(new RoleInfo { RoleID = this.AllUsersRoleId, RoleName = Globals.glbRoleAllUsersName }); + } + + foreach (var role in groupRoles.OrderBy(r => r.RoleName)) + { + this.cboSelectRole.Items.Add(new ListItem(role.RoleName, role.RoleID.ToString(CultureInfo.InvariantCulture))); + } + + int[] defaultRoleIds = { this.AllUsersRoleId, portalSettings.RegisteredRoleId, portalSettings.AdministratorRoleId }; + var itemToSelect = this.cboSelectRole.Items.Cast().FirstOrDefault(i => !defaultRoleIds.Contains(int.Parse(i.Value))); + if (itemToSelect != null) + { + this.cboSelectRole.SelectedValue = itemToSelect.Value; } - } - - /// - /// Updates the permissions. - /// - protected void UpdatePermissions() - { - this.EnsureChildControls(); - this.GetRoles(); - this.UpdateRolePermissions(); - this._users = this.GetUsers(); - this.UpdateUserPermissions(); } - /// - /// Updates the permissions. - /// - protected void UpdateRolePermissions() + private void SetErrorMessage(string errorKey) { - if (this.rolePermissionsGrid != null && !this.RefreshGrid) + this.lblErrorMessage = new Label { - var rolesList = this.Roles.Cast().ToList(); - foreach (DataGridItem dgi in this.rolePermissionsGrid.Items) - { - var roleId = int.Parse(dgi.Cells[1].Text); - if (rolesList.All(r => r.RoleID != roleId)) - { - continue; - } - - for (int i = 2; i <= dgi.Cells.Count - 2; i++) - { - // all except first two cells which is role names and role ids and last column is Actions - if (dgi.Cells[i].Controls.Count > 0) - { - var permissionInfo = (PermissionInfo)this._permissions[i - 2]; - var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; - if (this.SupportsDenyPermissions(permissionInfo)) - { - this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value); - } - else - { - this.UpdatePermission(permissionInfo, roleId, dgi.Cells[0].Text, triState.Value == PermissionTypeGrant); - } - } - } - } - } + // TODO Remove DEBUG test + Text = "
    " + (errorKey.StartsWith("DEBUG") ? errorKey : Localization.GetString(errorKey)), + CssClass = "NormalRed", + }; + this.pnlPermissions.Controls.Add(this.lblErrorMessage); } - /// - /// Updates the permissions. - /// - protected void UpdateUserPermissions() + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) { - if (this.userPermissionsGrid != null && !this.RefreshGrid) + var item = e.Item; + + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) { - var usersList = this._users.Cast().ToList(); - foreach (DataGridItem dgi in this.userPermissionsGrid.Items) + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (roleID == PortalSettings.Current.AdministratorRoleId || roleID == this.AllUsersRoleId || roleID == PortalSettings.Current.RegisteredRoleId) { - var userId = int.Parse(dgi.Cells[1].Text); - if (usersList.All(u => u.UserID != userId)) - { - continue; - } - - for (int i = 2; i <= dgi.Cells.Count - 2; i++) + var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; + if (actionImage != null) { - // all except first two cells which is displayname and userid and Last column is Actions - if (dgi.Cells[i].Controls.Count > 0) - { - var permissionInfo = (PermissionInfo)this._permissions[i - 2]; - var triState = (PermissionTriState)dgi.Cells[i].Controls[0]; - if (this.SupportsDenyPermissions(permissionInfo)) - { - this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value); - } - else - { - this.UpdatePermission(permissionInfo, dgi.Cells[0].Text, userId, triState.Value == PermissionTypeGrant); - } - } + actionImage.Visible = false; } } } - } - - /// - /// RoleGroupsSelectedIndexChanged runs when the Role Group is changed. - /// - protected virtual void RoleGroupsSelectedIndexChanged(object sender, EventArgs e) - { - this.FillSelectRoleComboBox(int.Parse(this.cboRoleGroups.SelectedValue)); } - /// - /// AddUser runs when the Add user linkbutton is clicked. - /// - protected virtual void AddUser(object sender, EventArgs e) + private void CreateAddRoleControls() { - this.UpdatePermissions(); - if (!string.IsNullOrEmpty(this.hiddenUserIds.Value)) - { - foreach (var id in this.hiddenUserIds.Value.Split(',')) - { - var userId = Convert.ToInt32(id); - var user = UserController.GetUserById(this.PortalId, userId); - if (user != null) - { - this.AddPermission(this._permissions, user); - this.BindData(); - } - } + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var arrGroups = RoleController.GetRoleGroups(portalSettings.PortalId); - this.txtUser.Text = this.hiddenUserIds.Value = string.Empty; + var addRoleControls = new Panel { CssClass = "dnnFormItem" }; + var divRoleGroups = new Panel { CssClass = "leftGroup" }; + var divSelectRole = new Panel { CssClass = "rightGroup" }; + + this.lblGroups = new Label { Text = Localization.GetString("RoleGroupFilter") }; + this.cboRoleGroups = new DropDownList { AutoPostBack = true, ID = "cboRoleGroups", ViewStateMode = ViewStateMode.Disabled }; + this.lblGroups.AssociatedControlID = this.cboRoleGroups.ID; + divRoleGroups.Controls.Add(this.lblGroups); + + this.cboRoleGroups.SelectedIndexChanged += this.RoleGroupsSelectedIndexChanged; + this.cboRoleGroups.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); + var liItem = new ListItem(Localization.GetString("GlobalRoles"), "-1") { Selected = true }; + this.cboRoleGroups.Items.Add(liItem); + foreach (RoleGroupInfo roleGroup in arrGroups) + { + this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); } + + divRoleGroups.Controls.Add(this.cboRoleGroups); + addRoleControls.Controls.Add(divRoleGroups); + + this.lblSelectRole = new Label { Text = Localization.GetString("RoleSelect") }; + this.cboSelectRole = new DropDownList { ID = "cboSelectRole", ViewStateMode = ViewStateMode.Disabled }; + this.lblSelectRole.AssociatedControlID = this.cboSelectRole.ID; + divSelectRole.Controls.Add(this.lblSelectRole); + + this.FillSelectRoleComboBox(-1); // Default Role Group is Global Roles + divSelectRole.Controls.Add(this.cboSelectRole); + + this.cmdRole = new LinkButton { Text = Localization.GetString("Add"), CssClass = "dnnSecondaryAction" }; + this.cmdRole.Click += this.AddRole; + divSelectRole.Controls.Add(this.cmdRole); + this.roleField = new HiddenField() { ID = "roleField" }; + addRoleControls.Controls.Add(this.roleField); + + addRoleControls.Controls.Add(divSelectRole); + + this.pnlPermissions.Controls.Add(addRoleControls); } /// @@ -1302,8 +1302,8 @@ private RoleInfo GetSelectedRole(int selectedRoleId) { role = RoleController.Instance.GetRoleById(this.PortalId, selectedRoleId); } - + return role; - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs index 7254464461e..337e0a6deb7 100644 --- a/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs +++ b/DNN Platform/Library/Security/Permissions/Controls/TabPermissionsGrid.cs @@ -20,10 +20,10 @@ namespace DotNetNuke.Security.Permissions.Controls using DotNetNuke.Security.Roles; public class TabPermissionsGrid : PermissionsGrid - { + { private List _PermissionsList; private int _TabID = -1; - private TabPermissionCollection _TabPermissions; + private TabPermissionCollection _TabPermissions; /// ----------------------------------------------------------------------------- /// @@ -53,7 +53,7 @@ public int TabID { return this._TabID; } - + set { this._TabID = value; @@ -72,30 +72,30 @@ protected override List PermissionsList { this._PermissionsList = this._TabPermissions.ToList(); } - + return this._PermissionsList; } } - - protected override bool IsFullControl(PermissionInfo permissionInfo) + + public override void DataBind() { - return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); + this.GetTabPermissions(); + base.DataBind(); } - protected override bool IsViewPermisison(PermissionInfo permissionInfo) + public override void GenerateDataGrid() { - return permissionInfo.PermissionKey == "VIEW"; } - public override void DataBind() + protected override bool IsFullControl(PermissionInfo permissionInfo) { - this.GetTabPermissions(); - base.DataBind(); + return (permissionInfo.PermissionKey == "EDIT") && PermissionProvider.Instance().SupportsFullControl(); } - - public override void GenerateDataGrid() + + protected override bool IsViewPermisison(PermissionInfo permissionInfo) { - } + return permissionInfo.PermissionKey == "VIEW"; + } protected override void CreateChildControls() { @@ -118,66 +118,6 @@ protected override void AddPermission(PermissionInfo permission, int roleId, str this._PermissionsList = null; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the TabPermissions from the Data Store. - /// - /// ----------------------------------------------------------------------------- - private void GetTabPermissions() - { - this._TabPermissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(this.TabID, this.PortalId)); - this._PermissionsList = null; - } - - /// ----------------------------------------------------------------------------- - /// - /// Parse the Permission Keys used to persist the Permissions in the ViewState. - /// - /// A string array of settings. - /// ----------------------------------------------------------------------------- - private TabPermissionInfo ParseKeys(string[] Settings) - { - var objTabPermission = new TabPermissionInfo(); - - // Call base class to load base properties - this.ParsePermissionKeys(objTabPermission, Settings); - if (string.IsNullOrEmpty(Settings[2])) - { - objTabPermission.TabPermissionID = -1; - } - else - { - objTabPermission.TabPermissionID = Convert.ToInt32(Settings[2]); - } - - objTabPermission.TabID = this.TabID; - - return objTabPermission; - } - - private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) - { - var item = e.Item; - - if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) - { - var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); - if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) - { - var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; - if (actionImage != null) - { - actionImage.Visible = false; - } - } - } - } - - private bool IsImplicitRole(int portalId, int roleId) - { - return TabPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); - } - /// ----------------------------------------------------------------------------- /// /// Updates a Permission. @@ -242,7 +182,7 @@ protected override void AddPermission(ArrayList permissions, RoleInfo role) /// /// The permission being loaded. /// The role. - /// The column of the Grid. + /// The column of the Grid. /// /// ----------------------------------------------------------------------------- protected override bool GetEnabled(PermissionInfo objPerm, RoleInfo role, int column) @@ -273,14 +213,14 @@ protected override string GetPermission(PermissionInfo objPerm, RoleInfo role, i // Call base class method to handle standard permissions permission = base.GetPermission(objPerm, role, column, PermissionTypeNull); } - + return permission; } /// ----------------------------------------------------------------------------- /// /// Gets the permissions from the Database. - /// + /// /// /// ----------------------------------------------------------------------------- protected override ArrayList GetPermissions() @@ -335,7 +275,7 @@ protected override void LoadViewState(object savedState) protected override void RemovePermission(int permissionID, int roleID, int userID) { this._TabPermissions.Remove(permissionID, roleID, userID); - + // Clear Permission List this._PermissionsList = null; } @@ -343,7 +283,7 @@ protected override void RemovePermission(int permissionID, int roleID, int userI /// ----------------------------------------------------------------------------- /// /// Saves the ViewState. - /// + /// /// /// ----------------------------------------------------------------------------- protected override object SaveViewState() @@ -371,8 +311,8 @@ protected override object SaveViewState() { addDelimiter = true; } - - sb.Append(this.BuildKey( + + sb.Append(this.BuildKey( objTabPermission.AllowAccess, objTabPermission.PermissionID, objTabPermission.TabPermissionID, @@ -382,7 +322,7 @@ protected override object SaveViewState() objTabPermission.DisplayName)); } } - + allStates[2] = sb.ToString(); return allStates; } @@ -390,12 +330,72 @@ protected override object SaveViewState() /// ----------------------------------------------------------------------------- /// /// returns whether or not the derived grid supports Deny permissions. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override bool SupportsDenyPermissions(PermissionInfo permissionInfo) { return true; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the TabPermissions from the Data Store. + /// + /// ----------------------------------------------------------------------------- + private void GetTabPermissions() + { + this._TabPermissions = new TabPermissionCollection(TabPermissionController.GetTabPermissions(this.TabID, this.PortalId)); + this._PermissionsList = null; + } + + /// ----------------------------------------------------------------------------- + /// + /// Parse the Permission Keys used to persist the Permissions in the ViewState. + /// + /// A string array of settings. + /// ----------------------------------------------------------------------------- + private TabPermissionInfo ParseKeys(string[] Settings) + { + var objTabPermission = new TabPermissionInfo(); + + // Call base class to load base properties + this.ParsePermissionKeys(objTabPermission, Settings); + if (string.IsNullOrEmpty(Settings[2])) + { + objTabPermission.TabPermissionID = -1; + } + else + { + objTabPermission.TabPermissionID = Convert.ToInt32(Settings[2]); + } + + objTabPermission.TabID = this.TabID; + + return objTabPermission; + } + + private void rolePermissionsGrid_ItemDataBound(object sender, DataGridItemEventArgs e) + { + var item = e.Item; + + if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.SelectedItem) + { + var roleID = int.Parse(((DataRowView)item.DataItem)[0].ToString()); + if (this.IsImplicitRole(PortalSettings.Current.PortalId, roleID)) + { + var actionImage = item.Controls.Cast().Last().Controls[0] as ImageButton; + if (actionImage != null) + { + actionImage.Visible = false; + } + } + } + } + + private bool IsImplicitRole(int portalId, int roleId) + { + return TabPermissionController.ImplicitRoles(portalId).Any(r => r.RoleID == roleId); + } } } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs index 4a4a1939eb6..17f73234da1 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionCollection.cs @@ -53,7 +53,7 @@ public DesktopModulePermissionInfo this[int index] { return (DesktopModulePermissionInfo)this.List[index]; } - + set { this.List[index] = value; @@ -83,7 +83,7 @@ public int Add(DesktopModulePermissionInfo value, bool checkForDuplicates) break; } } - + if (!isMatch) { id = this.Add(value); @@ -115,7 +115,7 @@ public bool CompareTo(DesktopModulePermissionCollection objDesktopModulePermissi { return false; } - + this.InnerList.Sort(new CompareDesktopModulePermissions()); objDesktopModulePermissionCollection.InnerList.Sort(new CompareDesktopModulePermissions()); for (int i = 0; i <= this.Count - 1; i++) @@ -125,7 +125,7 @@ public bool CompareTo(DesktopModulePermissionCollection objDesktopModulePermissi return false; } } - + return true; } @@ -168,7 +168,7 @@ public List ToList() { list.Add(permission); } - + return list; } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs index 1daa26576e3..34f5d69106d 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionController.cs @@ -28,24 +28,24 @@ namespace DotNetNuke.Security.Permissions public class DesktopModulePermissionController { private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - + /// ----------------------------------------------------------------------------- /// /// AddDesktopModulePermission adds a DesktopModule Permission to the Database. /// - /// The DesktopModule Permission to add. + /// The DesktopModule Permission to add. /// /// ----------------------------------------------------------------------------- public static int AddDesktopModulePermission(DesktopModulePermissionInfo objDesktopModulePermission) { - int Id = DataProvider.Instance().AddDesktopModulePermission( + int Id = DataProvider.Instance().AddDesktopModulePermission( objDesktopModulePermission.PortalDesktopModuleID, objDesktopModulePermission.PermissionID, objDesktopModulePermission.RoleID, objDesktopModulePermission.AllowAccess, objDesktopModulePermission.UserID, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( objDesktopModulePermission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, @@ -64,7 +64,7 @@ public static int AddDesktopModulePermission(DesktopModulePermissionInfo objDesk public static void DeleteDesktopModulePermission(int DesktopModulePermissionID) { DataProvider.Instance().DeleteDesktopModulePermission(DesktopModulePermissionID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "DesktopModulePermissionID", DesktopModulePermissionID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), @@ -73,16 +73,6 @@ public static void DeleteDesktopModulePermission(int DesktopModulePermissionID) ClearPermissionCache(); } - /// ----------------------------------------------------------------------------- - /// - /// ClearPermissionCache clears the DesktopModule Permission Cache. - /// - /// ----------------------------------------------------------------------------- - private static void ClearPermissionCache() - { - DataCache.ClearDesktopModulePermissionsCache(); - } - /// ----------------------------------------------------------------------------- /// /// DeleteDesktopModulePermissionsByPortalDesktopModuleID deletes a DesktopModule's @@ -93,7 +83,7 @@ private static void ClearPermissionCache() public static void DeleteDesktopModulePermissionsByPortalDesktopModuleID(int portalDesktopModuleID) { DataProvider.Instance().DeleteDesktopModulePermissionsByPortalDesktopModuleID(portalDesktopModuleID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PortalDesktopModuleID", portalDesktopModuleID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), @@ -111,7 +101,7 @@ public static void DeleteDesktopModulePermissionsByPortalDesktopModuleID(int por public static void DeleteDesktopModulePermissionsByUserID(UserInfo objUser) { DataProvider.Instance().DeleteDesktopModulePermissionsByUserID(objUser.UserID, objUser.PortalID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "UserID", objUser.UserID.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), @@ -124,7 +114,7 @@ public static void DeleteDesktopModulePermissionsByUserID(UserInfo objUser) /// /// GetDesktopModulePermission gets a DesktopModule Permission from the Database. /// - /// The ID of the DesktopModule Permission. + /// The ID of the DesktopModule Permission. /// /// ----------------------------------------------------------------------------- public static DesktopModulePermissionInfo GetDesktopModulePermission(int DesktopModulePermissionID) @@ -136,7 +126,7 @@ public static DesktopModulePermissionInfo GetDesktopModulePermission(int Desktop /// /// GetDesktopModulePermissions gets a DesktopModulePermissionCollection. /// - /// The ID of the DesktopModule. + /// The ID of the DesktopModule. /// /// ----------------------------------------------------------------------------- public static DesktopModulePermissionCollection GetDesktopModulePermissions(int portalDesktopModuleID) @@ -149,7 +139,7 @@ public static DesktopModulePermissionCollection GetDesktopModulePermissions(int /// HasDesktopModulePermission checks whether the current user has a specific DesktopModule Permission. /// /// The Permissions for the DesktopModule. - /// The Permission to check. + /// The Permission to check. /// /// ----------------------------------------------------------------------------- public static bool HasDesktopModulePermission(DesktopModulePermissionCollection objDesktopModulePermissions, string permissionKey) @@ -165,7 +155,7 @@ public static bool HasDesktopModulePermission(DesktopModulePermissionCollection /// ----------------------------------------------------------------------------- public static void UpdateDesktopModulePermission(DesktopModulePermissionInfo objDesktopModulePermission) { - DataProvider.Instance().UpdateDesktopModulePermission( + DataProvider.Instance().UpdateDesktopModulePermission( objDesktopModulePermission.DesktopModulePermissionID, objDesktopModulePermission.PortalDesktopModuleID, objDesktopModulePermission.PermissionID, @@ -173,13 +163,23 @@ public static void UpdateDesktopModulePermission(DesktopModulePermissionInfo obj objDesktopModulePermission.AllowAccess, objDesktopModulePermission.UserID, UserController.Instance.GetCurrentUserInfo().UserID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( objDesktopModulePermission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.DESKTOPMODULEPERMISSION_UPDATED); ClearPermissionCache(); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// ClearPermissionCache clears the DesktopModule Permission Cache. + /// + /// ----------------------------------------------------------------------------- + private static void ClearPermissionCache() + { + DataCache.ClearDesktopModulePermissionsCache(); + } } } diff --git a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs index 5a8cab91ec0..99d77b2b8de 100644 --- a/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/DesktopModulePermissionInfo.cs @@ -21,13 +21,13 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- [Serializable] public class DesktopModulePermissionInfo : PermissionInfoBase, IHydratable - { - // local property declarations + { + // local property declarations private int _desktopModulePermissionID; - private int _portalDesktopModuleID; - + private int _portalDesktopModuleID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new DesktopModulePermissionInfo. /// @@ -36,16 +36,16 @@ public DesktopModulePermissionInfo() { this._desktopModulePermissionID = Null.NullInteger; this._portalDesktopModuleID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new DesktopModulePermissionInfo. /// /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public DesktopModulePermissionInfo(PermissionInfo permission) + public DesktopModulePermissionInfo(PermissionInfo permission) : this() { this.ModuleDefID = permission.ModuleDefID; @@ -53,8 +53,8 @@ public DesktopModulePermissionInfo(PermissionInfo permission) this.PermissionID = permission.PermissionID; this.PermissionKey = permission.PermissionKey; this.PermissionName = permission.PermissionName; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the DesktopModule Permission ID. @@ -67,7 +67,7 @@ public int DesktopModulePermissionID { return this._desktopModulePermissionID; } - + set { this._desktopModulePermissionID = value; @@ -86,12 +86,12 @@ public int PortalDesktopModuleID { return this._portalDesktopModuleID; } - + set { this._portalDesktopModuleID = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -105,13 +105,13 @@ public int KeyID { return this.DesktopModulePermissionID; } - + set { this.DesktopModulePermissionID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a DesktopModulePermissionInfo from a Data Reader. @@ -124,7 +124,7 @@ public void Fill(IDataReader dr) this.DesktopModulePermissionID = Null.SetNullInteger(dr["DesktopModulePermissionID"]); this.PortalDesktopModuleID = Null.SetNullInteger(dr["PortalDesktopModuleID"]); } - + /// ----------------------------------------------------------------------------- /// /// Compares if two DesktopModulePermissionInfo objects are equivalent/equal. @@ -145,12 +145,12 @@ public bool Equals(DesktopModulePermissionInfo other) { return false; } - + if (ReferenceEquals(this, other)) { return true; } - + return (this.AllowAccess == other.AllowAccess) && (this.PortalDesktopModuleID == other.PortalDesktopModuleID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } @@ -174,17 +174,17 @@ public override bool Equals(object obj) { return false; } - + if (ReferenceEquals(this, obj)) { return true; } - + if (obj.GetType() != typeof(DesktopModulePermissionInfo)) { return false; } - + return this.Equals((DesktopModulePermissionInfo)obj); } @@ -194,6 +194,6 @@ public override int GetHashCode() { return (this._desktopModulePermissionID * 397) ^ this._portalDesktopModuleID; } - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs index ba262ea8e37..00f56925a9b 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionCollection.cs @@ -43,7 +43,7 @@ public FolderPermissionInfo this[int index] { return (FolderPermissionInfo)this.List[index]; } - + set { this.List[index] = value; @@ -73,7 +73,7 @@ public int Add(FolderPermissionInfo value, bool checkForDuplicates) break; } } - + if (!isMatch) { id = this.Add(value); @@ -142,17 +142,17 @@ public bool Contains(string key, int folderId, int roleId, int userId) break; } } - + return result; } - + public bool CompareTo(FolderPermissionCollection objFolderPermissionCollection) { if (objFolderPermissionCollection.Count != this.Count) { return false; } - + this.InnerList.Sort(new CompareFolderPermissions()); objFolderPermissionCollection.InnerList.Sort(new CompareFolderPermissions()); for (int i = 0; i <= this.Count - 1; i++) @@ -162,7 +162,7 @@ public bool CompareTo(FolderPermissionCollection objFolderPermissionCollection) return false; } } - + return true; } @@ -173,7 +173,7 @@ public List ToList() { list.Add(permission); } - + return list; } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs index b3db7f2d3b4..36c0088aac3 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionController.cs @@ -35,48 +35,6 @@ public static bool CanAddFolder(FolderInfo folder) { return provider.CanAddFolder(folder); } - - /// - /// Returns a flag indicating whether the current user can add a folder or file. - /// - /// The page. - /// A flag indicating whether the user has permission. - bool IFolderPermissionController.CanAddFolder(IFolderInfo folder) - { - return provider.CanAddFolder((FolderInfo)folder); - } - - /// - /// Returns a flag indicating whether the current user can addmister a folder. - /// - /// The page. - /// A flag indicating whether the user has permission. - 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. - /// - /// The page. - /// A flag indicating whether the user has permission. - bool IFolderPermissionController.CanViewFolder(IFolderInfo folder) - { - return provider.CanViewFolder((FolderInfo)folder); - } - - private static void ClearPermissionCache(int PortalID) - { - DataCache.ClearFolderPermissionsCache(PortalID); - DataCache.ClearCache(string.Format("Folders|{0}|", PortalID)); - DataCache.ClearFolderCache(PortalID); - } /// /// Returns a flag indicating whether the current user can addmister a folder. @@ -175,7 +133,7 @@ public static bool HasFolderPermission(FolderPermissionCollection objFolderPermi hasPermission = provider.HasFolderPermission(objFolderPermissions, PermissionKey); } } - + return hasPermission; } @@ -214,6 +172,18 @@ public static void SaveFolderPermissions(IFolderInfo folder) ClearPermissionCache(folder.PortalID); } + protected override Func GetFactory() + { + return () => new FolderPermissionController(); + } + + private static void ClearPermissionCache(int PortalID) + { + DataCache.ClearFolderPermissionsCache(PortalID); + DataCache.ClearCache(string.Format("Folders|{0}|", PortalID)); + DataCache.ClearFolderCache(PortalID); + } + private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, FolderPermissionCollection newPermissions) { bool clearCache = Null.NullBoolean; @@ -227,11 +197,41 @@ private static bool CopyPermissionsToSubfoldersRecursive(IFolderInfo folder, Fol SaveFolderPermissions(f); clearCache = true; } - + clearCache = CopyPermissionsToSubfoldersRecursive(f, newPermissions) || clearCache; } - + return clearCache; } + + /// + /// Returns a flag indicating whether the current user can add a folder or file. + /// + /// The page. + /// A flag indicating whether the user has permission. + bool IFolderPermissionController.CanAddFolder(IFolderInfo folder) + { + return provider.CanAddFolder((FolderInfo)folder); + } + + /// + /// Returns a flag indicating whether the current user can addmister a folder. + /// + /// The page. + /// A flag indicating whether the user has permission. + bool IFolderPermissionController.CanAdminFolder(IFolderInfo folder) + { + return provider.CanAdminFolder((FolderInfo)folder); + } + + /// + /// Returns a flag indicating whether the current user can view a folder or file. + /// + /// The page. + /// A flag indicating whether the user has permission. + bool IFolderPermissionController.CanViewFolder(IFolderInfo folder) + { + return provider.CanViewFolder((FolderInfo)folder); + } } } diff --git a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs index bb5db6d1ba1..09159cc5382 100644 --- a/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/FolderPermissionInfo.cs @@ -12,15 +12,15 @@ namespace DotNetNuke.Security.Permissions [Serializable] public class FolderPermissionInfo : PermissionInfoBase, IHydratable - { - // local property declarations + { + // local property declarations private int _folderID; private string _folderPath; private int _folderPermissionID; - private int _portalID; - + private int _portalID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new FolderPermissionInfo. /// @@ -31,16 +31,16 @@ public FolderPermissionInfo() this._folderPath = Null.NullString; this._portalID = Null.NullInteger; this._folderID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new FolderPermissionInfo. /// /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public FolderPermissionInfo(PermissionInfo permission) + public FolderPermissionInfo(PermissionInfo permission) : this() { this.ModuleDefID = permission.ModuleDefID; @@ -48,8 +48,8 @@ public FolderPermissionInfo(PermissionInfo permission) this.PermissionID = permission.PermissionID; this.PermissionKey = permission.PermissionKey; this.PermissionName = permission.PermissionName; - } - + } + [XmlIgnore] public int FolderPermissionID { @@ -57,7 +57,7 @@ public int FolderPermissionID { return this._folderPermissionID; } - + set { this._folderPermissionID = value; @@ -71,7 +71,7 @@ public int FolderID { return this._folderID; } - + set { this._folderID = value; @@ -85,7 +85,7 @@ public int PortalID { return this._portalID; } - + set { this._portalID = value; @@ -99,12 +99,12 @@ public string FolderPath { return this._folderPath; } - + set { this._folderPath = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -119,13 +119,13 @@ public int KeyID { return this.FolderPermissionID; } - + set { this.FolderPermissionID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a FolderPermissionInfo from a Data Reader. diff --git a/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs b/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs index f2ba0abadc8..7871bc9ff1e 100644 --- a/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/IFolderPermissionController.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.Security.Permissions public interface IFolderPermissionController { bool CanAddFolder(IFolderInfo folder); - + bool CanAdminFolder(IFolderInfo folder); - + bool CanViewFolder(IFolderInfo folder); } } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs index 6d9f01a3bac..3063872b7e2 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionCollection.cs @@ -66,7 +66,7 @@ public ModulePermissionInfo this[int index] { return (ModulePermissionInfo)this.List[index]; } - + set { this.List[index] = value; @@ -96,7 +96,7 @@ public int Add(ModulePermissionInfo value, bool checkForDuplicates) break; } } - + if (!isMatch) { id = this.Add(value); @@ -128,7 +128,7 @@ public bool CompareTo(ModulePermissionCollection objModulePermissionCollection) { return false; } - + this.InnerList.Sort(new CompareModulePermissions()); objModulePermissionCollection.InnerList.Sort(new CompareModulePermissions()); for (int i = 0; i <= this.Count - 1; i++) @@ -138,7 +138,7 @@ public bool CompareTo(ModulePermissionCollection objModulePermissionCollection) return false; } } - + return true; } @@ -172,7 +172,7 @@ public void Remove(int permissionID, int roleID, int userID) this.List.RemoveAt(idx); break; } - + idx++; } } @@ -184,7 +184,7 @@ public List ToList() { list.Add(permission); } - + return list; } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs index 1f283bdc93e..be0d8aa16ca 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionController.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.Security.Permissions /// /// ----------------------------------------------------------------------------- public class ModulePermissionController - { - private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - + { + private static readonly PermissionProvider _provider = PermissionProvider.Instance(); + /// /// Returns a list with all roles with implicit permissions on Modules. /// @@ -47,12 +47,6 @@ 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. @@ -131,7 +125,7 @@ public static void DeleteModulePermissionsByUser(UserInfo user) /// GetModulePermissions gets a ModulePermissionCollection. /// /// The ID of the module. - /// The ID of the tab. + /// The ID of the tab. /// /// ----------------------------------------------------------------------------- public static ModulePermissionCollection GetModulePermissions(int moduleId, int tabId) @@ -146,7 +140,7 @@ public static ModulePermissionCollection GetModulePermissions(int moduleId, int /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. /// The Permissions for the Module. - /// The Permission to check. + /// The Permission to check. /// /// ----------------------------------------------------------------------------- public static bool HasModulePermission(ModulePermissionCollection modulePermissions, string permissionKey) @@ -183,6 +177,12 @@ public static void SaveModulePermissions(ModuleInfo module) { _provider.SaveModulePermissions(module); DataCache.ClearModulePermissionsCache(module.TabID); - } + } + + private static void ClearPermissionCache(int moduleId) + { + ModuleInfo objModule = ModuleController.Instance.GetModule(moduleId, Null.NullInteger, false); + DataCache.ClearModulePermissionsCache(objModule.TabID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs index c4a650b033c..1ad2c89ff86 100644 --- a/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/ModulePermissionInfo.cs @@ -21,14 +21,14 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- [Serializable] public class ModulePermissionInfo : PermissionInfoBase, IHydratable - { + { private int _moduleID; // local property declarations - private int _modulePermissionID; - + private int _modulePermissionID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new ModulePermissionInfo. /// @@ -37,16 +37,16 @@ public ModulePermissionInfo() { this._modulePermissionID = Null.NullInteger; this._moduleID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new ModulePermissionInfo. /// /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public ModulePermissionInfo(PermissionInfo permission) + public ModulePermissionInfo(PermissionInfo permission) : this() { this.ModuleDefID = permission.ModuleDefID; @@ -54,8 +54,8 @@ public ModulePermissionInfo(PermissionInfo permission) this.PermissionID = permission.PermissionID; this.PermissionKey = permission.PermissionKey; this.PermissionName = permission.PermissionName; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Module Permission ID. @@ -69,7 +69,7 @@ public int ModulePermissionID { return this._modulePermissionID; } - + set { this._modulePermissionID = value; @@ -89,12 +89,12 @@ public int ModuleID { return this._moduleID; } - + set { this._moduleID = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -109,13 +109,13 @@ public int KeyID { return this.ModulePermissionID; } - + set { this.ModulePermissionID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a ModulePermissionInfo from a Data Reader. @@ -128,7 +128,7 @@ public void Fill(IDataReader dr) this.ModulePermissionID = Null.SetNullInteger(dr["ModulePermissionID"]); this.ModuleID = Null.SetNullInteger(dr["ModuleID"]); } - + /// ----------------------------------------------------------------------------- /// /// Compares if two ModulePermissionInfo objects are equivalent/equal. @@ -149,12 +149,12 @@ public bool Equals(ModulePermissionInfo other) { return false; } - + if (ReferenceEquals(this, other)) { return true; } - + return (this.AllowAccess == other.AllowAccess) && (this.ModuleID == other.ModuleID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } @@ -178,17 +178,17 @@ public override bool Equals(object obj) { return false; } - + if (ReferenceEquals(this, obj)) { return true; } - + if (obj.GetType() != typeof(ModulePermissionInfo)) { return false; } - + return this.Equals((ModulePermissionInfo)obj); } @@ -198,6 +198,6 @@ public override int GetHashCode() { return (this._moduleID * 397) ^ this._modulePermissionID; } - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionController.cs b/DNN Platform/Library/Security/Permissions/PermissionController.cs index e021dee2301..fcb67abc669 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionController.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Security.Permissions public class PermissionController { private static readonly DataProvider provider = DataProvider.Instance(); - + public static string BuildPermissions(IList Permissions, string PermissionKey) { var permissionsBuilder = new StringBuilder(); @@ -64,7 +64,7 @@ public static string BuildPermissions(IList Permissions, string PermissionKey) { permissionsString.Insert(0, ";"); } - + return permissionsString; } @@ -72,11 +72,21 @@ public static ArrayList GetPermissionsByFolder() { return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_FOLDER").ToArray()); } - + + public static ArrayList GetPermissionsByPortalDesktopModule() + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_DESKTOPMODULE").ToArray()); + } + + public static ArrayList GetPermissionsByTab() + { + return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_TAB").ToArray()); + } + public int AddPermission(PermissionInfo permission) { EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_CREATED); - var permissionId = Convert.ToInt32(provider.AddPermission( + var permissionId = Convert.ToInt32(provider.AddPermission( permission.PermissionCode, permission.ModuleDefID, permission.PermissionKey, @@ -89,7 +99,7 @@ public int AddPermission(PermissionInfo permission) public void DeletePermission(int permissionID) { - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "PermissionID", permissionID.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -99,21 +109,6 @@ 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); @@ -140,7 +135,7 @@ public ArrayList GetPermissionsByModule(int moduleId, int tabId) public void UpdatePermission(PermissionInfo permission) { EventLogController.Instance.AddLog(permission, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.PERMISSION_UPDATED); - provider.UpdatePermission( + provider.UpdatePermission( permission.PermissionID, permission.PermissionCode, permission.ModuleDefID, @@ -148,20 +143,10 @@ public void UpdatePermission(PermissionInfo permission) permission.PermissionName, UserController.Instance.GetCurrentUserInfo().UserID); this.ClearCache(); - } - - public static ArrayList GetPermissionsByPortalDesktopModule() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_DESKTOPMODULE").ToArray()); - } - - public static ArrayList GetPermissionsByTab() - { - return new ArrayList(GetPermissions().Where(p => p.PermissionCode == "SYSTEM_TAB").ToArray()); } - public T RemapPermission(T permission, int portalId) - where T : PermissionInfoBase + public T RemapPermission(T permission, int portalId) + where T : PermissionInfoBase { PermissionInfo permissionInfo = this.GetPermissionByCodeAndKey(permission.PermissionCode, permission.PermissionKey).ToArray().Cast().FirstOrDefault(); T result = null; @@ -195,7 +180,7 @@ public T RemapPermission(T permission, int portalId) { RoleID = _role.RoleID; } - + break; } } @@ -208,19 +193,19 @@ public T RemapPermission(T permission, int portalId) { permission.RoleID = RoleID; } - + if (UserID != int.MinValue) { permission.UserID = UserID; } - + result = permission; } } return result; - } - + } + [Obsolete("Deprecated in DNN 7.3.0. Replaced by GetPermissionsByModule(int, int). Scheduled removal in v10.0.0.")] public ArrayList GetPermissionsByModuleID(int moduleId) { @@ -228,5 +213,20 @@ public ArrayList GetPermissionsByModuleID(int moduleId) return this.GetPermissionsByModuleDefID(module.ModuleDefID); } + + 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); + } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionInfo.cs b/DNN Platform/Library/Security/Permissions/PermissionInfo.cs index bde9b299f71..c067d7e0866 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionInfo.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- [Serializable] public class PermissionInfo : BaseEntityInfo - { + { /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Mdoule Definition ID. @@ -65,8 +65,8 @@ public class PermissionInfo : BaseEntityInfo /// A String. /// ----------------------------------------------------------------------------- [XmlIgnore] - public string PermissionName { get; set; } - + public string PermissionName { get; set; } + /// ----------------------------------------------------------------------------- /// /// FillInternal fills a PermissionInfo from a Data Reader. @@ -81,6 +81,6 @@ protected override void FillInternal(IDataReader dr) this.PermissionCode = Null.SetNullString(dr["PermissionCode"]); this.PermissionKey = Null.SetNullString(dr["PermissionKey"]); this.PermissionName = Null.SetNullString(dr["PermissionName"]); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs index d974abe24d8..1921e4a5d77 100644 --- a/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs +++ b/DNN Platform/Library/Security/Permissions/PermissionInfoBase.cs @@ -31,14 +31,14 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- [Serializable] public abstract class PermissionInfoBase : PermissionInfo - { + { private bool _AllowAccess; private string _DisplayName; private int _RoleID; private string _RoleName; private int _UserID; - private string _Username; - + private string _Username; + public PermissionInfoBase() { this._RoleID = int.Parse(Globals.glbRoleNothing); @@ -47,8 +47,8 @@ public PermissionInfoBase() this._UserID = Null.NullInteger; this._Username = Null.NullString; this._DisplayName = Null.NullString; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and sets aflag that indicates whether the user or role has permission. @@ -62,7 +62,7 @@ public bool AllowAccess { return this._AllowAccess; } - + set { this._AllowAccess = value; @@ -82,7 +82,7 @@ public string DisplayName { return this._DisplayName; } - + set { this._DisplayName = value; @@ -102,7 +102,7 @@ public int RoleID { return this._RoleID; } - + set { this._RoleID = value; @@ -122,7 +122,7 @@ public string RoleName { return this._RoleName; } - + set { this._RoleName = value; @@ -142,7 +142,7 @@ public int UserID { return this._UserID; } - + set { this._UserID = value; @@ -162,13 +162,13 @@ public string Username { return this._Username; } - + set { this._Username = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// FillInternal fills the PermissionInfoBase from a Data Reader. @@ -193,8 +193,8 @@ protected override void FillInternal(IDataReader dr) this.RoleID = int.Parse(Globals.glbRoleNothing); this.RoleName = string.Empty; } - + this.AllowAccess = Null.SetNullBoolean(dr["AllowAccess"]); - } + } } } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs index d4c0895b073..11f0306d5e0 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionCollection.cs @@ -56,7 +56,7 @@ public TabPermissionInfo this[int index] { return (TabPermissionInfo)this.List[index]; } - + set { this.List[index] = value; @@ -87,7 +87,7 @@ public int Add(TabPermissionInfo value, bool checkForDuplicates) break; } } - + if (!isMatch) { id = this.Add(value); @@ -127,7 +127,7 @@ public bool CompareTo(TabPermissionCollection objTabPermissionCollection) { return false; } - + this.InnerList.Sort(new CompareTabPermissions()); objTabPermissionCollection.InnerList.Sort(new CompareTabPermissions()); for (int i = 0; i <= this.Count - 1; i++) @@ -141,7 +141,7 @@ public bool CompareTo(TabPermissionCollection objTabPermissionCollection) return false; } } - + return true; } @@ -184,7 +184,7 @@ public List ToList() { list.Add(permission); } - + return list; } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs index 161178e85f9..192c076935c 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionController.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionController.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.Security.Permissions /// /// ----------------------------------------------------------------------------- public class TabPermissionController - { - private static readonly PermissionProvider _provider = PermissionProvider.Instance(); - + { + private static readonly PermissionProvider _provider = PermissionProvider.Instance(); + /// /// Returns a list with all roles with implicit permissions on Tabs. /// @@ -46,12 +46,6 @@ 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. @@ -252,7 +246,7 @@ public static void DeleteTabPermissionsByUser(UserInfo user) /// GetTabPermissions gets a TabPermissionCollection. /// /// The ID of the tab. - /// The ID of the portal. + /// The ID of the portal. /// /// ----------------------------------------------------------------------------- public static TabPermissionCollection GetTabPermissions(int tabId, int portalId) @@ -266,7 +260,7 @@ public static TabPermissionCollection GetTabPermissions(int tabId, int portalId) /// /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. - /// The Permission to check. + /// The Permission to check. /// /// ----------------------------------------------------------------------------- public static bool HasTabPermission(string permissionKey) @@ -281,7 +275,7 @@ public static bool HasTabPermission(string permissionKey) /// If you pass in a comma delimited list of permissions (eg "ADD,DELETE", this will return /// true if the user has any one of the permissions. /// The Permissions for the Tab. - /// The Permission(s) to check. + /// The Permission(s) to check. /// /// ----------------------------------------------------------------------------- public static bool HasTabPermission(TabPermissionCollection tabPermissions, string permissionKey) @@ -300,6 +294,12 @@ public static void SaveTabPermissions(TabInfo tab) _provider.SaveTabPermissions(tab); EventLogController.Instance.AddLog(tab, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.TABPERMISSION_UPDATED); DataCache.ClearTabPermissionsCache(tab.PortalID); - } + } + + private static void ClearPermissionCache(int tabId) + { + var objTab = TabController.Instance.GetTab(tabId, Null.NullInteger, false); + DataCache.ClearTabPermissionsCache(objTab.PortalID); + } } } diff --git a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs index 2b09229797d..14cb7854352 100644 --- a/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs +++ b/DNN Platform/Library/Security/Permissions/TabPermissionInfo.cs @@ -22,14 +22,14 @@ namespace DotNetNuke.Security.Permissions [Serializable] [XmlRoot("permission")] public class TabPermissionInfo : PermissionInfoBase, IHydratable - { + { private int _TabID; - + // local property declarations - private int _TabPermissionID; - + private int _TabPermissionID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new TabPermissionInfo. /// @@ -38,16 +38,16 @@ public TabPermissionInfo() { this._TabPermissionID = Null.NullInteger; this._TabID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new TabPermissionInfo. /// /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public TabPermissionInfo(PermissionInfo permission) + public TabPermissionInfo(PermissionInfo permission) : this() { this.ModuleDefID = permission.ModuleDefID; @@ -55,8 +55,8 @@ public TabPermissionInfo(PermissionInfo permission) this.PermissionID = permission.PermissionID; this.PermissionKey = permission.PermissionKey; this.PermissionName = permission.PermissionName; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Tab Permission ID. @@ -70,7 +70,7 @@ public int TabPermissionID { return this._TabPermissionID; } - + set { this._TabPermissionID = value; @@ -90,12 +90,12 @@ public int TabID { return this._TabID; } - + set { this._TabID = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -110,13 +110,13 @@ public int KeyID { return this.TabPermissionID; } - + set { this.TabPermissionID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a TabPermissionInfo from a Data Reader. diff --git a/DNN Platform/Library/Security/PortalSecurity.cs b/DNN Platform/Library/Security/PortalSecurity.cs index ae44808f205..101cf501b4e 100644 --- a/DNN Platform/Library/Security/PortalSecurity.cs +++ b/DNN Platform/Library/Security/PortalSecurity.cs @@ -25,8 +25,6 @@ namespace DotNetNuke.Security public class PortalSecurity { - public static readonly PortalSecurity Instance = new PortalSecurity(); - private const string RoleFriendPrefix = "FRIEND:"; private const string RoleFollowerPrefix = "FOLLOWER:"; private const string RoleOwnerPrefix = "OWNER:"; @@ -34,11 +32,13 @@ public class PortalSecurity 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; + public static readonly PortalSecurity Instance = new PortalSecurity(); private static readonly DateTime OldExpiryTime = new DateTime(1999, 1, 1); private static readonly Regex StripTagsRegex = new Regex("<[^<>]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); private static readonly Regex BadStatementRegex = new Regex(BadStatementExpression, RegexOptions.IgnoreCase | RegexOptions.Compiled); + private static readonly Regex[] RxListStrings = new[] { new Regex("]*>.*?<]*>", RxOptions), @@ -85,8 +85,8 @@ public class PortalSecurity }; private static readonly Regex DangerElementsRegex = new Regex(@"(<[^>]*?) on.*?\=(['""]*)[\s\S]*?(\2)( *)([^>]*?>)", RxOptions); - private static readonly Regex DangerElementContentRegex = new Regex(@"on.*?\=(['""]*)[\s\S]*?(\1)( *)", RxOptions); - + private static readonly Regex DangerElementContentRegex = new Regex(@"on.*?\=(['""]*)[\s\S]*?(\1)( *)", RxOptions); + /// ----------------------------------------------------------------------------- /// /// The FilterFlag enum determines which filters are applied by the InputFilter @@ -124,27 +124,27 @@ public enum FilterScope SystemList, PortalList, SystemAndPortalList, - } - + } + private enum RoleType { Security, Friend, Follower, 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) { @@ -154,7 +154,7 @@ public static void ForceSecureConnection() { url = url + "&ssl=1"; } - + // redirect to secure connection HttpContext.Current.Response.Redirect(url, true); } @@ -186,10 +186,118 @@ public static string GetCookieDomain(int portalId) // set cookie domain to be consistent with domain specification in web.config cookieDomain = FormsAuthentication.CookieDomain; } - + return cookieDomain; } - + + public static bool IsDenied(string roles) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + return IsDenied(objUserInfo, settings, roles); + } + + public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, string roles) + { + // super user always has full access + if (objUserInfo.IsSuperUser) + { + return false; + } + + bool isDenied = 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("!")) + { + // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) + if (settings != null && !(settings.PortalId == objUserInfo.PortalID && objUserInfo.IsInRole(settings.AdministratorRoleName))) + { + string denyRole = role.Replace("!", string.Empty); + if (denyRole == Globals.glbRoleAllUsersName || objUserInfo.IsInRole(denyRole)) + { + isDenied = true; + break; + } + } + } + } + } + } + + return isDenied; + } + + public static bool IsInRole(string role) + { + if (!string.IsNullOrEmpty(role) && role == Globals.glbRoleUnauthUserName && !HttpContext.Current.Request.IsAuthenticated) + { + return true; + } + + return IsInRoles(UserController.Instance.GetCurrentUserInfo(), PortalController.Instance.GetCurrentPortalSettings(), role); + } + + public static bool IsInRoles(string roles) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + return IsInRoles(objUserInfo, settings, roles); + } + + public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, string roles) + { + // super user always has full access + bool isInRoles = objUserInfo.IsSuperUser; + + if (!isInRoles) + { + if (roles != null) + { + foreach (string role in roles.Split(new[] { ';' })) + { + bool? roleAllowed; + ProcessRole(objUserInfo, settings, role, out roleAllowed); + if (roleAllowed.HasValue) + { + isInRoles = roleAllowed.Value; + break; + } + } + } + } + + return isInRoles; + } + + public static bool IsFriend(int userId) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + return IsInRoles(objUserInfo, settings, RoleFriendPrefix + userId); + } + + public static bool IsFollower(int userId) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + return IsInRoles(objUserInfo, settings, RoleFollowerPrefix + userId); + } + + public static bool IsOwner(int userId) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); + return IsInRoles(objUserInfo, settings, RoleOwnerPrefix + userId); + } + /// ----------------------------------------------------------------------------- /// /// This function creates a random key. @@ -213,331 +321,72 @@ 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); - switch (roleType) - { - case RoleType.Friend: - ProcessFriendRole(user, roleName, out roleAllowed); - break; - case RoleType.Follower: - ProcessFollowerRole(user, roleName, out roleAllowed); - break; - case RoleType.Owner: - ProcessOwnerRole(user, roleName, out roleAllowed); - break; - default: - ProcessSecurityRole(user, settings, roleName, out roleAllowed); - break; - } - } - private static void ProcessFriendRole(UserInfo user, string roleName, out bool? roleAllowed) + public string DecryptString(string message, string passphrase) { - roleAllowed = null; - var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName)); - var relationShip = RelationshipController.Instance.GetFriendRelationship(user, targetUser); - if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted) - { - roleAllowed = true; - } + return CryptographyProvider.Instance().DecryptString(message, passphrase); } - private static void ProcessFollowerRole(UserInfo user, string roleName, out bool? roleAllowed) + public string Encrypt(string key, string data) { - roleAllowed = null; - var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName)); - var relationShip = RelationshipController.Instance.GetFollowerRelationship(user, targetUser); - if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted) - { - roleAllowed = true; - } + return CryptographyProvider.Instance().EncryptParameter(data, key); } - private static void ProcessOwnerRole(UserInfo user, string roleName, out bool? roleAllowed) + public string EncryptString(string message, string passphrase) { - roleAllowed = null; - var entityId = GetEntityFromRoleName(roleName); - if (entityId == user.UserID) - { - roleAllowed = true; - } + return CryptographyProvider.Instance().EncryptString(message, passphrase); } - private static int GetEntityFromRoleName(string roleName) + /// ----------------------------------------------------------------------------- + /// + /// This function applies security filtering to the UserInput string. + /// + /// This is the string to be filtered. + /// Flags which designate the filters to be applied. + /// Filtered UserInput. + /// ----------------------------------------------------------------------------- + public string InputFilter(string userInput, FilterFlag filterType) { - var roleParts = roleName.Split(':'); - int result; - if (roleParts.Length > 1 && int.TryParse(roleParts[1], out result)) + if (userInput == null) { - return result; + return string.Empty; } - - return Null.NullInteger; - } - private static void ProcessSecurityRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) - { - roleAllowed = null; - - // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance - if (!string.IsNullOrEmpty(roleName)) + var tempInput = userInput; + if ((filterType & FilterFlag.NoAngleBrackets) == FilterFlag.NoAngleBrackets) { - // Deny permission - if (roleName.StartsWith("!")) - { - // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) - if (settings != null && !(settings.PortalId == user.PortalID && user.IsInRole(settings.AdministratorRoleName))) - { - string denyRole = roleName.Replace("!", string.Empty); - if (denyRole == Globals.glbRoleAllUsersName || user.IsInRole(denyRole)) - { - roleAllowed = false; - } - } - } - else // Grant permission + var removeAngleBrackets = Config.GetSetting("RemoveAngleBrackets") != null && bool.Parse(Config.GetSetting("RemoveAngleBrackets")); + if (removeAngleBrackets) { - if (roleName == Globals.glbRoleAllUsersName || user.IsInRole(roleName)) - { - roleAllowed = true; - } + tempInput = FormatAngleBrackets(tempInput); } } - } - private static RoleType GetRoleType(string roleName) - { - if (roleName.StartsWith(RoleFriendPrefix, StringComparison.InvariantCultureIgnoreCase)) + if ((filterType & FilterFlag.NoSQL) == FilterFlag.NoSQL) { - return RoleType.Friend; + tempInput = FormatRemoveSQL(tempInput); } - - if (roleName.StartsWith(RoleFollowerPrefix, StringComparison.InvariantCultureIgnoreCase)) + + if ((filterType & FilterFlag.NoMarkup) == FilterFlag.NoMarkup && IncludesMarkup(tempInput)) { - return RoleType.Follower; + tempInput = HttpUtility.HtmlEncode(tempInput); } - - if (roleName.StartsWith(RoleOwnerPrefix, StringComparison.InvariantCultureIgnoreCase)) + + if ((filterType & FilterFlag.NoScripting) == FilterFlag.NoScripting) { - return RoleType.Owner; + tempInput = this.FormatDisableScripting(tempInput); } - - return RoleType.Security; - } - private static string BytesToHexString(IEnumerable bytes) - { - var hexString = new StringBuilder(); - foreach (var b in bytes) + if ((filterType & FilterFlag.MultiLine) == FilterFlag.MultiLine) { - hexString.Append(string.Format("{0:X2}", b)); + tempInput = FormatMultiLine(tempInput); } - - return hexString.ToString(); - } - - /// ----------------------------------------------------------------------------- - /// - /// 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. - /// - /// This is a private function that is used internally by the FormatDisableScripting function. - /// - /// ----------------------------------------------------------------------------- - private static string FilterStrings(string strInput) - { - // setup up list of search terms as items may be used twice - var tempInput = strInput; - if (string.IsNullOrEmpty(tempInput)) - { - return tempInput; - } - - const string replacement = " "; - - // remove the js event from html tags - var tagMatches = DangerElementsRegex.Matches(tempInput); - foreach (Match match in tagMatches) - { - var tagContent = match.Value; - var cleanTagContent = DangerElementContentRegex.Replace(tagContent, string.Empty); - tempInput = tempInput.Replace(tagContent, cleanTagContent); - } - - // check if text contains encoded angle brackets, if it does it we decode it to check the plain text - if (tempInput.Contains(">") || tempInput.Contains("<")) - { - // text is encoded, so decode and try again - tempInput = HttpUtility.HtmlDecode(tempInput); - tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement)); - - // Re-encode - tempInput = HttpUtility.HtmlEncode(tempInput); - } - else - { - tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement)); - } - - return tempInput; - } - - /// ----------------------------------------------------------------------------- - /// - /// This filter removes angle brackets i.e. - /// - /// This is the string to be filtered. - /// Filtered UserInput. - /// - /// This is a private function that is used internally by the InputFilter function. - /// - /// ----------------------------------------------------------------------------- - private static string FormatAngleBrackets(string strInput) - { - var tempInput = new StringBuilder(strInput).Replace("<", string.Empty).Replace(">", string.Empty); - return tempInput.ToString(); - } - - /// ----------------------------------------------------------------------------- - /// - /// This filter removes CrLf characters and inserts br. - /// - /// This is the string to be filtered. - /// Filtered UserInput. - /// - /// This is a private function that is used internally by the InputFilter function. - /// - /// ----------------------------------------------------------------------------- - private static string FormatMultiLine(string strInput) - { - const string lbreak = "
    "; - var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); - return tempInput.ToString(); - } - - /// ----------------------------------------------------------------------------- - /// - /// 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. - /// - /// This is a private function that is used internally by the InputFilter function. - /// - /// ----------------------------------------------------------------------------- - private string FormatDisableScripting(string strInput) - { - return string.IsNullOrWhiteSpace(strInput) - ? strInput - : FilterStrings(strInput); - } - - /// ----------------------------------------------------------------------------- - /// - /// This function verifies raw SQL statements to prevent SQL injection attacks - /// and replaces a similar function (PreventSQLInjection) from the Common.Globals.vb module. - /// - /// This is the string to be filtered. - /// Filtered UserInput. - /// - /// This is a private function that is used internally by the InputFilter function. - /// - /// ----------------------------------------------------------------------------- - private static string FormatRemoveSQL(string strSQL) - { - // Check for forbidden T-SQL commands. Use word boundaries to filter only real statements. - return BadStatementRegex.Replace(strSQL, " ").Replace("'", "''"); - } - - /// ----------------------------------------------------------------------------- - /// - /// This function determines if the Input string contains any markup. - /// - /// This is the string to be checked. - /// True if string contains Markup tag(s). - /// - /// This is a private function that is used internally by the InputFilter function. - /// - /// ----------------------------------------------------------------------------- - private static bool IncludesMarkup(string strInput) - { - return StripTagsRegex.IsMatch(strInput); - } - - public string DecryptString(string message, string passphrase) - { - return CryptographyProvider.Instance().DecryptString(message, passphrase); - } - - public string Encrypt(string key, string data) - { - return CryptographyProvider.Instance().EncryptParameter(data, key); - } - - public string EncryptString(string message, string passphrase) - { - return CryptographyProvider.Instance().EncryptString(message, passphrase); - } - /// ----------------------------------------------------------------------------- - /// - /// This function applies security filtering to the UserInput string. - /// - /// This is the string to be filtered. - /// Flags which designate the filters to be applied. - /// Filtered UserInput. - /// ----------------------------------------------------------------------------- - public string InputFilter(string userInput, FilterFlag filterType) - { - if (userInput == null) - { - return string.Empty; - } - - var tempInput = userInput; - if ((filterType & FilterFlag.NoAngleBrackets) == FilterFlag.NoAngleBrackets) - { - var removeAngleBrackets = Config.GetSetting("RemoveAngleBrackets") != null && bool.Parse(Config.GetSetting("RemoveAngleBrackets")); - if (removeAngleBrackets) - { - tempInput = FormatAngleBrackets(tempInput); - } - } - - if ((filterType & FilterFlag.NoSQL) == FilterFlag.NoSQL) - { - tempInput = FormatRemoveSQL(tempInput); - } - - if ((filterType & FilterFlag.NoMarkup) == FilterFlag.NoMarkup && IncludesMarkup(tempInput)) - { - tempInput = HttpUtility.HtmlEncode(tempInput); - } - - if ((filterType & FilterFlag.NoScripting) == FilterFlag.NoScripting) - { - tempInput = this.FormatDisableScripting(tempInput); - } - - if ((filterType & FilterFlag.MultiLine) == FilterFlag.MultiLine) - { - tempInput = FormatMultiLine(tempInput); - } - if ((filterType & FilterFlag.NoProfanity) == FilterFlag.NoProfanity) { tempInput = this.Replace(tempInput, ConfigType.ListController, "ProfanityFilter", FilterScope.SystemAndPortalList); } - + return tempInput; } @@ -592,7 +441,7 @@ public string Replace(string inputString, ConfigType configType, string configSo inputString = listEntryPortalInfos.Aggregate(inputString, (current, removeItem) => Regex.Replace(current, @"\b" + Regex.Escape(removeItem.Text) + @"\b", removeItem.Value, options)); break; } - + break; case ConfigType.ExternalFile: throw new NotImplementedException(); @@ -688,11 +537,11 @@ public void SignIn(UserInfo user, bool createPersistentCookie) Secure = FormsAuthentication.RequireSSL, }; - if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) - { - HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - } - + if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) + { + HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + } + HttpContext.Current.Response.Cookies.Set(authCookie); AuthCookieController.Instance.Update(authCookie.Value, authCookie.Expires.ToUniversalTime(), user.UserID); @@ -712,11 +561,11 @@ public void SignIn(UserInfo user, bool createPersistentCookie) } else { - if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) - { - HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); - } - + if (HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName] != null) + { + HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName); + } + FormsAuthentication.SetAuthCookie(user.Username, false); var authCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (!string.IsNullOrEmpty(authCookie?.Value)) @@ -880,124 +729,275 @@ public void CheckAllPortalFileExtensionWhitelists(string newMasterList) } } } - } + } - private static void InvalidateAspNetSession(HttpContext context) + private static void ProcessRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) { - if (context.Session != null && !context.Session.IsNewSession) + var roleType = GetRoleType(roleName); + switch (roleType) { - // invalidate existing session so a new one is created - context.Session.Clear(); - context.Session.Abandon(); + case RoleType.Friend: + ProcessFriendRole(user, roleName, out roleAllowed); + break; + case RoleType.Follower: + ProcessFollowerRole(user, roleName, out roleAllowed); + break; + case RoleType.Owner: + ProcessOwnerRole(user, roleName, out roleAllowed); + break; + default: + ProcessSecurityRole(user, settings, roleName, out roleAllowed); + break; } } - public static bool IsDenied(string roles) + private static void ProcessFriendRole(UserInfo user, string roleName, out bool? roleAllowed) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - return IsDenied(objUserInfo, settings, roles); + roleAllowed = null; + var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName)); + var relationShip = RelationshipController.Instance.GetFriendRelationship(user, targetUser); + if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted) + { + roleAllowed = true; + } } - public static bool IsDenied(UserInfo objUserInfo, PortalSettings settings, string roles) + private static void ProcessFollowerRole(UserInfo user, string roleName, out bool? roleAllowed) { - // super user always has full access - if (objUserInfo.IsSuperUser) + roleAllowed = null; + var targetUser = UserController.Instance.GetUserById(user.PortalID, GetEntityFromRoleName(roleName)); + var relationShip = RelationshipController.Instance.GetFollowerRelationship(user, targetUser); + if (relationShip != null && relationShip.Status == RelationshipStatus.Accepted) { - return false; + roleAllowed = true; } + } - bool isDenied = false; + private static void ProcessOwnerRole(UserInfo user, string roleName, out bool? roleAllowed) + { + roleAllowed = null; + var entityId = GetEntityFromRoleName(roleName); + if (entityId == user.UserID) + { + roleAllowed = true; + } + } - if (roles != null) + private static int GetEntityFromRoleName(string roleName) + { + var roleParts = roleName.Split(':'); + int result; + if (roleParts.Length > 1 && int.TryParse(roleParts[1], out result)) { - // 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[] { ';' })) + return result; + } + + return Null.NullInteger; + } + + private static void ProcessSecurityRole(UserInfo user, PortalSettings settings, string roleName, out bool? roleAllowed) + { + roleAllowed = null; + + // permissions strings are encoded with Deny permissions at the beginning and Grant permissions at the end for optimal performance + if (!string.IsNullOrEmpty(roleName)) + { + // Deny permission + if (roleName.StartsWith("!")) { - if (!string.IsNullOrEmpty(role)) + // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) + if (settings != null && !(settings.PortalId == user.PortalID && user.IsInRole(settings.AdministratorRoleName))) { - // Deny permission - if (role.StartsWith("!")) + string denyRole = roleName.Replace("!", string.Empty); + if (denyRole == Globals.glbRoleAllUsersName || user.IsInRole(denyRole)) { - // Portal Admin cannot be denied from his/her portal (so ignore deny permissions if user is portal admin) - if (settings != null && !(settings.PortalId == objUserInfo.PortalID && objUserInfo.IsInRole(settings.AdministratorRoleName))) - { - string denyRole = role.Replace("!", string.Empty); - if (denyRole == Globals.glbRoleAllUsersName || objUserInfo.IsInRole(denyRole)) - { - isDenied = true; - break; - } - } + roleAllowed = false; } } } + else // Grant permission + { + if (roleName == Globals.glbRoleAllUsersName || user.IsInRole(roleName)) + { + roleAllowed = true; + } + } } - - return isDenied; } - public static bool IsInRole(string role) + private static RoleType GetRoleType(string roleName) { - if (!string.IsNullOrEmpty(role) && role == Globals.glbRoleUnauthUserName && !HttpContext.Current.Request.IsAuthenticated) + if (roleName.StartsWith(RoleFriendPrefix, StringComparison.InvariantCultureIgnoreCase)) { - return true; + return RoleType.Friend; } - return IsInRoles(UserController.Instance.GetCurrentUserInfo(), PortalController.Instance.GetCurrentPortalSettings(), role); + if (roleName.StartsWith(RoleFollowerPrefix, StringComparison.InvariantCultureIgnoreCase)) + { + return RoleType.Follower; + } + + if (roleName.StartsWith(RoleOwnerPrefix, StringComparison.InvariantCultureIgnoreCase)) + { + return RoleType.Owner; + } + + return RoleType.Security; } - public static bool IsInRoles(string roles) + private static string BytesToHexString(IEnumerable bytes) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - return IsInRoles(objUserInfo, settings, roles); + var hexString = new StringBuilder(); + foreach (var b in bytes) + { + hexString.Append(string.Format("{0:X2}", b)); + } + + return hexString.ToString(); } - public static bool IsInRoles(UserInfo objUserInfo, PortalSettings settings, string roles) + /// ----------------------------------------------------------------------------- + /// + /// 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. + /// + /// This is a private function that is used internally by the FormatDisableScripting function. + /// + /// ----------------------------------------------------------------------------- + private static string FilterStrings(string strInput) { - // super user always has full access - bool isInRoles = objUserInfo.IsSuperUser; + // setup up list of search terms as items may be used twice + var tempInput = strInput; + if (string.IsNullOrEmpty(tempInput)) + { + return tempInput; + } - if (!isInRoles) + const string replacement = " "; + + // remove the js event from html tags + var tagMatches = DangerElementsRegex.Matches(tempInput); + foreach (Match match in tagMatches) { - if (roles != null) - { - foreach (string role in roles.Split(new[] { ';' })) - { - bool? roleAllowed; - ProcessRole(objUserInfo, settings, role, out roleAllowed); - if (roleAllowed.HasValue) - { - isInRoles = roleAllowed.Value; - break; - } - } - } + var tagContent = match.Value; + var cleanTagContent = DangerElementContentRegex.Replace(tagContent, string.Empty); + tempInput = tempInput.Replace(tagContent, cleanTagContent); } - - return isInRoles; + + // check if text contains encoded angle brackets, if it does it we decode it to check the plain text + if (tempInput.Contains(">") || tempInput.Contains("<")) + { + // text is encoded, so decode and try again + tempInput = HttpUtility.HtmlDecode(tempInput); + tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement)); + + // Re-encode + tempInput = HttpUtility.HtmlEncode(tempInput); + } + else + { + tempInput = RxListStrings.Aggregate(tempInput, (current, s) => s.Replace(current, replacement)); + } + + return tempInput; } - public static bool IsFriend(int userId) + /// ----------------------------------------------------------------------------- + /// + /// This filter removes angle brackets i.e. + /// + /// This is the string to be filtered. + /// Filtered UserInput. + /// + /// This is a private function that is used internally by the InputFilter function. + /// + /// ----------------------------------------------------------------------------- + private static string FormatAngleBrackets(string strInput) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - return IsInRoles(objUserInfo, settings, RoleFriendPrefix + userId); + var tempInput = new StringBuilder(strInput).Replace("<", string.Empty).Replace(">", string.Empty); + return tempInput.ToString(); } - public static bool IsFollower(int userId) + /// ----------------------------------------------------------------------------- + /// + /// This filter removes CrLf characters and inserts br. + /// + /// This is the string to be filtered. + /// Filtered UserInput. + /// + /// This is a private function that is used internally by the InputFilter function. + /// + /// ----------------------------------------------------------------------------- + private static string FormatMultiLine(string strInput) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - return IsInRoles(objUserInfo, settings, RoleFollowerPrefix + userId); + const string lbreak = "
    "; + var tempInput = new StringBuilder(strInput).Replace("\r\n", lbreak).Replace("\n", lbreak).Replace("\r", lbreak); + return tempInput.ToString(); } - public static bool IsOwner(int userId) + /// ----------------------------------------------------------------------------- + /// + /// This function verifies raw SQL statements to prevent SQL injection attacks + /// and replaces a similar function (PreventSQLInjection) from the Common.Globals.vb module. + /// + /// This is the string to be filtered. + /// Filtered UserInput. + /// + /// This is a private function that is used internally by the InputFilter function. + /// + /// ----------------------------------------------------------------------------- + private static string FormatRemoveSQL(string strSQL) { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - return IsInRoles(objUserInfo, settings, RoleOwnerPrefix + userId); - } + // Check for forbidden T-SQL commands. Use word boundaries to filter only real statements. + return BadStatementRegex.Replace(strSQL, " ").Replace("'", "''"); + } + + /// ----------------------------------------------------------------------------- + /// + /// This function determines if the Input string contains any markup. + /// + /// This is the string to be checked. + /// True if string contains Markup tag(s). + /// + /// This is a private function that is used internally by the InputFilter function. + /// + /// ----------------------------------------------------------------------------- + private static bool IncludesMarkup(string strInput) + { + return StripTagsRegex.IsMatch(strInput); + } + + 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 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. + /// + /// This is a private function that is used internally by the InputFilter function. + /// + /// ----------------------------------------------------------------------------- + private string FormatDisableScripting(string strInput) + { + return string.IsNullOrWhiteSpace(strInput) + ? strInput + : FilterStrings(strInput); + } } } diff --git a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs index b60d41b4d1c..ad008c3b523 100644 --- a/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/DNNProfileProvider.cs @@ -32,9 +32,9 @@ namespace DotNetNuke.Security.Profile /// /// ----------------------------------------------------------------------------- public class DNNProfileProvider : ProfileProvider - { - private readonly DataProvider _dataProvider = DataProvider.Instance(); - + { + private readonly DataProvider _dataProvider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the Provider Properties can be edited. @@ -84,7 +84,7 @@ public override void GetUserProfile(ref UserInfo user) { break; } - + int definitionId = Convert.ToInt32(dr["PropertyDefinitionId"]); profProperty = properties.GetById(definitionId); if (profProperty != null) @@ -96,7 +96,7 @@ public override void GetUserProfile(ref UserInfo user) { extendedVisibility = Convert.ToString(dr["ExtendedVisibility"]); } - + profProperty.ProfileVisibility = new ProfileVisibility(portalId, extendedVisibility) { VisibilityMode = (UserVisibilityMode)dr["Visibility"], @@ -123,7 +123,7 @@ public override void GetUserProfile(ref UserInfo user) { profProperty.PropertyValue = profProperty.DefaultValue; } - + user.Profile.ProfileProperties.Add(profProperty); } @@ -157,12 +157,12 @@ public override void UpdateUserProfile(UserInfo user) if (newTimeZone.IsDirty && !string.IsNullOrEmpty(newTimeZone.PropertyValue)) { var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(newTimeZone.PropertyValue); - if (timeZoneInfo != null) - { - oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); - } + if (timeZoneInfo != null) + { + oldTimeZone.PropertyValue = timeZoneInfo.BaseUtcOffset.TotalMinutes.ToString(CultureInfo.InvariantCulture); + } } - + // however if old is changed, we need to update new as well else if (oldTimeZone.IsDirty) { @@ -184,8 +184,8 @@ public override void UpdateUserProfile(UserInfo user) EventLogController.Instance.AddLog(user, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, "USERPROFILE_UPDATED"); } } - } - + } + private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollection properties) { ProfilePropertyDefinition newTimeZone = properties["PreferredTimeZone"]; @@ -201,7 +201,7 @@ private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollecti 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)) { @@ -212,8 +212,8 @@ private void UpdateTimeZoneInfo(UserInfo user, ProfilePropertyDefinitionCollecti } } } - } - + } + private string GetProfileCacheKey(UserInfo user) { return string.Format(DataCache.UserProfileCacheKey, user.PortalID, user.Username); diff --git a/DNN Platform/Library/Security/Profile/ProfileProvider.cs b/DNN Platform/Library/Security/Profile/ProfileProvider.cs index 313e101c20b..6cd3e9d122b 100644 --- a/DNN Platform/Library/Security/Profile/ProfileProvider.cs +++ b/DNN Platform/Library/Security/Profile/ProfileProvider.cs @@ -11,13 +11,13 @@ public abstract class ProfileProvider public abstract bool CanEditProviderProperties { get; } // return the provider - public static ProfileProvider Instance() - { - return ComponentFactory.GetComponent(); + public static ProfileProvider Instance() + { + return ComponentFactory.GetComponent(); } - public abstract void GetUserProfile(ref UserInfo user); - + public abstract void GetUserProfile(ref UserInfo user); + public abstract void UpdateUserProfile(UserInfo user); } } diff --git a/DNN Platform/Library/Security/RegistrationSettings.cs b/DNN Platform/Library/Security/RegistrationSettings.cs index 40a0e848878..da32cd983ac 100644 --- a/DNN Platform/Library/Security/RegistrationSettings.cs +++ b/DNN Platform/Library/Security/RegistrationSettings.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Security using DotNetNuke.Common.Utilities; public class RegistrationSettings - { + { public RegistrationSettings() { this.RandomPassword = false; @@ -34,8 +34,8 @@ public RegistrationSettings() this.DisplayNameFormat = string.Empty; this.EmailValidator = Globals.glbEmailRegEx; } - - public RegistrationSettings(Dictionary settings) + + public RegistrationSettings(Dictionary settings) : this() { this.RandomPassword = settings.GetValueOrDefault("Registration_RandomPassword", this.RandomPassword); @@ -58,44 +58,44 @@ public RegistrationSettings(Dictionary settings) this.EmailValidator = settings.GetValueOrDefault("Security_EmailValidation", this.EmailValidator); 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; } + + public string EmailValidator { get; set; } } } diff --git a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs index 80f2a252687..592916e3b8a 100644 --- a/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/DNNRoleProvider.cs @@ -33,8 +33,8 @@ namespace DotNetNuke.Security.Roles public class DNNRoleProvider : RoleProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DNNRoleProvider)); - private readonly DataProvider dataProvider = DataProvider.Instance(); - + private readonly DataProvider dataProvider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- /// /// CreateRole persists a Role to the Data Store. @@ -51,7 +51,7 @@ public override bool CreateRole(RoleInfo role) try { role.RoleID = - Convert.ToInt32(this.dataProvider.AddRole( + Convert.ToInt32(this.dataProvider.AddRole( role.PortalID, role.RoleGroupID, role.RoleName.Trim(), @@ -89,15 +89,6 @@ 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)); - } /// ----------------------------------------------------------------------------- /// @@ -109,7 +100,7 @@ private void AddDNNUserRole(UserRoleInfo userRole) /// ----------------------------------------------------------------------------- public override ArrayList GetRoles(int portalId) { - var arrRoles = CBO.FillCollection( + var arrRoles = CBO.FillCollection( portalId == Null.NullInteger ? this.dataProvider.GetRoles() : this.dataProvider.GetPortalRoles(portalId), typeof(RoleInfo)); @@ -124,16 +115,16 @@ public override IList GetRolesBasicSearch(int portalID, int pageSize, public override IDictionary GetRoleSettings(int roleId) { var settings = new Dictionary { }; - using (IDataReader dr = this.dataProvider.GetRoleSettings(roleId)) + using (IDataReader dr = this.dataProvider.GetRoleSettings(roleId)) { - while (dr.Read()) + while (dr.Read()) { settings.Add(dr["SettingName"].ToString(), dr["SettingValue"].ToString()); } - + dr.Close(); } - + return settings; } @@ -145,7 +136,7 @@ public override IDictionary GetRoleSettings(int roleId) /// ----------------------------------------------------------------------------- public override void UpdateRole(RoleInfo role) { - this.dataProvider.UpdateRole( + this.dataProvider.UpdateRole( role.RoleID, role.RoleGroupID, role.RoleName.Trim(), @@ -183,8 +174,8 @@ public override void UpdateRoleSettings(RoleInfo role) this.dataProvider.UpdateRoleSetting(role.RoleID, setting.Key, setting.Value, UserController.Instance.GetCurrentUserInfo().UserID); } } - } - + } + /// ----------------------------------------------------------------------------- /// /// AddUserToRole adds a User to a Role. @@ -211,7 +202,7 @@ public override bool AddUserToRole(int portalId, UserInfo user, UserRoleInfo use createStatus = false; } - + return createStatus; } @@ -299,12 +290,12 @@ public override void RemoveUserFromRole(int portalId, UserInfo user, UserRoleInf /// ----------------------------------------------------------------------------- public override void UpdateUserRole(UserRoleInfo userRole) { - this.dataProvider.UpdateUserRole( + this.dataProvider.UpdateUserRole( userRole.UserRoleID, (int)userRole.Status, userRole.IsOwner, userRole.EffectiveDate, userRole.ExpiryDate, UserController.Instance.GetCurrentUserInfo().UserID); - } + } /// ----------------------------------------------------------------------------- /// @@ -335,16 +326,6 @@ 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); - } /// ----------------------------------------------------------------------------- /// @@ -389,11 +370,30 @@ public override void UpdateRoleGroup(RoleGroupInfo roleGroup) this.dataProvider.UpdateRoleGroup(roleGroup.RoleGroupID, roleGroup.RoleGroupName.Trim(), (roleGroup.Description ?? string.Empty).Trim(), UserController.Instance.GetCurrentUserInfo().UserID); this.ClearRoleGroupCache(roleGroup.PortalID); - } + } + + 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)); + } + + private void ClearRoleGroupCache(int portalId) + { + DataCache.ClearCache(this.GetRoleGroupsCacheKey(portalId)); + } + + private string GetRoleGroupsCacheKey(int portalId) + { + return string.Format(DataCache.RoleGroupsCacheKey, portalId); + } private IEnumerable GetRoleGroupsInternal(int portalId) { - var cacheArgs = new CacheItemArgs( + var cacheArgs = new CacheItemArgs( this.GetRoleGroupsCacheKey(portalId), DataCache.RoleGroupsCacheTimeOut, DataCache.RoleGroupsCachePriority); diff --git a/DNN Platform/Library/Security/Roles/RoleComparer.cs b/DNN Platform/Library/Security/Roles/RoleComparer.cs index 39eb5f2692c..45e48996159 100644 --- a/DNN Platform/Library/Security/Roles/RoleComparer.cs +++ b/DNN Platform/Library/Security/Roles/RoleComparer.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Security.Roles /// /// ----------------------------------------------------------------------------- public class RoleComparer : IComparer - { + { /// ----------------------------------------------------------------------------- /// /// Compares two RoleInfo objects by performing a comparison of their rolenames. @@ -28,6 +28,6 @@ public class RoleComparer : IComparer public int Compare(object x, object y) { return new CaseInsensitiveComparer().Compare(((RoleInfo)x).RoleName, ((RoleInfo)y).RoleName); - } + } } } diff --git a/DNN Platform/Library/Security/Roles/RoleController.cs b/DNN Platform/Library/Security/Roles/RoleController.cs index 20a86ec9aff..f1b9f47867e 100644 --- a/DNN Platform/Library/Security/Roles/RoleController.cs +++ b/DNN Platform/Library/Security/Roles/RoleController.cs @@ -44,7 +44,7 @@ private enum UserRoleActions update = 1, delete = 2, } - + /// ----------------------------------------------------------------------------- /// /// Adds a Role Group. @@ -102,148 +102,189 @@ public static void AddUserRole(UserInfo user, RoleInfo role, PortalSettings port // Remove the UserInfo from the Cache, as it has been modified DataCache.ClearUserCache(portalSettings.PortalId, user.Username); } - - public int AddRole(RoleInfo role) + + /// ----------------------------------------------------------------------------- + /// + /// Determines if the specified user can be removed from a role. + /// + /// + /// Roles such as "Registered Users" and "Administrators" can only + /// be removed in certain circumstances. + /// + /// A PortalSettings structure representing the current portal settings. + /// The Id of the User that should be checked for role removability. + /// The Id of the Role that should be checked for removability. + /// + /// ----------------------------------------------------------------------------- + public static bool CanRemoveUserFromRole(PortalSettings PortalSettings, int UserId, int RoleId) { - return Instance.AddRole(role, true); + // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb + // HACK: Duplicated in CanRemoveUserFromRole(PortalInfo, Integer, Integer) method below + // changes to this method should be reflected in the other method as well + return !((PortalSettings.AdministratorId == UserId && PortalSettings.AdministratorRoleId == RoleId) || PortalSettings.RegisteredRoleId == RoleId); } - int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) + /// ----------------------------------------------------------------------------- + /// + /// Determines if the specified user can be removed from a role. + /// + /// + /// Roles such as "Registered Users" and "Administrators" can only + /// be removed in certain circumstances. + /// + /// A PortalInfo structure representing the current portal. + /// The Id of the User. + /// The Id of the Role that should be checked for removability. + /// + /// ----------------------------------------------------------------------------- + public static bool CanRemoveUserFromRole(PortalInfo PortalInfo, int UserId, int RoleId) { - Requires.NotNull("role", role); + // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb + // HACK: Duplicated in CanRemoveUserFromRole(PortalSettings, Integer, Integer) method above + // changes to this method should be reflected in the other method as well + return !((PortalInfo.AdministratorId == UserId && PortalInfo.AdministratorRoleId == RoleId) || PortalInfo.RegisteredRoleId == RoleId); + } - var roleId = -1; - if (provider.CreateRole(role)) + /// ----------------------------------------------------------------------------- + /// + /// Deletes a Role Group. + /// + /// ----------------------------------------------------------------------------- + public static void DeleteRoleGroup(int PortalID, int RoleGroupId) + { + DeleteRoleGroup(GetRoleGroup(PortalID, RoleGroupId)); + } + + /// ----------------------------------------------------------------------------- + /// + /// Deletes a Role Group. + /// + /// The RoleGroup to Delete. + /// ----------------------------------------------------------------------------- + public static void DeleteRoleGroup(RoleGroupInfo objRoleGroupInfo) + { + provider.DeleteRoleGroup(objRoleGroupInfo); + EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_DELETED); + } + + /// + /// Removes a User from a Role. + /// + /// The user to remove. + /// The role to remove the use from. + /// The PortalSettings of the Portal. + /// A flag that indicates whether the user should be notified. + /// + public static bool DeleteUserRole(UserInfo objUser, RoleInfo role, PortalSettings portalSettings, bool notifyUser) + { + bool canDelete = DeleteUserRoleInternal(portalSettings.PortalId, objUser.UserID, role.RoleID); + if (canDelete) { - this.AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); - if (addToExistUsers) + if (notifyUser) { - this.AutoAssignUsers(role); + SendNotification(objUser, role, portalSettings, UserRoleActions.delete); } - - roleId = role.RoleID; - - this.ClearRoleCache(role.PortalID); - - EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } - return roleId; + return canDelete; } - protected override Func GetFactory() + /// ----------------------------------------------------------------------------- + /// + /// Fetch a single RoleGroup. + /// + /// The Id of the Portal. + /// Role Group ID. + /// + /// + /// ----------------------------------------------------------------------------- + public static RoleGroupInfo GetRoleGroup(int portalId, int roleGroupId) { - return () => new RoleController(); - } + return provider.GetRoleGroup(portalId, roleGroupId); + } - private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) + /// ----------------------------------------------------------------------------- + /// + /// Fetch a single RoleGroup by Name. + /// + /// The Id of the Portal. + /// Role Group Name. + /// + /// + /// ----------------------------------------------------------------------------- + public static RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) { - var user = UserController.GetUserById(portalId, userId); - var userRole = RoleController.Instance.GetUserRole(portalId, userId, roleId); - bool delete = true; - var portal = PortalController.Instance.GetPortal(portalId); - if (portal != null && userRole != null) - { - if (CanRemoveUserFromRole(portal, userId, roleId)) - { - provider.RemoveUserFromRole(portalId, user, userRole); - EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); - - // Remove the UserInfo from the Cache, as it has been modified - DataCache.ClearUserCache(portalId, user.Username); - Instance.ClearRoleCache(portalId); + return provider.GetRoleGroupByName(portalId, roleGroupName); + } - EventManager.Instance.OnRoleLeft(new RoleEventArgs() { Role = Instance.GetRoleById(portalId, roleId), User = user }); - } - else - { - delete = false; - } - } - - return delete; + /// ----------------------------------------------------------------------------- + /// + /// Gets an ArrayList of RoleGroups. + /// + /// The Id of the Portal. + /// An ArrayList of RoleGroups. + /// ----------------------------------------------------------------------------- + public static ArrayList GetRoleGroups(int PortalID) + { + return provider.GetRoleGroups(PortalID); } - private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalSettings PortalSettings, UserRoleActions Action) + /// ----------------------------------------------------------------------------- + /// + /// Serializes the role groups. + /// + /// An XmlWriter. + /// The Id of the Portal. + /// ----------------------------------------------------------------------------- + public static void SerializeRoleGroups(XmlWriter writer, int portalID) { - var Custom = new ArrayList { objRole.RoleName, objRole.Description }; - switch (Action) + // Serialize Role Groups + writer.WriteStartElement("rolegroups"); + foreach (RoleGroupInfo objRoleGroup in GetRoleGroups(portalID)) { - case UserRoleActions.add: - case UserRoleActions.update: - string preferredLocale = objUser.Profile.PreferredLocale; - if (string.IsNullOrEmpty(preferredLocale)) - { - preferredLocale = PortalSettings.DefaultLanguage; - } - - var ci = new CultureInfo(preferredLocale); - UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(PortalSettings.PortalId, objUser.UserID, objRole.RoleID); - Custom.Add(Null.IsNull(objUserRole.EffectiveDate) - ? DateTime.Today.ToString("g", ci) - : objUserRole.EffectiveDate.ToString("g", ci)); - Custom.Add(Null.IsNull(objUserRole.ExpiryDate) ? "-" : objUserRole.ExpiryDate.ToString("g", ci)); - break; - case UserRoleActions.delete: - Custom.Add(string.Empty); - break; + CBO.SerializeObject(objRoleGroup, writer); } - - var _message = new Message + + // Serialize Global Roles + var globalRoleGroup = new RoleGroupInfo(Null.NullInteger, portalID, true) { - FromUserID = PortalSettings.AdministratorId, - ToUserID = objUser.UserID, - Subject = - Localization.GetSystemMessage(objUser.Profile.PreferredLocale, PortalSettings, - "EMAIL_ROLE_" + - UserRoleActionsCaption[(int)Action] + - "_SUBJECT", objUser), - Body = Localization.GetSystemMessage( - objUser.Profile.PreferredLocale, - PortalSettings, - "EMAIL_ROLE_" + - UserRoleActionsCaption[(int)Action] + "_BODY", - objUser, - Localization.GlobalResourceFile, - Custom), - Status = MessageStatusType.Unread, + RoleGroupName = "GlobalRoles", + Description = "A dummy role group that represents the Global roles", }; + CBO.SerializeObject(globalRoleGroup, writer); + writer.WriteEndElement(); + } - // _messagingController.SaveMessage(_message); - Mail.SendEmail(PortalSettings.Email, objUser.Email, _message.Subject, _message.Body); - } - - private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) + /// ----------------------------------------------------------------------------- + /// + /// Updates a Role Group. + /// + /// The RoleGroup to Update. + /// ----------------------------------------------------------------------------- + public static void UpdateRoleGroup(RoleGroupInfo roleGroup) { - EventLogController.Instance.AddLog( - roleInfo, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - logType); + UpdateRoleGroup(roleGroup, false); } - private void AutoAssignUsers(RoleInfo role) + public static void UpdateRoleGroup(RoleGroupInfo roleGroup, bool includeRoles) { - if (role.AutoAssignment) + provider.UpdateRoleGroup(roleGroup); + EventLogController.Instance.AddLog(roleGroup, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); + if (includeRoles) { - // loop through users for portal and add to role - var arrUsers = UserController.GetUsers(role.PortalID); - foreach (UserInfo objUser in arrUsers) + foreach (RoleInfo role in roleGroup.Roles.Values) { - 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); - } + Instance.UpdateRole(role); + EventLogController.Instance.AddLog(role, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); } } } + public int AddRole(RoleInfo role) + { + return Instance.AddRole(role, true); + } + public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, bool isOwner, DateTime effectiveDate, DateTime expiryDate) { UserInfo user = UserController.GetUserById(portalId, userId); @@ -275,7 +316,7 @@ public void AddUserRole(int portalId, int userId, int roleId, RoleStatus status, } EventManager.Instance.OnRoleJoined(new RoleEventArgs() { Role = this.GetRoleById(portalId, roleId), User = user }); - + // Remove the UserInfo and Roles from the Cache, as they have been modified DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); @@ -310,7 +351,7 @@ public void DeleteRole(RoleInfo role) _fileManager.DeleteFiles(_folderManager.GetFiles(groupFolder)); _folderManager.DeleteFolder(groupFolder); } - + JournalController.Instance.SoftDeleteJournalItemByGroupId(portalSettings.PortalId, role.RoleID); } @@ -358,7 +399,7 @@ public RoleInfo GetRoleByName(int portalId, string roleName) public IList GetRoles(int portalId) { var cacheKey = string.Format(DataCache.RolesCacheKey, portalId); - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( new CacheItemArgs(cacheKey, DataCache.RolesCacheTimeOut, DataCache.RolesCachePriority), c => provider.GetRoles(portalId).Cast().ToList()); } @@ -411,11 +452,6 @@ public IList GetUsersByRole(int portalId, string roleName) return provider.GetUsersByRoleName(portalId, roleName).Cast().ToList(); } - void IRoleController.UpdateRole(RoleInfo role) - { - this.UpdateRole(role, true); - } - public void UpdateRole(RoleInfo role, bool addToExistUsers) { Requires.NotNull("role", role); @@ -460,7 +496,7 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat { // Delete Role DeleteUserRoleInternal(portalId, userId, roleId); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "UserId", userId.ToString(CultureInfo.InvariantCulture), PortalController.Instance.GetCurrentPortalSettings(), @@ -483,7 +519,7 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat ExpiryDate = userRole.ExpiryDate; IsTrialUsed = userRole.IsTrialUsed; } - + RoleInfo role = Instance.GetRole(portalId, r => r.RoleID == roleId); if (role != null) { @@ -498,17 +534,17 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat Frequency = role.BillingFrequency; } } - + if (EffectiveDate < DateTime.Now) { EffectiveDate = Null.NullDate; } - + if (ExpiryDate < DateTime.Now) { ExpiryDate = DateTime.Now; } - + if (Period == Null.NullInteger) { ExpiryDate = Null.NullDate; @@ -537,7 +573,7 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat break; } } - + if (UserRoleId != -1 && userRole != null) { userRole.ExpiryDate = ExpiryDate; @@ -551,203 +587,167 @@ public void UpdateUserRole(int portalId, int userId, int roleId, RoleStatus stat this.AddUserRole(portalId, userId, roleId, status, isOwner, EffectiveDate, ExpiryDate); } } - + // Remove the UserInfo from the Cache, as it has been modified DataCache.ClearUserCache(portalId, user.Username); Instance.ClearRoleCache(portalId); - } - - /// ----------------------------------------------------------------------------- - /// - /// Determines if the specified user can be removed from a role. - /// - /// - /// Roles such as "Registered Users" and "Administrators" can only - /// be removed in certain circumstances. - /// - /// A PortalSettings structure representing the current portal settings. - /// The Id of the User that should be checked for role removability. - /// The Id of the Role that should be checked for removability. - /// - /// ----------------------------------------------------------------------------- - public static bool CanRemoveUserFromRole(PortalSettings PortalSettings, int UserId, int RoleId) - { - // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb - // HACK: Duplicated in CanRemoveUserFromRole(PortalInfo, Integer, Integer) method below - // changes to this method should be reflected in the other method as well - return !((PortalSettings.AdministratorId == UserId && PortalSettings.AdministratorRoleId == RoleId) || PortalSettings.RegisteredRoleId == RoleId); - } - - /// ----------------------------------------------------------------------------- - /// - /// Determines if the specified user can be removed from a role. - /// - /// - /// Roles such as "Registered Users" and "Administrators" can only - /// be removed in certain circumstances. - /// - /// A PortalInfo structure representing the current portal. - /// The Id of the User. - /// The Id of the Role that should be checked for removability. - /// - /// ----------------------------------------------------------------------------- - public static bool CanRemoveUserFromRole(PortalInfo PortalInfo, int UserId, int RoleId) - { - // [DNN-4285] Refactored this check into a method for use in SecurityRoles.ascx.vb - // HACK: Duplicated in CanRemoveUserFromRole(PortalSettings, Integer, Integer) method above - // changes to this method should be reflected in the other method as well - return !((PortalInfo.AdministratorId == UserId && PortalInfo.AdministratorRoleId == RoleId) || PortalInfo.RegisteredRoleId == RoleId); } - /// ----------------------------------------------------------------------------- /// - /// Deletes a Role Group. + /// Completely remove all a user's roles for a specific portal. This method is used when + /// anonymizing a user. /// - /// ----------------------------------------------------------------------------- - public static void DeleteRoleGroup(int PortalID, int RoleGroupId) + /// 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) { - DeleteRoleGroup(GetRoleGroup(PortalID, RoleGroupId)); + 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); + } } - /// ----------------------------------------------------------------------------- - /// - /// Deletes a Role Group. - /// - /// The RoleGroup to Delete. - /// ----------------------------------------------------------------------------- - public static void DeleteRoleGroup(RoleGroupInfo objRoleGroupInfo) + protected override Func GetFactory() { - provider.DeleteRoleGroup(objRoleGroupInfo); - EventLogController.Instance.AddLog(objRoleGroupInfo, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_DELETED); + return () => new RoleController(); } - /// - /// Removes a User from a Role. - /// - /// The user to remove. - /// The role to remove the use from. - /// The PortalSettings of the Portal. - /// A flag that indicates whether the user should be notified. - /// - public static bool DeleteUserRole(UserInfo objUser, RoleInfo role, PortalSettings portalSettings, bool notifyUser) + private static bool DeleteUserRoleInternal(int portalId, int userId, int roleId) { - bool canDelete = DeleteUserRoleInternal(portalSettings.PortalId, objUser.UserID, role.RoleID); - if (canDelete) + var user = UserController.GetUserById(portalId, userId); + var userRole = RoleController.Instance.GetUserRole(portalId, userId, roleId); + bool delete = true; + var portal = PortalController.Instance.GetPortal(portalId); + if (portal != null && userRole != null) { - if (notifyUser) + if (CanRemoveUserFromRole(portal, userId, roleId)) { - SendNotification(objUser, role, portalSettings, UserRoleActions.delete); + provider.RemoveUserFromRole(portalId, user, userRole); + EventLogController.Instance.AddLog(userRole, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); + + // Remove the UserInfo from the Cache, as it has been modified + DataCache.ClearUserCache(portalId, user.Username); + Instance.ClearRoleCache(portalId); + + EventManager.Instance.OnRoleLeft(new RoleEventArgs() { Role = Instance.GetRoleById(portalId, roleId), User = user }); + } + else + { + delete = false; } } - - return canDelete; - } - - /// ----------------------------------------------------------------------------- - /// - /// Fetch a single RoleGroup. - /// - /// The Id of the Portal. - /// Role Group ID. - /// - /// - /// ----------------------------------------------------------------------------- - public static RoleGroupInfo GetRoleGroup(int portalId, int roleGroupId) - { - return provider.GetRoleGroup(portalId, roleGroupId); - } - /// ----------------------------------------------------------------------------- - /// - /// Fetch a single RoleGroup by Name. - /// - /// The Id of the Portal. - /// Role Group Name. - /// - /// - /// ----------------------------------------------------------------------------- - public static RoleGroupInfo GetRoleGroupByName(int portalId, string roleGroupName) - { - return provider.GetRoleGroupByName(portalId, roleGroupName); + return delete; } - /// - /// 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) + private static void SendNotification(UserInfo objUser, RoleInfo objRole, PortalSettings PortalSettings, UserRoleActions Action) { - var ctrl = new RoleController(); - var userRoles = ctrl.GetUserRoles(user, true); - foreach (var ur in userRoles.Where(r => r.PortalID == user.PortalID)) + var Custom = new ArrayList { objRole.RoleName, objRole.Description }; + switch (Action) { - provider.RemoveUserFromRole(user.PortalID, user, ur); + case UserRoleActions.add: + case UserRoleActions.update: + string preferredLocale = objUser.Profile.PreferredLocale; + if (string.IsNullOrEmpty(preferredLocale)) + { + preferredLocale = PortalSettings.DefaultLanguage; + } + + var ci = new CultureInfo(preferredLocale); + UserRoleInfo objUserRole = RoleController.Instance.GetUserRole(PortalSettings.PortalId, objUser.UserID, objRole.RoleID); + Custom.Add(Null.IsNull(objUserRole.EffectiveDate) + ? DateTime.Today.ToString("g", ci) + : objUserRole.EffectiveDate.ToString("g", ci)); + Custom.Add(Null.IsNull(objUserRole.ExpiryDate) ? "-" : objUserRole.ExpiryDate.ToString("g", ci)); + break; + case UserRoleActions.delete: + Custom.Add(string.Empty); + break; } - } - /// ----------------------------------------------------------------------------- - /// - /// Gets an ArrayList of RoleGroups. - /// - /// The Id of the Portal. - /// An ArrayList of RoleGroups. - /// ----------------------------------------------------------------------------- - public static ArrayList GetRoleGroups(int PortalID) - { - return provider.GetRoleGroups(PortalID); + var _message = new Message + { + FromUserID = PortalSettings.AdministratorId, + ToUserID = objUser.UserID, + Subject = + Localization.GetSystemMessage(objUser.Profile.PreferredLocale, PortalSettings, + "EMAIL_ROLE_" + + UserRoleActionsCaption[(int)Action] + + "_SUBJECT", objUser), + Body = Localization.GetSystemMessage( + objUser.Profile.PreferredLocale, + PortalSettings, + "EMAIL_ROLE_" + + UserRoleActionsCaption[(int)Action] + "_BODY", + objUser, + Localization.GlobalResourceFile, + Custom), + Status = MessageStatusType.Unread, + }; + + // _messagingController.SaveMessage(_message); + Mail.SendEmail(PortalSettings.Email, objUser.Email, _message.Subject, _message.Body); } - /// ----------------------------------------------------------------------------- - /// - /// Serializes the role groups. - /// - /// An XmlWriter. - /// The Id of the Portal. - /// ----------------------------------------------------------------------------- - public static void SerializeRoleGroups(XmlWriter writer, int portalID) + int IRoleController.AddRole(RoleInfo role, bool addToExistUsers) { - // Serialize Role Groups - writer.WriteStartElement("rolegroups"); - foreach (RoleGroupInfo objRoleGroup in GetRoleGroups(portalID)) + Requires.NotNull("role", role); + + var roleId = -1; + if (provider.CreateRole(role)) { - CBO.SerializeObject(objRoleGroup, writer); + this.AddMessage(role, EventLogController.EventLogType.ROLE_CREATED); + if (addToExistUsers) + { + this.AutoAssignUsers(role); + } + + roleId = role.RoleID; + + this.ClearRoleCache(role.PortalID); + + EventManager.Instance.OnRoleCreated(new RoleEventArgs() { Role = role }); } - // Serialize Global Roles - var globalRoleGroup = new RoleGroupInfo(Null.NullInteger, portalID, true) - { - RoleGroupName = "GlobalRoles", - Description = "A dummy role group that represents the Global roles", - }; - CBO.SerializeObject(globalRoleGroup, writer); - writer.WriteEndElement(); + return roleId; } - /// ----------------------------------------------------------------------------- - /// - /// Updates a Role Group. - /// - /// The RoleGroup to Update. - /// ----------------------------------------------------------------------------- - public static void UpdateRoleGroup(RoleGroupInfo roleGroup) + private void AddMessage(RoleInfo roleInfo, EventLogController.EventLogType logType) { - UpdateRoleGroup(roleGroup, false); + EventLogController.Instance.AddLog( + roleInfo, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + logType); } - public static void UpdateRoleGroup(RoleGroupInfo roleGroup, bool includeRoles) + private void AutoAssignUsers(RoleInfo role) { - provider.UpdateRoleGroup(roleGroup); - EventLogController.Instance.AddLog(roleGroup, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.USER_ROLE_UPDATED); - if (includeRoles) + if (role.AutoAssignment) { - foreach (RoleInfo role in roleGroup.Roles.Values) + // loop through users for portal and add to role + var arrUsers = UserController.GetUsers(role.PortalID); + foreach (UserInfo objUser in arrUsers) { - Instance.UpdateRole(role); - EventLogController.Instance.AddLog(role, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.ROLE_UPDATED); + 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); + } } } - } + } + + void IRoleController.UpdateRole(RoleInfo role) + { + this.UpdateRole(role, true); + } } } diff --git a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs index 551db984134..5868a4abddd 100644 --- a/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleGroupInfo.cs @@ -26,13 +26,13 @@ namespace DotNetNuke.Security.Roles /// ----------------------------------------------------------------------------- [Serializable] public class RoleGroupInfo : BaseEntityInfo, IHydratable, IXmlSerializable - { + { private string _Description; private int _PortalID = Null.NullInteger; private int _RoleGroupID = Null.NullInteger; private string _RoleGroupName; - private Dictionary _Roles; - + private Dictionary _Roles; + public RoleGroupInfo() { } @@ -45,8 +45,27 @@ public RoleGroupInfo(int roleGroupID, int portalID, bool loadRoles) { this.GetRoles(); } - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Roles for this Role Group. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public Dictionary Roles + { + get + { + if (this._Roles == null && this.RoleGroupID > Null.NullInteger) + { + this.GetRoles(); + } + + return this._Roles; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the RoleGroup Id. @@ -59,7 +78,7 @@ public int RoleGroupID { return this._RoleGroupID; } - + set { this._RoleGroupID = value; @@ -78,7 +97,7 @@ public int PortalID { return this._PortalID; } - + set { this._PortalID = value; @@ -97,7 +116,7 @@ public string RoleGroupName { return this._RoleGroupName; } - + set { this._RoleGroupName = value; @@ -116,32 +135,13 @@ public string Description { return this._Description; } - + set { this._Description = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Roles for this Role Group. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - public Dictionary Roles - { - get - { - if (this._Roles == null && this.RoleGroupID > Null.NullInteger) - { - this.GetRoles(); - } - - return this._Roles; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Key ID. @@ -154,13 +154,13 @@ public int KeyID { return this.RoleGroupID; } - + set { this.RoleGroupID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a RoleGroupInfo from a Data Reader. @@ -177,11 +177,11 @@ public void Fill(IDataReader dr) // Fill base class fields this.FillInternal(dr); } - + /// ----------------------------------------------------------------------------- /// /// Gets an XmlSchema for the RoleGroupInfo. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -203,12 +203,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name.ToLowerInvariant()) @@ -220,7 +220,7 @@ public void ReadXml(XmlReader reader) { this.ReadRoles(reader); } - + break; case "rolegroupname": this.RoleGroupName = reader.ReadElementContentAsString(); @@ -233,7 +233,7 @@ public void ReadXml(XmlReader reader) { reader.ReadElementContentAsString(); } - + break; } } @@ -272,8 +272,8 @@ public void WriteXml(XmlWriter writer) // Write end of main element writer.WriteEndElement(); - } - + } + private void GetRoles() { this._Roles = new Dictionary(); @@ -299,7 +299,7 @@ private void ReadRoles(XmlReader reader) var role = new RoleInfo(); role.ReadXml(reader); this._Roles.Add(role.RoleName, role); - } + } while (reader.ReadToNextSibling("role")); } } diff --git a/DNN Platform/Library/Security/Roles/RoleInfo.cs b/DNN Platform/Library/Security/Roles/RoleInfo.cs index 21d3fd8717d..51b89611192 100644 --- a/DNN Platform/Library/Security/Roles/RoleInfo.cs +++ b/DNN Platform/Library/Security/Roles/RoleInfo.cs @@ -44,8 +44,73 @@ public RoleInfo() this.BillingFrequency = "N"; this.RoleID = Null.NullInteger; this.IsSystemRole = false; - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Role Type. + /// + /// A enum representing the type of the role. + /// ----------------------------------------------------------------------------- + public RoleType RoleType + { + get + { + if (!this._RoleTypeSet) + { + this.GetRoleType(); + this._RoleTypeSet = true; + } + + return this._RoleType; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the role settings. + /// + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public Dictionary Settings + { + get + { + return this._settings ?? (this._settings = (this.RoleID == Null.NullInteger) + ? new Dictionary() + : RoleController.Instance.GetRoleSettings(this.RoleID) as + Dictionary); + } + } + + public string PhotoURL + { + get + { + string photoURL = Globals.ApplicationPath + "/images/sample-group-profile.jpg"; + + if (this.IconFile != null) + { + if (!string.IsNullOrEmpty(this.IconFile)) + { + IFileInfo fileInfo = + FileManager.Instance.GetFile(int.Parse(this.IconFile.Replace("FileID=", string.Empty))); + if (fileInfo != null) + { + photoURL = FileManager.Instance.GetUrl(fileInfo); + } + } + } + + return photoURL; + } + } + + public CacheLevel Cacheability + { + get { return CacheLevel.fullyCacheable; } + } + /// /// Gets or sets a value indicating whether gets whether this role is a system role. /// @@ -144,26 +209,6 @@ public RoleInfo() /// ----------------------------------------------------------------------------- public string RoleName { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Role Type. - /// - /// A enum representing the type of the role. - /// ----------------------------------------------------------------------------- - public RoleType RoleType - { - get - { - if (!this._RoleTypeSet) - { - this.GetRoleType(); - this._RoleTypeSet = true; - } - - return this._RoleType; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the RSVP Code for the role. @@ -189,23 +234,6 @@ public RoleType RoleType /// ----------------------------------------------------------------------------- public float ServiceFee { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the role settings. - /// - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public Dictionary Settings - { - get - { - return this._settings ?? (this._settings = (this.RoleID == Null.NullInteger) - ? new Dictionary() - : RoleController.Instance.GetRoleSettings(this.RoleID) as - Dictionary); - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the status for the role. @@ -255,29 +283,6 @@ public Dictionary Settings /// ----------------------------------------------------------------------------- public int UserCount { get; private set; } - public string PhotoURL - { - get - { - string photoURL = Globals.ApplicationPath + "/images/sample-group-profile.jpg"; - - if (this.IconFile != null) - { - if (!string.IsNullOrEmpty(this.IconFile)) - { - IFileInfo fileInfo = - FileManager.Instance.GetFile(int.Parse(this.IconFile.Replace("FileID=", string.Empty))); - if (fileInfo != null) - { - photoURL = FileManager.Instance.GetUrl(fileInfo); - } - } - } - - return photoURL; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Key ID. @@ -288,13 +293,8 @@ public virtual int KeyID { get { return this.RoleID; } set { this.RoleID = value; } - } - - public CacheLevel Cacheability - { - get { return CacheLevel.fullyCacheable; } } - + /// ----------------------------------------------------------------------------- /// /// Fills a RoleInfo from a Data Reader. @@ -335,7 +335,7 @@ public virtual void Fill(IDataReader dr) this.SecurityMode = SecurityMode.Both; break; } - + int status = Null.SetNullInteger(dr["Status"]); switch (status) { @@ -349,7 +349,7 @@ public virtual void Fill(IDataReader dr) this.Status = RoleStatus.Approved; break; } - + // check for values only relevant to UserRoles var schema = dr.GetSchemaTable(); if (schema != null) @@ -358,7 +358,7 @@ public virtual void Fill(IDataReader dr) { this.UserCount = Null.SetNullInteger(dr["UserCount"]); } - + if (schema.Select("ColumnName = 'IsSystemRole'").Length > 0) { this.IsSystemRole = Null.SetNullBoolean(dr["IsSystemRole"]); @@ -369,7 +369,7 @@ public virtual void Fill(IDataReader dr) { // do nothing } - + // Fill base class fields this.FillInternal(dr); } @@ -386,7 +386,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format { OutputFormat = format; } - + string propName = propertyName.ToLowerInvariant(); switch (propName) { @@ -445,33 +445,12 @@ public string GetProperty(string propertyName, string format, CultureInfo format propertyNotFound = true; return string.Empty; } - } - - 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. - /// + /// /// /// ----------------------------------------------------------------------------- public XmlSchema GetSchema() @@ -496,12 +475,12 @@ public void ReadXml(XmlReader reader) { break; } - + if (reader.NodeType == XmlNodeType.Whitespace) { continue; } - + if (reader.NodeType == XmlNodeType.Element) { switch (reader.Name.ToLowerInvariant()) @@ -520,7 +499,7 @@ public void ReadXml(XmlReader reader) { this.BillingFrequency = "N"; } - + break; case "billingperiod": this.BillingPeriod = reader.ReadElementContentAsInt(); @@ -531,7 +510,7 @@ public void ReadXml(XmlReader reader) { this.ServiceFee = 0; } - + break; case "trialfrequency": this.TrialFrequency = reader.ReadElementContentAsString(); @@ -539,7 +518,7 @@ public void ReadXml(XmlReader reader) { this.TrialFrequency = "N"; } - + break; case "trialperiod": this.TrialPeriod = reader.ReadElementContentAsInt(); @@ -550,7 +529,7 @@ public void ReadXml(XmlReader reader) { this.TrialFee = 0; } - + break; case "ispublic": this.IsPublic = reader.ReadElementContentAsBoolean(); @@ -586,7 +565,7 @@ public void ReadXml(XmlReader reader) this._RoleType = RoleType.None; break; } - + this._RoleTypeSet = true; break; case "securitymode": @@ -602,7 +581,7 @@ public void ReadXml(XmlReader reader) this.SecurityMode = SecurityMode.Both; break; } - + break; case "status": switch (reader.ReadElementContentAsString()) @@ -617,14 +596,14 @@ public void ReadXml(XmlReader reader) this.Status = RoleStatus.Approved; break; } - + break; default: if (reader.NodeType == XmlNodeType.Element && !string.IsNullOrEmpty(reader.Name)) { reader.ReadElementContentAsString(); } - + break; } } @@ -687,7 +666,7 @@ public void WriteXml(XmlWriter writer) writer.WriteElementString("securitymode", "both"); break; } - + switch (this.Status) { case RoleStatus.Pending: @@ -703,15 +682,36 @@ public void WriteXml(XmlWriter writer) // Write end of main element writer.WriteEndElement(); - } - + } + + 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; + } + } + private string GetString(string keyName, string defaultValue) { if (this.Settings == null) { return defaultValue; } - + if (this.Settings.ContainsKey(keyName)) { return this.Settings[keyName]; @@ -727,7 +727,7 @@ private string FormatUrl(string url) // server absolute path return Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + url; } - + return url; } } diff --git a/DNN Platform/Library/Security/Roles/RoleProvider.cs b/DNN Platform/Library/Security/Roles/RoleProvider.cs index 00aa1d7ded3..eed3ef4bb57 100644 --- a/DNN Platform/Library/Security/Roles/RoleProvider.cs +++ b/DNN Platform/Library/Security/Roles/RoleProvider.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Security.Roles using DotNetNuke.Security.Roles.Internal; public abstract class RoleProvider - { - // return the provider + { + // return the provider public static RoleProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + public virtual bool CreateRole(RoleInfo role) { throw new NotImplementedException(); @@ -35,7 +35,7 @@ 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(); } @@ -43,9 +43,9 @@ public virtual IDictionary GetRoleSettings(int roleId) public virtual void UpdateRoleSettings(RoleInfo role) { - } - - // Role Groups + } + + // Role Groups public abstract int CreateRoleGroup(RoleGroupInfo roleGroup); public abstract void DeleteRoleGroup(RoleGroupInfo roleGroup); @@ -54,8 +54,8 @@ public virtual void UpdateRoleSettings(RoleInfo role) public abstract ArrayList GetRoleGroups(int portalId); - public abstract void UpdateRoleGroup(RoleGroupInfo roleGroup); - + public abstract void UpdateRoleGroup(RoleGroupInfo roleGroup); + public abstract bool AddUserToRole(int portalId, UserInfo user, UserRoleInfo userRole); public abstract UserRoleInfo GetUserRole(int PortalId, int UserId, int RoleId); @@ -66,8 +66,8 @@ public virtual void UpdateRoleSettings(RoleInfo role) public abstract void RemoveUserFromRole(int portalId, UserInfo user, UserRoleInfo userRole); - public abstract void UpdateUserRole(UserRoleInfo userRole); - + public abstract void UpdateUserRole(UserRoleInfo userRole); + public virtual RoleGroupInfo GetRoleGroupByName(int PortalID, string RoleGroupName) { return null; diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs index daddd81785a..028b69ac497 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsConfiguration.cs @@ -19,17 +19,17 @@ namespace DotNetNuke.Services.Analytics.Config [XmlRoot("AnalyticsConfig")] public class AnalyticsConfiguration { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsConfiguration)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AnalyticsConfiguration)); private AnalyticsRuleCollection _rules; - private AnalyticsSettingCollection _settings; - + private AnalyticsSettingCollection _settings; + public AnalyticsSettingCollection Settings { get { return this._settings; } - + set { this._settings = value; @@ -42,13 +42,13 @@ public AnalyticsRuleCollection Rules { return this._rules; } - + set { this._rules = value; } - } - + } + public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { string cacheKey = analyticsEngineName + "." + PortalSettings.Current.PortalId; @@ -87,7 +87,7 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) setting.SettingValue = nav.SelectSingleNode("SettingValue").Value; Config.Settings.Add(setting); } - + foreach (XPathNavigator nav in doc.CreateNavigator().Select("AnalyticsConfig/Rules/AnalyticsRule")) { var rule = new AnalyticsRule(); @@ -99,10 +99,10 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) { rule.Value = valueNode.Value; } - + Config.Rules.Add(rule); } - + if (File.Exists(filePath)) { // Set back into Cache @@ -128,7 +128,7 @@ public static AnalyticsConfiguration GetConfig(string analyticsEngineName) fileReader.Close(); } } - + return Config; } @@ -147,7 +147,7 @@ public static void SaveConfig(string analyticsEngineName, AnalyticsConfiguration { File.SetAttributes(filePath, FileAttributes.Normal); } - + using (var fileWriter = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var writer = new StreamWriter(fileWriter)) { @@ -158,9 +158,9 @@ public static void SaveConfig(string analyticsEngineName, AnalyticsConfiguration writer.Close(); fileWriter.Close(); } - + DataCache.SetCache(cacheKey, config, new DNNCacheDependency(filePath)); } - } + } } } diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs index 93f2b77a263..79e281dc2f7 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRule.cs @@ -18,7 +18,7 @@ public int RoleId { return this._roleId; } - + set { this._roleId = value; @@ -31,7 +31,7 @@ public int TabId { return this._tabId; } - + set { this._tabId = value; @@ -44,7 +44,7 @@ public string Label { return this._label; } - + set { this._label = value; diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs index 036bb95adba..f5432022c48 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsRuleCollection.cs @@ -15,7 +15,7 @@ public virtual AnalyticsRule this[int index] { return (AnalyticsRule)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs index 80f466cded3..520ca78afe1 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSetting.cs @@ -17,7 +17,7 @@ public string SettingName { return this._settingName; } - + set { this._settingName = value; @@ -30,7 +30,7 @@ public string SettingValue { return this._settingValue; } - + set { this._settingValue = value; diff --git a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs index 58f91d6506e..f9277e82b6a 100644 --- a/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs +++ b/DNN Platform/Library/Services/Analytics/Config/AnalyticsSettingCollection.cs @@ -15,7 +15,7 @@ public virtual AnalyticsSetting this[int index] { return (AnalyticsSetting)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs index acf8c7b498f..45465470fed 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsController.cs @@ -27,7 +27,7 @@ namespace DotNetNuke.Services.Analytics public class GoogleAnalyticsController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(GoogleAnalyticsController)); - + /// ----------------------------------------------------------------------------- /// /// Handles module upgrades includes a new Google Analytics Asychronous script. @@ -70,7 +70,7 @@ public void UpgradeModule(string Version) } } } - + break; } } @@ -108,7 +108,7 @@ private StreamReader GetConfigFile() { fileReader.Close(); } - + Logger.Error(ex); } diff --git a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs index 04d43895743..e09f75744d9 100644 --- a/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs +++ b/DNN Platform/Library/Services/Analytics/GoogleAnalyticsEngine.cs @@ -47,7 +47,7 @@ public override string RenderScript(string scriptTemplate) { trackForAdmin = true; } - + break; } } @@ -93,20 +93,20 @@ 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; } } } - + var customScripts = new System.Text.StringBuilder(); if (anonymize || PortalSettings.Current.DataConsentActive) diff --git a/DNN Platform/Library/Services/Assets/AssetManager.cs b/DNN Platform/Library/Services/Assets/AssetManager.cs index 3ecb6251fbb..f1f8264cf08 100644 --- a/DNN Platform/Library/Services/Assets/AssetManager.cs +++ b/DNN Platform/Library/Services/Assets/AssetManager.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Services.Assets using Localization = DotNetNuke.Services.Localization.Localization; public class AssetManager : ComponentBase, IAssetManager - { + { private const string UserHasNoPermissionToBrowseFolderDefaultMessage = "The user has no permission to browse this folder"; private const string FileNameInvalidDefaultMessage = "The specified name ({0}) is not valid"; private const string FolderFileNameIsReservedDefaultMessage = "The name is reserved. Try a different name"; @@ -33,7 +33,7 @@ public class AssetManager : ComponentBase, IAssetMa private const string InvalidMappedPathDefaultMessage = "The Mapped Path is invalid"; private const string FolderAlreadyExistsDefaultMessage = "Cannot create folder ({0}), folder already exists in this location"; private const string FolderFileNameHasInvalidcharactersDefaultMessage = "The name contains invalid character(s). Please specify a name without {0}"; - private const string DefaultMessageDefaultMessage = "The folder does not exist"; + 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) @@ -45,11 +45,11 @@ public static IOrderedQueryable ApplyOrder(IQueryable source, string pr var property = typeof(T).GetProperty(propertyName); // If property is undefined returns the original source - if (property == null) - { - return (IOrderedQueryable)source; - } - + if (property == null) + { + return (IOrderedQueryable)source; + } + Expression expr = Expression.Property(arg, property); var delegateType = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType); @@ -229,7 +229,7 @@ public IFolderInfo RenameFolder(int folderId, string newFolderName) { return folder; } - + if (folder.FolderName.Equals(newFolderName, StringComparison.InvariantCultureIgnoreCase)) { folder.FolderPath = this.ReplaceFolderName(folder.FolderPath, folder.FolderName, newFolderName); @@ -237,7 +237,7 @@ public IFolderInfo RenameFolder(int folderId, string newFolderName) } var newFolderPath = this.GetNewFolderPath(newFolderName, folder); - + // Check if the new folder already exists if (FolderManager.Instance.FolderExists(folder.PortalID, newFolderPath)) { @@ -248,47 +248,6 @@ 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); @@ -338,11 +297,11 @@ public IFolderInfo CreateFolder(string folderName, int folderParentId, int folde public bool DeleteFolder(int folderId, bool onlyUnlink, ICollection nonDeletedSubfolders) { var folder = FolderManager.Instance.GetFolder(folderId); - if (folder == null) - { - return false; - } - + if (folder == null) + { + return false; + } + if (!HasPermission(folder, "DELETE")) { nonDeletedSubfolders.Add(folder); @@ -365,11 +324,11 @@ public bool DeleteFolder(int folderId, bool onlyUnlink, ICollection public bool DeleteFile(int fileId) { var fileInfo = FileManager.Instance.GetFile(fileId, true); - if (fileInfo == null) - { - return false; - } - + if (fileInfo == null) + { + return false; + } + var folder = FolderManager.Instance.GetFolder(fileInfo.FolderId); if (!HasPermission(folder, "DELETE")) @@ -381,11 +340,52 @@ public bool DeleteFile(int fileId) return true; } + 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 static IOrderedEnumerable OrderBy(IEnumerable source, Func keySelector, IComparer comparer, bool ascending) + { + return ascending ? source.OrderBy(keySelector, comparer) : source.OrderByDescending(keySelector, comparer); + } + private static string CleanDotsAtTheEndOfTheName(string name) { return name.Trim().TrimEnd('.', ' '); } + 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 void DeleteFolder(IFolderInfo folder, ICollection nonDeletedItems) { var nonDeletedSubfolders = new List(); @@ -431,7 +431,7 @@ private bool IsReservedName(string name) private string GetInvalidCharsErrorText() { - throw new AssetManagerException(Localization.GetExceptionMessage( + throw new AssetManagerException(Localization.GetExceptionMessage( "FolderFileNameHasInvalidcharacters", FolderFileNameHasInvalidcharactersDefaultMessage, "\\:/*?\"<>|")); } @@ -443,7 +443,7 @@ private IFolderInfo GetFolderInfo(int folderId) { throw new AssetManagerException(Localization.GetExceptionMessage("FolderDoesNotExists", DefaultMessageDefaultMessage)); } - + return folder; } @@ -454,7 +454,7 @@ private string ReplaceFolderName(string path, string folderName, string newFolde { return path; } - + var nameIndex = newPath.LastIndexOf(folderName, StringComparison.Ordinal); if (nameIndex == -1) { diff --git a/DNN Platform/Library/Services/Assets/AssetManagerException.cs b/DNN Platform/Library/Services/Assets/AssetManagerException.cs index b80a2f536ae..ea9ff9ad065 100644 --- a/DNN Platform/Library/Services/Assets/AssetManagerException.cs +++ b/DNN Platform/Library/Services/Assets/AssetManagerException.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.Services.Assets public class AssetManagerException : Exception { - public AssetManagerException(string message) + public AssetManagerException(string message) : base(message) { } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs index 24a0316dd7d..13890bfb264 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfig.cs @@ -21,7 +21,7 @@ public class AuthenticationConfig : AuthenticationConfigBase private const string CACHEKEY = "Authentication.DNN"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AuthenticationConfig)); - protected AuthenticationConfig(int portalID) + protected AuthenticationConfig(int portalID) : base(portalID) { this.UseCaptcha = Null.NullBoolean; @@ -33,7 +33,7 @@ protected AuthenticationConfig(int portalID) { this.Enabled = bool.Parse(setting); } - + setting = Null.NullString; if (PortalController.Instance.GetPortalSettings(portalID).TryGetValue("DNN_UseCaptcha", out setting)) { @@ -65,7 +65,7 @@ public static AuthenticationConfig GetConfig(int portalId) config = new AuthenticationConfig(portalId); DataCache.SetCache(key, config); } - + return config; } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs index 49afae67766..823f33e9f3e 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationConfigBase.cs @@ -31,7 +31,7 @@ protected AuthenticationConfigBase(int portalID) [Browsable(false)] public int PortalID { get; set; } - + /// /// Gets the Dependency Provider to resolve registered /// services with the container. diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs index fcb0e4cde23..ffbbbaa143d 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationController.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationController.cs @@ -88,11 +88,6 @@ 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. /// @@ -409,5 +404,10 @@ public static void UpdateAuthentication(AuthenticationInfo authSystem) UserController.Instance.GetCurrentUserInfo().UserID); EventLogController.Instance.AddLog(authSystem, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.AUTHENTICATION_UPDATED); } + + private static object GetAuthenticationServicesCallBack(CacheItemArgs cacheItemArgs) + { + return CBO.FillCollection(provider.GetAuthenticationServices()); + } } } diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs index 0d6cdaf242d..0a117d7142e 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationInfo.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Services.Authentication /// ----------------------------------------------------------------------------- [Serializable] public class AuthenticationInfo : BaseEntityInfo, IHydratable - { + { public AuthenticationInfo() { this.LogoffControlSrc = Null.NullString; @@ -26,8 +26,8 @@ public AuthenticationInfo() this.SettingsControlSrc = Null.NullString; this.AuthenticationType = Null.NullString; this.AuthenticationID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and Sets the ID of the Authentication System. @@ -75,7 +75,7 @@ public AuthenticationInfo() /// Gets or sets and Sets the url for the Logoff Control. /// /// ----------------------------------------------------------------------------- - public string LogoffControlSrc { get; set; } + public string LogoffControlSrc { get; set; } /// ----------------------------------------------------------------------------- /// @@ -89,13 +89,13 @@ public virtual int KeyID { return this.AuthenticationID; } - + set { this.AuthenticationID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a RoleInfo from a Data Reader. diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs index 3a07044a872..3990c0441d7 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLoginBase.cs @@ -17,24 +17,17 @@ namespace DotNetNuke.Services.Authentication /// /// ----------------------------------------------------------------------------- public abstract class AuthenticationLoginBase : UserModuleBase - { + { 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; + public delegate void UserAuthenticatedEventHandler(object sender, UserAuthenticatedEventArgs e); - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and Sets the Type of Authentication associated with this control. - /// - /// ----------------------------------------------------------------------------- - public string AuthenticationType { get; set; } + public event UserAuthenticatedEventHandler UserAuthenticated; /// ----------------------------------------------------------------------------- /// @@ -61,29 +54,36 @@ public string IPAddress /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Authentication mode of the control (Login or Register). + /// Gets a value indicating whether gets whether the control supports Registration. /// /// This property may be overriden in the inherited class. /// ----------------------------------------------------------------------------- - public virtual AuthMode Mode { get; set; } + public virtual bool SupportsRegistration + { + get { return false; } + } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and Sets the Redirect Url for this control. + /// Gets or sets and Sets the Type of Authentication associated with this control. /// /// ----------------------------------------------------------------------------- - public string RedirectURL { get; set; } + public string AuthenticationType { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether gets whether the control supports Registration. + /// Gets or sets the Authentication mode of the control (Login or Register). /// /// This property may be overriden in the inherited class. /// ----------------------------------------------------------------------------- - public virtual bool SupportsRegistration - { - get { return false; } - } + public virtual AuthMode Mode { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and Sets the Redirect Url for this control. + /// + /// ----------------------------------------------------------------------------- + public string RedirectURL { get; set; } [Obsolete("Deprecated in 9.2.0. Use UserRequestIPAddressController.Instance.GetUserRequestIPAddress. Scheduled removal in v11.0.0.")] public static string GetIPAddress() diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs index 4aefc9dae38..796d3811bb8 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationLogoffBase.cs @@ -26,7 +26,7 @@ public AuthenticationLogoffBase() } public event EventHandler LogOff; - + public event EventHandler Redirect; /// ----------------------------------------------------------------------------- @@ -40,7 +40,7 @@ public string AuthenticationType { return this._AuthenticationType; } - + set { this._AuthenticationType = value; diff --git a/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs b/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs index 346108a23a7..ec0d5ab1253 100644 --- a/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs +++ b/DNN Platform/Library/Services/Authentication/AuthenticationSettingsBase.cs @@ -27,7 +27,7 @@ public string AuthenticationType { return this._AuthenticationType; } - + set { this._AuthenticationType = value; diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs index a84a04b8c37..6523bcbc316 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthClientBase.cs @@ -24,14 +24,12 @@ namespace DotNetNuke.Services.Authentication.OAuth using DotNetNuke.Services.Localization; public abstract class 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"; @@ -54,10 +52,12 @@ public abstract class OAuthClientBase // 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 const string OAuthResourceKey = "resource"; + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(OAuthClientBase)); private readonly Random random = new Random(); - + protected OAuthClientBase(int portalId, AuthMode mode, string service) { // Set default Expiry to 14 days @@ -73,10 +73,20 @@ protected OAuthClientBase(int portalId, AuthMode mode, string service) this.CallbackUri = this.Mode == AuthMode.Login ? new Uri(Globals.LoginURL(string.Empty, false)) : new Uri(Globals.RegisterURL(string.Empty, string.Empty)); - } - + } + + public virtual bool PrefixServiceToUserName + { + get { return true; } + } + + public virtual bool AutoMatchExistingUsers + { + get { return false; } + } + public Uri CallbackUri { get; set; } - + public string Service { get; set; } protected virtual string UserGuidKey @@ -84,67 +94,57 @@ protected virtual string UserGuidKey get { return string.Empty; } } + // oAuth 1 + protected string OAuthVerifier + { + get { return HttpContext.Current.Request.Params[OAuthVerifierKey]; } + } + + protected string VerificationCode + { + get { return HttpContext.Current.Request.Params[OAuthCodeKey]; } + } + protected string APIKey { get; set; } - + protected string APISecret { get; set; } - + protected AuthMode Mode { get; set; } - + protected string OAuthVersion { get; set; } - + protected HttpMethod TokenMethod { get; set; } - // oAuth 1 - protected string OAuthVerifier - { - get { return HttpContext.Current.Request.Params[OAuthVerifierKey]; } - } - protected Uri RequestTokenEndpoint { get; set; } - + protected HttpMethod RequestTokenMethod { get; set; } - + protected string TokenSecret { get; set; } - + protected string UserGuid { get; set; } // oAuth 1 and 2 protected Uri AuthorizationEndpoint { get; set; } - + protected string AuthToken { get; set; } - + protected TimeSpan AuthTokenExpiry { get; set; } - + protected Uri MeGraphEndpoint { get; set; } - + protected Uri TokenEndpoint { get; set; } - + protected string OAuthHeaderCode { get; set; } // oAuth 2 protected string AuthTokenName { get; set; } - + protected string Scope { get; set; } - + protected string AccessToken { get; set; } - - protected string VerificationCode - { - get { return HttpContext.Current.Request.Params[OAuthCodeKey]; } - } // DNN-6265 Support "Optional" Resource Parameter required by Azure AD Oauth V2 Solution - protected string APIResource { get; set; } - - public virtual bool PrefixServiceToUserName - { - get { return true; } - } - - public virtual bool AutoMatchExistingUsers - { - get { return false; } - } + protected string APIResource { get; set; } /// /// This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case. @@ -170,7 +170,7 @@ public static string UrlEncode(string value) return result.ToString(); } - + public virtual void AuthenticateUser(UserData user, PortalSettings settings, string IPAddress, Action addCustomProperties, Action onAuthenticated) { var loginStatus = UserLoginStatus.LOGIN_FAILURE; @@ -198,12 +198,12 @@ public virtual void AuthenticateUser(UserData user, PortalSettings settings, str 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 eventArgs = new UserAuthenticatedEventArgs(objUserInfo, token, loginStatus, this.Service) + { + AutoRegister = true, + UserName = userName, }; var profileProperties = new NameValueCollection(); @@ -212,32 +212,32 @@ public virtual void AuthenticateUser(UserData user, PortalSettings settings, str { 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('_', '-'))) @@ -286,10 +286,83 @@ public virtual AuthorisationResult Authorize() { return this.AuthorizeV1(); } - + return this.AuthorizeV2(); } - + + /// + /// Generates a signature using the HMAC-SHA1 algorithm. + /// + /// The full url that needs to be signed including its non OAuth url parameters. + /// The token, if available. If not available pass null or an empty string. + /// The token secret, if available. If not available pass null or an empty string. + /// + /// This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string. + /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc). + /// + /// + /// + /// + /// A base64 string of the hash value. + public string GenerateSignature(Uri url, string token, string tokenSecret, string callbackurl, string oauthVerifier, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out List requestParameters) + { + 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), + string.IsNullOrEmpty(tokenSecret) + ? string.Empty + : UrlEncode(tokenSecret))), + }; + + return this.GenerateSignatureUsingHash(signatureBase, hmacsha1); + } + + public virtual TUserData GetCurrentUser() + where TUserData : UserData + { + this.LoadTokenCookie(string.Empty); + + if (!this.IsCurrentUserAuthorized()) + { + return null; + } + + var accessToken = string.IsNullOrEmpty(this.AccessToken) ? "access_token=" + this.AuthToken : this.AccessToken + "=" + this.AuthToken; + string responseText = (this.OAuthVersion == "1.0") + ? this.ExecuteAuthorizedRequest(HttpMethod.GET, this.MeGraphEndpoint) + : this.ExecuteWebRequest(HttpMethod.GET, this.GenerateRequestUri(this.MeGraphEndpoint.ToString(), accessToken), null, string.Empty); + var user = Json.Deserialize(responseText); + return user; + } + + public bool HaveVerificationCode() + { + return (this.OAuthVersion == "1.0") ? (this.OAuthVerifier != null) : (this.VerificationCode != null); + } + + public bool IsCurrentService() + { + string service = HttpContext.Current.Request.Params["state"]; + return !string.IsNullOrEmpty(service) && service == this.Service; + } + + public bool IsCurrentUserAuthorized() + { + return !string.IsNullOrEmpty(this.AuthToken); + } + + public void RemoveToken() + { + var authTokenCookie = new HttpCookie(this.AuthTokenName) + { + Expires = DateTime.Now.AddDays(-30), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }; + HttpContext.Current.Response.SetCookie(authTokenCookie); + } + /// /// Generate the timestamp for the signature. /// @@ -310,7 +383,31 @@ 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) + { + return TimeSpan.MinValue; + } + + protected virtual string GetToken(string responseText) + { + return responseText; + } + + protected void LoadTokenCookie(string suffix) + { + HttpCookie authTokenCookie = HttpContext.Current.Request.Cookies[this.AuthTokenName + suffix]; + if (authTokenCookie != null) + { + if (authTokenCookie.HasKeys) + { + this.AuthToken = authTokenCookie.Values[OAuthTokenKey]; + this.TokenSecret = authTokenCookie.Values[OAuthTokenSecretKey]; + this.UserGuid = authTokenCookie.Values[this.UserGuidKey]; + } + } + } + private AuthorisationResult AuthorizeV1() { if (!this.IsCurrentUserAuthorized()) @@ -410,7 +507,7 @@ private void ExchangeCodeForToken() IList parameters = new List(); parameters.Add(new QueryParameter(OAuthClientIdKey, this.APIKey)); parameters.Add(new QueryParameter(OAuthRedirectUriKey, HttpContext.Current.Server.UrlEncode(this.CallbackUri.ToString()))); - + // DNN-6265 Support for OAuth V2 Secrets which are not URL Friendly parameters.Add(new QueryParameter(OAuthClientSecretKey, HttpContext.Current.Server.UrlEncode(this.APISecret.ToString()))); parameters.Add(new QueryParameter(OAuthGrantTyepKey, "authorization_code")); @@ -442,12 +539,12 @@ private void ExchangeRequestTokenForToken() { this.AuthToken = qs[OAuthTokenKey]; } - + if (qs[OAuthTokenSecretKey] != null) { this.TokenSecret = qs[OAuthTokenSecretKey]; } - + if (qs[this.UserGuidKey] != null) { this.UserGuid = qs[this.UserGuidKey]; @@ -464,9 +561,9 @@ private string ExecuteAuthorizedRequest(HttpMethod method, Uri uri) string timeStamp = this.GenerateTimeStamp(); string verifier = (uri == this.TokenEndpoint) ? this.OAuthVerifier : string.Empty; - + // Generate Signature - string sig = this.GenerateSignature( + string sig = this.GenerateSignature( uri, this.AuthToken, this.TokenSecret, @@ -477,7 +574,7 @@ private string ExecuteAuthorizedRequest(HttpMethod method, Uri uri) nonce, out outUrl, out requestParameters); - + var headerParameters = new List { new QueryParameter(OAuthConsumerKeyKey, this.APIKey), @@ -509,7 +606,7 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, request = WebRequest.CreateDefault(uri); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; - + // request.ContentType = "text/xml"; request.ContentLength = byteArray.Length; @@ -517,7 +614,7 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, { byte[] API64 = Encoding.UTF8.GetBytes(this.APIKey + ":" + this.APISecret); string Api64Encoded = System.Convert.ToBase64String(API64); - + // Authentication providers needing an "Authorization: Basic/bearer base64(clientID:clientSecret)" header. OAuthHeaderCode might be: Basic/Bearer/empty. request.Headers.Add("Authorization: " + this.OAuthHeaderCode + " " + Api64Encoded); } @@ -569,7 +666,7 @@ private string ExecuteWebRequest(HttpMethod method, Uri uri, string parameters, } } } - + return null; } @@ -614,7 +711,7 @@ private string GenerateSignatureBase(Uri url, string token, string callbackurl, { normalizedUrl += ":" + url.Port; } - + normalizedUrl += url.AbsolutePath; string normalizedRequestParameters = requestParameters.ToNormalizedString(); @@ -671,7 +768,7 @@ private string RequestToken() string nonce = this.GenerateNonce(); string timeStamp = this.GenerateTimeStamp(); - string sig = this.GenerateSignature( + string sig = this.GenerateSignature( this.RequestTokenEndpoint, string.Empty, string.Empty, @@ -718,103 +815,6 @@ private Uri GenerateRequestUri(string url, string parameters) } return new Uri(string.Format("{0}{1}{2}", url, url.Contains("?") ? "&" : "?", parameters)); - } - - protected virtual TimeSpan GetExpiry(string responseText) - { - return TimeSpan.MinValue; - } - - protected virtual string GetToken(string responseText) - { - return responseText; - } - - protected void LoadTokenCookie(string suffix) - { - HttpCookie authTokenCookie = HttpContext.Current.Request.Cookies[this.AuthTokenName + suffix]; - if (authTokenCookie != null) - { - if (authTokenCookie.HasKeys) - { - this.AuthToken = authTokenCookie.Values[OAuthTokenKey]; - this.TokenSecret = authTokenCookie.Values[OAuthTokenSecretKey]; - this.UserGuid = authTokenCookie.Values[this.UserGuidKey]; - } - } - } - - /// - /// Generates a signature using the HMAC-SHA1 algorithm. - /// - /// The full url that needs to be signed including its non OAuth url parameters. - /// The token, if available. If not available pass null or an empty string. - /// The token secret, if available. If not available pass null or an empty string. - /// - /// This value MUST be included when exchanging Request Tokens for Access Tokens. Otherwise pass a null or an empty string. - /// The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc). - /// - /// - /// - /// - /// A base64 string of the hash value. - public string GenerateSignature(Uri url, string token, string tokenSecret, string callbackurl, string oauthVerifier, string httpMethod, string timeStamp, string nonce, out string normalizedUrl, out List requestParameters) - { - 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), - string.IsNullOrEmpty(tokenSecret) - ? string.Empty - : UrlEncode(tokenSecret))), - }; - - return this.GenerateSignatureUsingHash(signatureBase, hmacsha1); - } - - public virtual TUserData GetCurrentUser() - where TUserData : UserData - { - this.LoadTokenCookie(string.Empty); - - if (!this.IsCurrentUserAuthorized()) - { - return null; - } - - var accessToken = string.IsNullOrEmpty(this.AccessToken) ? "access_token=" + this.AuthToken : this.AccessToken + "=" + this.AuthToken; - string responseText = (this.OAuthVersion == "1.0") - ? this.ExecuteAuthorizedRequest(HttpMethod.GET, this.MeGraphEndpoint) - : this.ExecuteWebRequest(HttpMethod.GET, this.GenerateRequestUri(this.MeGraphEndpoint.ToString(), accessToken), null, string.Empty); - var user = Json.Deserialize(responseText); - return user; - } - - public bool HaveVerificationCode() - { - return (this.OAuthVersion == "1.0") ? (this.OAuthVerifier != null) : (this.VerificationCode != null); - } - - public bool IsCurrentService() - { - string service = HttpContext.Current.Request.Params["state"]; - return !string.IsNullOrEmpty(service) && service == this.Service; - } - - public bool IsCurrentUserAuthorized() - { - return !string.IsNullOrEmpty(this.AuthToken); - } - - public void RemoveToken() - { - var authTokenCookie = new HttpCookie(this.AuthTokenName) - { - Expires = DateTime.Now.AddDays(-30), - Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", - }; - HttpContext.Current.Response.SetCookie(authTokenCookie); } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs index 4b651264932..61d4a20ec34 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthConfigBase.cs @@ -55,12 +55,12 @@ protected OAuthConfigBase(string service, int portalId) public string APISecret { get; set; } - protected string Service { get; set; } - public bool Enabled { get; set; } public bool HostConfig { get; set; } + protected string Service { get; set; } + public static void ClearConfig(string service, int portalId) { DataCache.RemoveCache(GetCacheKey(service, portalId)); @@ -75,13 +75,8 @@ public static OAuthConfigBase GetConfig(string service, int portalId) config = new OAuthConfigBase(service, portalId); DataCache.SetCache(key, config); } - - return config; - } - private static string GetCacheKey(string service, int portalId) - { - return _cacheKey + "." + service + "_" + portalId; + return config; } public static void UpdateConfig(OAuthConfigBase config) @@ -104,5 +99,10 @@ public static void UpdateConfig(OAuthConfigBase config) ClearConfig(config.Service, config.PortalID); } + + private static string GetCacheKey(string service, int portalId) + { + return _cacheKey + "." + service + "_" + portalId; + } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs index b026e4d8830..bd8cbc8c6bf 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthLoginBase.cs @@ -14,8 +14,8 @@ 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; } @@ -56,6 +56,6 @@ protected override void OnLoad(EventArgs e) this.OAuthClient.AuthenticateUser(this.GetCurrentUser(), this.PortalSettings, this.IPAddress, this.AddCustomProperties, this.OnUserAuthenticated); } } - } + } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs index 3ae16d4506f..13c5c389e88 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/OAuthSettingsBase.cs @@ -13,10 +13,10 @@ public class OAuthSettingsBase : AuthenticationSettingsBase { protected PropertyEditorControl SettingsEditor; - protected virtual string AuthSystemApplicationName - { - get { return string.Empty; } - } + protected virtual string AuthSystemApplicationName + { + get { return string.Empty; } + } public override void UpdateSettings() { diff --git a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs index 8342504beff..c6e3a732b2f 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/QueryParameterComparer.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Services.Authentication.OAuth /// Comparer class used to perform the sorting of the query parameters. /// internal class QueryParameterComparer : IComparer - { + { public int Compare(QueryParameter x, QueryParameter y) { if (x.Name == y.Name) { return string.CompareOrdinal(x.Value, y.Value); } - + return string.CompareOrdinal(x.Name, y.Name); - } + } } } diff --git a/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs b/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs index 9aabc792fab..e92bfd7b3e8 100644 --- a/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs +++ b/DNN Platform/Library/Services/Authentication/OAuth/UserData.cs @@ -10,6 +10,19 @@ namespace DotNetNuke.Services.Authentication.OAuth [DataContract] public class UserData { + public string PreferredEmail + { + get + { + if (this.Emails == null) + { + return this.Email; + } + + return this.Emails.PreferredEmail; + } + } + [DataMember(Name = "id")] public string Id { get; set; } @@ -19,7 +32,7 @@ public virtual string DisplayName { return this.Name; } - + set { } } @@ -35,7 +48,7 @@ public virtual string FirstName { return (!string.IsNullOrEmpty(this.Name) && this.Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? this.Name.Substring(0, this.Name.IndexOf(" ", StringComparison.Ordinal)) : string.Empty; } - + set { this.Name = value + " " + this.LastName; } } @@ -48,7 +61,7 @@ public virtual string LastName { return (!string.IsNullOrEmpty(this.Name) && this.Name.IndexOf(" ", StringComparison.Ordinal) > 0) ? this.Name.Substring(this.Name.IndexOf(" ", StringComparison.Ordinal) + 1) : this.Name; } - + set { this.Name = this.FirstName + " " + value; } } @@ -58,19 +71,6 @@ public virtual string LastName [DataMember(Name = "name")] public virtual string Name { get; set; } - public string PreferredEmail - { - get - { - if (this.Emails == null) - { - return this.Email; - } - - return this.Emails.PreferredEmail; - } - } - public virtual string ProfileImage { get; set; } [DataMember(Name = "timezone")] diff --git a/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs b/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs index 091f6bee904..1b2966c149e 100644 --- a/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs +++ b/DNN Platform/Library/Services/Authentication/UserAuthenticatedEventArgs.cs @@ -17,9 +17,9 @@ namespace DotNetNuke.Services.Authentication /// /// ----------------------------------------------------------------------------- public class UserAuthenticatedEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// All properties Constructor. /// diff --git a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs index 297602667a6..4c8d0c4625e 100644 --- a/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs +++ b/DNN Platform/Library/Services/Authentication/UserAuthenticationInfo.cs @@ -17,14 +17,14 @@ namespace DotNetNuke.Services.Authentication /// [Serializable] public class UserAuthenticationInfo : BaseEntityInfo, IHydratable - { + { public UserAuthenticationInfo() { this.AuthenticationToken = Null.NullString; this.AuthenticationType = Null.NullString; this.UserAuthenticationID = Null.NullInteger; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and Sets the ID of the User Record in the Authentication System. @@ -51,7 +51,7 @@ public UserAuthenticationInfo() /// Gets or sets and Sets the url for the Logoff Control. /// /// ----------------------------------------------------------------------------- - public string AuthenticationToken { get; set; } + public string AuthenticationToken { get; set; } /// ----------------------------------------------------------------------------- /// @@ -65,13 +65,13 @@ public virtual int KeyID { return this.UserAuthenticationID; } - + set { this.UserAuthenticationID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a UserAuthenticationInfo from a Data Reader. diff --git a/DNN Platform/Library/Services/Cache/CachingProvider.cs b/DNN Platform/Library/Services/Cache/CachingProvider.cs index 621dd4fcb65..302ba426b07 100644 --- a/DNN Platform/Library/Services/Cache/CachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/CachingProvider.cs @@ -40,12 +40,12 @@ namespace DotNetNuke.Services.Cache /// /// public abstract class CachingProvider - { - private const string CachePrefix = "DNN_"; + { + private const string CachePrefix = "DNN_"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CachingProvider)); private static System.Web.Caching.Cache _cache; - + /// /// Gets the default cache provider. /// @@ -62,8 +62,8 @@ protected static System.Web.Caching.Cache Cache /// Gets a value indicating whether whether current caching provider disabled to expire cache. /// /// This setting shouldn't affect current server, cache should always expire in current server even this setting set to True. - protected static bool CacheExpirationDisable { get; private set; } - + protected static bool CacheExpirationDisable { get; private set; } + /// /// Cleans the cache key by remove cache key prefix. /// @@ -76,7 +76,7 @@ public static string CleanCacheKey(string CacheKey) { throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); } - + return CacheKey.Substring(CachePrefix.Length); } @@ -92,7 +92,7 @@ public static string GetCacheKey(string CacheKey) { throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); } - + return CachePrefix + CacheKey; } @@ -120,6 +120,95 @@ public virtual IDictionaryEnumerator GetEnumerator() return Cache.GetEnumerator(); } + /// + /// Gets the item. + /// + /// The cache key. + /// cache content. + public virtual object GetItem(string cacheKey) + { + return Cache[cacheKey]; + } + + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. + public virtual void Insert(string cacheKey, object itemToCache) + { + this.Insert(cacheKey, itemToCache, null as DNNCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); + } + + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. + /// The dependency. + public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency) + { + this.Insert(cacheKey, itemToCache, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); + } + + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The object. + /// The dependency. + /// The absolute expiration. + /// The sliding expiration. + public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration) + { + this.Insert(cacheKey, itemToCache, dependency, absoluteExpiration, slidingExpiration, CacheItemPriority.Default, null); + } + + /// + /// Inserts the specified cache key. + /// + /// The cache key. + /// The value. + /// The dependency. + /// The absolute expiration. + /// The sliding expiration. + /// The priority. + /// The on remove callback. + public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, + CacheItemRemovedCallback onRemoveCallback) + { + Cache.Insert(cacheKey, itemToCache, dependency == null ? null : dependency.SystemCacheDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); + } + + /// + /// Determines whether is web farm. + /// + /// + /// true if is web farm; otherwise, false. + /// + public virtual bool IsWebFarm() + { + return ServerController.GetEnabledServers().Count > 1; + } + + /// + /// Purges the cache. + /// + /// + public virtual string PurgeCache() + { + return Localization.GetString("PurgeCacheUnsupported.Text", Localization.GlobalResourceFile); + } + + /// + /// Removes the specified cache key. + /// + /// The cache key. + public virtual void Remove(string CacheKey) + { + this.RemoveInternal(CacheKey); + } + /// /// 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. @@ -141,8 +230,8 @@ internal static void EnableCacheExpiration() CacheExpirationDisable = false; DataCache.ClearHostCache(true); Logger.Warn("Enable cache expiration."); - } - + } + /// /// Clears the cache internal. /// @@ -191,14 +280,14 @@ 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) @@ -249,7 +338,7 @@ private void ClearFolderCacheInternal(int portalId, bool clearRuntime) var folderUserCachePrefix = GetCacheKey(string.Format("Folders|{0}|", portalId)); this.ClearCacheInternal(folderUserCachePrefix, clearRuntime); - PermissionProvider.ResetCacheDependency( + PermissionProvider.ResetCacheDependency( portalId, () => this.RemoveFormattedCacheKey(DataCache.FolderPermissionCacheKey, clearRuntime, portalId)); } @@ -287,14 +376,14 @@ private void ClearModuleCacheInternal(int tabId, bool clearRuntime) foreach (var moduleInfo in tabModules.Values) { cacheKey = string.Format(DataCache.SingleTabModuleCacheKey, moduleInfo.TabModuleID); - if (clearRuntime) - { - this.RemoveInternal(cacheKey); - } - else - { - this.Remove(cacheKey); - } + if (clearRuntime) + { + this.RemoveInternal(cacheKey); + } + else + { + this.Remove(cacheKey); + } } } @@ -332,18 +421,18 @@ private void ClearPortalCacheInternal(int portalId, bool cascade, bool clearRunt this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, portalLocale.Code), clearRuntime); this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, portalLocale.Code); } - + this.RemoveCacheKey(string.Format(DataCache.PortalCacheKey, portalId, Null.NullString), clearRuntime); this.RemoveFormattedCacheKey(DataCache.PortalSettingsCacheKey, clearRuntime, portalId, Null.NullString); } - + if (cascade) { foreach (KeyValuePair tabPair in TabController.Instance.GetTabsByPortal(portalId)) { this.ClearModuleCacheInternal(tabPair.Value.TabID, clearRuntime); } - + foreach (ModuleInfo moduleInfo in ModuleController.Instance.GetModules(portalId)) { this.RemoveCacheKey("GetModuleSettings" + moduleInfo.ModuleID, clearRuntime); @@ -412,7 +501,7 @@ private void RemoveFormattedCacheKey(string CacheKeyBase, bool clearRuntime, par // Call provider's remove method this.Remove(string.Format(GetCacheKey(CacheKeyBase), parameters)); } - } + } private void ReloadServicesFrameworkRoutes() { @@ -421,94 +510,5 @@ private void ReloadServicesFrameworkRoutes() // that is reliable ServicesRoutingManager.RegisterServiceRoutes(); } - - /// - /// Gets the item. - /// - /// The cache key. - /// cache content. - public virtual object GetItem(string cacheKey) - { - return Cache[cacheKey]; - } - - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. - public virtual void Insert(string cacheKey, object itemToCache) - { - this.Insert(cacheKey, itemToCache, null as DNNCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); - } - - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. - /// The dependency. - public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency) - { - this.Insert(cacheKey, itemToCache, dependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Default, null); - } - - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The object. - /// The dependency. - /// The absolute expiration. - /// The sliding expiration. - public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration) - { - this.Insert(cacheKey, itemToCache, dependency, absoluteExpiration, slidingExpiration, CacheItemPriority.Default, null); - } - - /// - /// Inserts the specified cache key. - /// - /// The cache key. - /// The value. - /// The dependency. - /// The absolute expiration. - /// The sliding expiration. - /// The priority. - /// The on remove callback. - public virtual void Insert(string cacheKey, object itemToCache, DNNCacheDependency dependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, - CacheItemRemovedCallback onRemoveCallback) - { - Cache.Insert(cacheKey, itemToCache, dependency == null ? null : dependency.SystemCacheDependency, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); - } - - /// - /// Determines whether is web farm. - /// - /// - /// true if is web farm; otherwise, false. - /// - public virtual bool IsWebFarm() - { - return ServerController.GetEnabledServers().Count > 1; - } - - /// - /// Purges the cache. - /// - /// - public virtual string PurgeCache() - { - return Localization.GetString("PurgeCacheUnsupported.Text", Localization.GlobalResourceFile); - } - - /// - /// Removes the specified cache key. - /// - /// The cache key. - public virtual void Remove(string CacheKey) - { - this.RemoveInternal(CacheKey); - } } } diff --git a/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs b/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs index 4b440e0d94a..11589d5fca1 100644 --- a/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs +++ b/DNN Platform/Library/Services/Cache/DNNCacheDependency.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Services.Cache /// The CacheDependency class monitors the dependency relationships so that when any of them changes, the cached item will be automatically removed. /// public class DNNCacheDependency : IDisposable - { + { private readonly DateTime _utcStart = DateTime.MaxValue; private DNNCacheDependency _cacheDependency; private string[] _cacheKeys; private string[] _fileNames; - private CacheDependency _systemCacheDependency; - + private CacheDependency _systemCacheDependency; + /// /// Initializes a new instance of the class. /// @@ -128,8 +128,8 @@ public DNNCacheDependency(string[] filenames, string[] cachekeys, DNNCacheDepend this._fileNames = filenames; this._cacheKeys = cachekeys; this._cacheDependency = dependency; - } - + } + /// /// Gets the cache keys. /// @@ -206,7 +206,7 @@ public CacheDependency SystemCacheDependency this._systemCacheDependency = new CacheDependency(this._fileNames, this._cacheKeys, this._cacheDependency.SystemCacheDependency, this._utcStart); } } - + return this._systemCacheDependency; } } @@ -220,8 +220,8 @@ public DateTime UtcLastModified { return this.SystemCacheDependency.UtcLastModified; } - } - + } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// @@ -230,7 +230,7 @@ public void Dispose() this.Dispose(true); GC.SuppressFinalize(this); } - + // Method that does the actual disposal of resources protected virtual void Dispose(bool disposing) { @@ -240,17 +240,17 @@ protected virtual void Dispose(bool disposing) { this._cacheDependency.Dispose(disposing); } - + if (this._systemCacheDependency != null) { this._systemCacheDependency.Dispose(); } - + this._fileNames = null; this._cacheKeys = null; this._cacheDependency = null; this._systemCacheDependency = null; } - } + } } } diff --git a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs index 252e42a862f..acfd8fdc642 100644 --- a/DNN Platform/Library/Services/Cache/FBCachingProvider.cs +++ b/DNN Platform/Library/Services/Cache/FBCachingProvider.cs @@ -16,9 +16,9 @@ namespace DotNetNuke.Services.Cache public class FBCachingProvider : CachingProvider { internal const string CacheFileExtension = ".resources"; - internal static string CachingDirectory = "Cache\\"; + 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) { @@ -31,10 +31,10 @@ public override void Insert(string cacheKey, object itemToCache, DNNCacheDepende // get hashed file name var f = new string[1]; f[0] = GetFileName(cacheKey); - + // create a cache file for item CreateCacheFile(f[0], cacheKey); - + // create a cache dependency on the cache file d = new DNNCacheDependency(f, null, dependency); } @@ -50,7 +50,7 @@ public override bool IsWebFarm() { _IsWebFarm = bool.Parse(Config.GetSetting("IsWebFarm")); } - + return _IsWebFarm; } @@ -69,12 +69,12 @@ public override void Remove(string Key) { // get hashed filename string f = GetFileName(Key); - + // delete cache file - this synchronizes the cache across servers in the farm DeleteCacheFile(f); } - } - + } + private static string ByteArrayToString(byte[] arrInput) { int i; @@ -83,7 +83,7 @@ private static string ByteArrayToString(byte[] arrInput) { sOutput.Append(arrInput[i].ToString("X2")); } - + return sOutput.ToString(); } @@ -98,10 +98,10 @@ private static void CreateCacheFile(string FileName, string CacheKey) { // create the cache file s = File.CreateText(FileName); - + // write the CacheKey to the file to provide a documented link between cache item and cache file s.Write(CacheKey); - + // close the stream } } @@ -164,13 +164,13 @@ private string PurgeCacheFiles(string Folder) // get last write time for file DateTime dtLastWrite; dtLastWrite = File.GetLastWriteTime(f[i]); - + // if the cache file is more than 2 hours old ( no point in checking most recent cache files ) if (dtLastWrite < DateTime.Now.Subtract(new TimeSpan(2, 0, 0))) { // get cachekey string strCacheKey = Path.GetFileNameWithoutExtension(f[i]); - + // if the cache key does not exist in memory if (DataCache.GetCache(strCacheKey) == null) { @@ -193,6 +193,6 @@ private string PurgeCacheFiles(string Folder) // return a summary message for the job return string.Format("Cache Synchronization Files Processed: " + f.Length + ", Purged: " + PurgedFiles + ", Errors: " + PurgeErrors); - } + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs index 1c8584f09e6..aab2174f565 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapability.cs @@ -16,17 +16,17 @@ namespace DotNetNuke.Services.ClientCapability /// public class ClientCapability : IClientCapability { - private IDictionary _capabilities; - - /// + private IDictionary _capabilities; + + /// /// Initializes a new instance of the class. /// Default Constructor. /// public ClientCapability() { this._capabilities = new Dictionary(); - } - + } + /// /// Gets or sets unique ID of the client making request. /// @@ -86,7 +86,7 @@ public IDictionary Capabilities { return this._capabilities; } - + set { this._capabilities = value; @@ -119,6 +119,6 @@ public virtual string this[string name] { throw new NotImplementedException(string.Empty); } - } + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs index 5cb0c4d78a9..dd8cc0f2a6e 100644 --- a/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs +++ b/DNN Platform/Library/Services/ClientCapability/ClientCapabilityProvider.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Services.ClientCapability using DotNetNuke.ComponentModel; 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. /// @@ -28,22 +28,22 @@ public virtual bool SupportsTabletDetection { return true; } - } - + } + public static ClientCapabilityProvider Instance() { return ComponentFactory.GetComponent(); } - + /// /// Returns ClientCapability based on userAgent. - /// + /// /// public abstract IClientCapability GetClientCapability(string userAgent); /// /// Returns ClientCapability based on ClientCapabilityId. - /// + /// /// public abstract IClientCapability GetClientCapabilityById(string clientId); @@ -62,11 +62,11 @@ public static ClientCapabilityProvider Instance() /// /// List of IClientCapability present. /// - public abstract IQueryable GetAllClientCapabilities(); - + public abstract IQueryable GetAllClientCapabilities(); + /// /// Returns ClientCapability based on HttpRequest. - /// + /// /// public virtual IClientCapability GetClientCapability(HttpRequest httpRequest) { @@ -74,6 +74,6 @@ public virtual IClientCapability GetClientCapability(HttpRequest httpRequest) clientCapability.FacebookRequest = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); return clientCapability; - } + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs index a8826faf5e2..6d75a0f3285 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequest.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Services.ClientCapability /// For more details visit http://developers.facebook.com/docs/authentication/signed_request/. /// public class FacebookRequest - { + { /// /// Gets or sets mechanism used to sign the request. /// @@ -99,11 +99,11 @@ public class FacebookRequest /// /// Gets or sets a value indicating whether is this a valid FaceBook Request. Check this value prior to accessing any other property. /// - public bool IsValid { get; set; } - + public bool IsValid { get; set; } + public bool IsValidSignature(string secretKey) { return FacebookRequestController.IsValidSignature(this.RawSignedRequest, secretKey); - } + } } } diff --git a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs index 943f0c1de1f..f3a4a43d9cf 100644 --- a/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs +++ b/DNN Platform/Library/Services/ClientCapability/FacebookRequestController.cs @@ -16,25 +16,25 @@ namespace DotNetNuke.Services.ClientCapability 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; } } @@ -46,46 +46,46 @@ internal struct User 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; } - + public long UserID { get; set; } - + public long ProfileId { get; set; } - + public string RawSignedRequest { get; set; } - + public bool IsValid { get; set; } public static FacebookRequest GetFacebookDetailsFromRequest(HttpRequest Request) { - if (Request == null) - { - return null; - } - - if (Request.RequestType != "POST") - { - return null; - } - + if (Request == null) + { + return null; + } + + if (Request.RequestType != "POST") + { + return null; + } + string rawSignedRequest = Request[SignedRequestParameter]; return GetFacebookDetailsFromRequest(rawSignedRequest); } public static FacebookRequest GetFacebookDetailsFromRequest(string rawSignedRequest) { - if (string.IsNullOrEmpty(rawSignedRequest)) - { - return null; - } - + if (string.IsNullOrEmpty(rawSignedRequest)) + { + return null; + } + try { var facebookRequest = new FacebookRequest(); @@ -145,10 +145,10 @@ public static bool IsValidSignature(string rawSignedRequest, string secretKey) var encoding = new UTF8Encoding(); var hmac = SignWithHmac(encoding.GetBytes(payload), encoding.GetBytes(secretKey)); var hmacBase64 = Base64UrlDecode(Convert.ToBase64String(hmac)); - if (hmacBase64 == expectedSignature) - { - return true; - } + if (hmacBase64 == expectedSignature) + { + return true; + } } } @@ -162,11 +162,11 @@ public static bool IsValidSignature(string rawSignedRequest, string secretKey) /// The base 64 string. private static string Base64UrlDecode(string encodedValue) { - if (string.IsNullOrEmpty(encodedValue)) - { - return null; - } - + if (string.IsNullOrEmpty(encodedValue)) + { + return null; + } + encodedValue = encodedValue.Replace('+', '-').Replace('/', '_').Replace("=", string.Empty).Trim(); return encodedValue; } @@ -184,7 +184,7 @@ private static byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody) return hmacAlgorithm.Hash; } } - + /// /// method for converting a System.DateTime value to a UNIX Timestamp. /// @@ -202,21 +202,21 @@ private static DateTime ConvertToTimestamp(long value) internal struct FaceBookData { public User user { get; set; } - + public string algorithm { get; set; } - + public long issued_at { get; set; } - + public string user_id { get; set; } - + public string oauth_token { get; set; } - + public long expires { get; set; } - + public string app_data { get; set; } - + public Page page { get; set; } - + public long profile_id { get; set; } } } diff --git a/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs b/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs index 53e758c2942..62e12d750cc 100644 --- a/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs +++ b/DNN Platform/Library/Services/ClientCapability/IClientCapabilityProvider.cs @@ -12,13 +12,13 @@ public interface IClientCapabilityProvider { /// /// Returns ClientCapability based on userAgent. - /// + /// /// IClientCapability GetClientCapability(string userAgent); /// /// Returns ClientCapability based on ClientCapabilityId. - /// + /// /// IClientCapability GetClientCapabilityById(string clientId); @@ -41,7 +41,7 @@ public interface IClientCapabilityProvider /// /// Returns ClientCapability based on HttpRequest. - /// + /// /// IClientCapability GetClientCapability(HttpRequest httpRequest); } diff --git a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs index 1aed798e628..e91c30a805b 100644 --- a/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs +++ b/DNN Platform/Library/Services/ClientDependency/PurgeClientDependencyFiles.cs @@ -24,7 +24,7 @@ public override void DoWork() { File.Delete(filePath); } - + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED this.ScheduleHistoryItem.AddLogNote("Purging client dependency files task succeeded"); } diff --git a/DNN Platform/Library/Services/Connections/ConnectionsController.cs b/DNN Platform/Library/Services/Connections/ConnectionsController.cs index 223a088cb5c..0a4543f6f99 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsController.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsController.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Services.Connections using DotNetNuke.Framework; public class ConnectionsController : ServiceLocator, IConnectionsController - { + { public IList GetConnections(int portalId) { var connectors = ConnectionsManager.Instance.GetConnectors().Where(c => c.HasConfig(portalId)).ToList(); @@ -22,7 +22,7 @@ public IList GetConnections(int portalId) { allConnectors.AddRange(con.GetConnectors(portalId)); } - + return allConnectors; } @@ -37,10 +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 40293627678..f931d53cc50 100644 --- a/DNN Platform/Library/Services/Connections/ConnectionsManager.cs +++ b/DNN Platform/Library/Services/Connections/ConnectionsManager.cs @@ -15,16 +15,11 @@ namespace DotNetNuke.Services.Connections using DotNetNuke.Services.Installer.Packages; 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 IDictionary _processors; + public void RegisterConnections() { if (_processors == null) @@ -42,8 +37,13 @@ public void RegisterConnections() public IList GetConnectors() { return _processors.Values.Where(x => this.IsPackageInstalled(x.GetType().Assembly)).ToList(); - } - + } + + protected override Func GetFactory() + { + return () => new ConnectionsManager(); + } + private void LoadProcessors() { _processors = new Dictionary(); @@ -77,9 +77,9 @@ private bool IsValidFilter(Type t) private bool IsPackageInstalled(Assembly assembly) { - return PackageController.Instance.GetExtensionPackages( + return PackageController.Instance.GetExtensionPackages( -1, info => info.Name == assembly.GetName().Name && info.IsValid).Count > 0; - } + } } } diff --git a/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs b/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs index 547b9bba34a..eb65f0800aa 100644 --- a/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs +++ b/DNN Platform/Library/Services/Connections/ConnectorArgumentException.cs @@ -12,12 +12,12 @@ public ConnectorArgumentException() { } - public ConnectorArgumentException(string message) + public ConnectorArgumentException(string message) : base(message) { } - public ConnectorArgumentException(string message, Exception innerException) + public ConnectorArgumentException(string message, Exception innerException) : base(message, innerException) { } diff --git a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs index a65ef91e137..cf4a845ff9a 100644 --- a/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs +++ b/DNN Platform/Library/Services/Connections/DynamicJsonConverter.cs @@ -18,15 +18,15 @@ 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) - { - throw new ArgumentNullException("dictionary"); - } - + if (dictionary == null) + { + throw new ArgumentNullException("dictionary"); + } + return type == typeof(object) ? new DynamicJsonObject(dictionary) : null; } @@ -34,18 +34,18 @@ public override IDictionary Serialize(object obj, JavaScriptSeri { throw new NotImplementedException(); } - + private sealed class DynamicJsonObject : DynamicObject { private readonly IDictionary _dictionary; public DynamicJsonObject(IDictionary dictionary) { - if (dictionary == null) - { - throw new ArgumentNullException("dictionary"); - } - + if (dictionary == null) + { + throw new ArgumentNullException("dictionary"); + } + this._dictionary = dictionary; } @@ -87,6 +87,25 @@ public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out ob return base.TryGetIndex(binder, indexes, out result); } + private static object WrapResultObject(object result) + { + var dictionary = result as IDictionary; + if (dictionary != null) + { + return new DynamicJsonObject(dictionary); + } + + var arrayList = result as ArrayList; + if (arrayList != null && arrayList.Count > 0) + { + return arrayList[0] is IDictionary + ? new List(arrayList.Cast>().Select(x => new DynamicJsonObject(x))) + : new List(arrayList.Cast()); + } + + return result; + } + private void ToString(StringBuilder sb) { var firstInDictionary = true; @@ -118,7 +137,7 @@ private void ToString(StringBuilder sb) { sb.Append(","); } - + firstInArray = false; if (arrayValue is IDictionary) @@ -134,7 +153,7 @@ private void ToString(StringBuilder sb) sb.AppendFormat("{0}", arrayValue); } } - + sb.Append("]"); } else @@ -142,28 +161,9 @@ private void ToString(StringBuilder sb) sb.AppendFormat("{0}:{1}", name, value); } } - - sb.Append("}"); - } - - private static object WrapResultObject(object result) - { - var dictionary = result as IDictionary; - if (dictionary != null) - { - return new DynamicJsonObject(dictionary); - } - - var arrayList = result as ArrayList; - if (arrayList != null && arrayList.Count > 0) - { - return arrayList[0] is IDictionary - ? new List(arrayList.Cast>().Select(x => new DynamicJsonObject(x))) - : new List(arrayList.Cast()); - } - return result; + sb.Append("}"); } - } + } } } diff --git a/DNN Platform/Library/Services/Connections/IConnectionsController.cs b/DNN Platform/Library/Services/Connections/IConnectionsController.cs index ae0b04d75be..86234850d87 100644 --- a/DNN Platform/Library/Services/Connections/IConnectionsController.cs +++ b/DNN Platform/Library/Services/Connections/IConnectionsController.cs @@ -11,7 +11,7 @@ public interface IConnectionsController { /// /// Get Connection Settings for a Site. - /// + /// /// IList GetConnections(int portalId); diff --git a/DNN Platform/Library/Services/Connections/IConnector.cs b/DNN Platform/Library/Services/Connections/IConnector.cs index a412b69191b..4e0d80a8bf4 100644 --- a/DNN Platform/Library/Services/Connections/IConnector.cs +++ b/DNN Platform/Library/Services/Connections/IConnector.cs @@ -8,11 +8,6 @@ namespace DotNetNuke.Services.Connections public interface IConnector { - /// - /// Gets or sets id of the connector. It is required if SupportsMultiple is true. - /// - string Id { get; set; } - /// /// Gets unique name of the connector. It is used to distinguish between different types of connectors. /// @@ -28,11 +23,6 @@ public interface IConnector /// bool SupportsMultiple { get; } - /// - /// Gets or sets display name of the connector. - /// - string DisplayName { get; set; } - /// /// Gets icon url of the connector. /// @@ -48,6 +38,16 @@ public interface IConnector /// bool IsEngageConnector { get; } + /// + /// Gets or sets id of the connector. It is required if SupportsMultiple is true. + /// + string Id { get; set; } + + /// + /// Gets or sets display name of the connector. + /// + string DisplayName { get; set; } + /// /// Checks if the connector has been configured or not. /// diff --git a/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs index e94d73241fe..8f32c23d3a3 100644 --- a/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/CoreCryptographyProvider.cs @@ -56,7 +56,7 @@ public override string EncryptParameter(string message, string passphrase) { value = message; } - + return value; } @@ -91,7 +91,7 @@ public override string DecryptParameter(string message, string passphrase) // decrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) - using (var objCryptoStream = new CryptoStream( + using (var objCryptoStream = new CryptoStream( objMemoryStream, objDes.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write)) { @@ -108,7 +108,7 @@ public override string DecryptParameter(string message, string passphrase) strValue = string.Empty; } } - + return strValue; } @@ -176,7 +176,7 @@ public override string DecryptString(string message, string passphrase) Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, }; - + byte[] dataToDecrypt = Convert.FromBase64String(message); try { diff --git a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs index 26911bbf067..c13de101ba1 100644 --- a/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/CryptographyProvider.cs @@ -7,12 +7,12 @@ namespace DotNetNuke.Services.Cryptography using DotNetNuke.ComponentModel; public abstract class CryptographyProvider : ICryptographyProvider - { + { public static CryptographyProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + /// /// simple method that uses basic encryption to safely encode parameters. /// @@ -43,6 +43,6 @@ public static CryptographyProvider Instance() /// the text to be decrypted. /// the key to perform the decryption. /// decrypted string. - public abstract string DecryptString(string message, string passphrase); + public abstract string DecryptString(string message, string passphrase); } } diff --git a/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs b/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs index aed4a069d55..59d4ea260d3 100644 --- a/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs +++ b/DNN Platform/Library/Services/Cryptography/FipsCompilanceCryptographyProvider.cs @@ -58,7 +58,7 @@ public override string EncryptParameter(string message, string passphrase) { value = message; } - + return value; } @@ -94,7 +94,7 @@ public override string DecryptParameter(string message, string passphrase) // decrypt using (var objDes = new DESCryptoServiceProvider()) using (var objMemoryStream = new MemoryStream()) - using (var objCryptoStream = new CryptoStream( + using (var objCryptoStream = new CryptoStream( objMemoryStream, objDes.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write)) { @@ -111,7 +111,7 @@ public override string DecryptParameter(string message, string passphrase) strValue = string.Empty; } } - + return strValue; } @@ -179,7 +179,7 @@ public override string DecryptString(string message, string passphrase) Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, }; - + byte[] dataToDecrypt = Convert.FromBase64String(message); try { diff --git a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs index 0348de3d6e0..d8e25de308f 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/EventQueueConfiguration.cs @@ -15,16 +15,16 @@ namespace DotNetNuke.Services.EventQueue.Config [Serializable] internal class EventQueueConfiguration - { + { internal EventQueueConfiguration() { this.PublishedEvents = new Dictionary(); this.EventQueueSubscribers = new Dictionary(); - } - + } + internal Dictionary EventQueueSubscribers { get; set; } - internal Dictionary PublishedEvents { get; set; } + internal Dictionary PublishedEvents { get; set; } public static void RegisterEventSubscription(EventQueueConfiguration config, string eventname, SubscriberInfo subscriber) { @@ -37,7 +37,7 @@ public static void RegisterEventSubscription(EventQueueConfiguration config, str config.EventQueueSubscribers.Add(subscriber.ID, subscriber); } } - + internal static EventQueueConfiguration GetConfig() { var config = (EventQueueConfiguration)DataCache.GetCache("EventQueueConfig"); @@ -47,10 +47,10 @@ internal static EventQueueConfiguration GetConfig() 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)); } @@ -66,7 +66,7 @@ internal static EventQueueConfiguration GetConfig() SaveConfig(config, filePath); } } - + return config; } @@ -75,11 +75,11 @@ 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) { if (!string.IsNullOrEmpty(configXml)) @@ -93,7 +93,7 @@ private void Deserialize(string configXml) oPublishedEvent.Subscribers = xmlItem.SelectSingleNode("Subscribers").InnerText; this.PublishedEvents.Add(oPublishedEvent.EventName, oPublishedEvent); } - + foreach (XmlElement xmlItem in xmlDoc.SelectNodes("/EventQueueConfig/EventQueueSubscribers/Subscriber")) { var oSubscriberInfo = new SubscriberInfo(); @@ -131,7 +131,7 @@ private string Serialize() writer.WriteEndElement(); } - + writer.WriteEndElement(); writer.WriteStartElement("EventQueueSubscribers"); @@ -146,7 +146,7 @@ private string Serialize() writer.WriteElementString("PrivateKey", this.EventQueueSubscribers[key].PrivateKey); writer.WriteEndElement(); } - + writer.WriteEndElement(); // Close EventQueueConfig @@ -155,6 +155,6 @@ private string Serialize() writer.Close(); return sb.ToString(); } - } + } } } diff --git a/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs b/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs index 11e569ef1e8..10c25ed61e4 100644 --- a/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs +++ b/DNN Platform/Library/Services/EventQueue/Config/SubscriberInfo.cs @@ -20,7 +20,7 @@ public SubscriberInfo() this.PrivateKey = oPortalSecurity.CreateKey(16); } - public SubscriberInfo(string subscriberName) + public SubscriberInfo(string subscriberName) : this() { this.Name = subscriberName; diff --git a/DNN Platform/Library/Services/EventQueue/EventMessage.cs b/DNN Platform/Library/Services/EventQueue/EventMessage.cs index 838219cb443..2d1ec3a0a32 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessage.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessage.cs @@ -20,7 +20,7 @@ public enum MessagePriority [Serializable] public class EventMessage - { + { private NameValueCollection _attributes; private string _authorizedRoles = Null.NullString; private string _body = Null.NullString; @@ -32,20 +32,20 @@ public class EventMessage private string _processorType = Null.NullString; private string _sender = Null.NullString; private DateTime _sentDate; - private string _subscribers = Null.NullString; - + private string _subscribers = Null.NullString; + public EventMessage() { this._attributes = new NameValueCollection(); - } - + } + public int EventMessageID { get { return this._eventMessageID; } - + set { this._eventMessageID = value; @@ -65,7 +65,7 @@ public string ProcessorType return this._processorType; } } - + set { this._processorType = value; @@ -85,7 +85,7 @@ public string ProcessorCommand return this._processorCommand; } } - + set { this._processorCommand = value; @@ -105,7 +105,7 @@ public string Body return this._body; } } - + set { this._body = value; @@ -125,7 +125,7 @@ public string Sender return this._sender; } } - + set { this._sender = value; @@ -145,7 +145,7 @@ public string Subscribers return this._subscribers; } } - + set { this._subscribers = value; @@ -165,7 +165,7 @@ public string AuthorizedRoles return this._authorizedRoles; } } - + set { this._authorizedRoles = value; @@ -178,7 +178,7 @@ public MessagePriority Priority { return this._priority; } - + set { this._priority = value; @@ -198,7 +198,7 @@ public string ExceptionMessage return this._exceptionMessage; } } - + set { this._exceptionMessage = value; @@ -211,7 +211,7 @@ public DateTime SentDate { return this._sentDate.ToLocalTime(); } - + set { this._sentDate = value.ToUniversalTime(); @@ -224,7 +224,7 @@ public DateTime ExpirationDate { return this._expirationDate.ToLocalTime(); } - + set { this._expirationDate = value.ToUniversalTime(); @@ -237,13 +237,13 @@ public NameValueCollection Attributes { return this._attributes; } - + set { this._attributes = value; } - } - + } + public void DeserializeAttributes(string configXml) { string attName = Null.NullString; @@ -276,7 +276,7 @@ public void DeserializeAttributes(string configXml) // Add attribute to the collection this._attributes.Add(attName, attValue); - } + } while (reader.ReadToNextSibling("Attribute")); } } @@ -325,6 +325,6 @@ public string SerializeAttributes() return sb.ToString(); } - } + } } } diff --git a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs index 67ebc52cbf8..4f707de7163 100644 --- a/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs +++ b/DNN Platform/Library/Services/EventQueue/EventMessageCollection.cs @@ -13,7 +13,7 @@ public virtual EventMessage this[int index] { return (EventMessage)this.List[index]; } - + set { this.List[index] = value; diff --git a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs index af907dd412b..c0d8aa57eca 100644 --- a/DNN Platform/Library/Services/EventQueue/EventQueueController.cs +++ b/DNN Platform/Library/Services/EventQueue/EventQueueController.cs @@ -42,7 +42,7 @@ namespace DotNetNuke.Services.EventQueue /// /// public class EventQueueController - { + { /// /// Gets the messages. /// @@ -63,94 +63,6 @@ public static EventMessageCollection GetMessages(string eventName, string subscr { return FillMessageCollection(DataProvider.Instance().GetEventMessagesBySubscriber(eventName, subscriberId)); } - - private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataReader) - { - EventMessage message; - - // read datareader - bool canContinue = true; - if (CheckForOpenDataReader) - { - canContinue = false; - if (dr.Read()) - { - canContinue = true; - } - } - - if (canContinue) - { - message = new EventMessage(); - message.EventMessageID = Convert.ToInt32(Null.SetNull(dr["EventMessageID"], message.EventMessageID)); - message.Priority = (MessagePriority)Enum.Parse(typeof(MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority))); - message.ProcessorType = Convert.ToString(Null.SetNull(dr["ProcessorType"], message.ProcessorType)); - message.ProcessorCommand = Convert.ToString(Null.SetNull(dr["ProcessorCommand"], message.ProcessorCommand)); - message.Body = Convert.ToString(Null.SetNull(dr["Body"], message.Body)); - message.Sender = Convert.ToString(Null.SetNull(dr["Sender"], message.Sender)); - message.Subscribers = Convert.ToString(Null.SetNull(dr["Subscriber"], message.Subscribers)); - message.AuthorizedRoles = Convert.ToString(Null.SetNull(dr["AuthorizedRoles"], message.AuthorizedRoles)); - message.ExceptionMessage = Convert.ToString(Null.SetNull(dr["ExceptionMessage"], message.ExceptionMessage)); - message.SentDate = Convert.ToDateTime(Null.SetNull(dr["SentDate"], message.SentDate)); - message.ExpirationDate = Convert.ToDateTime(Null.SetNull(dr["ExpirationDate"], message.ExpirationDate)); - - // Deserialize Attributes - string xmlAttributes = Null.NullString; - xmlAttributes = Convert.ToString(Null.SetNull(dr["Attributes"], xmlAttributes)); - message.DeserializeAttributes(xmlAttributes); - } - else - { - message = null; - } - - return message; - } - - private static EventMessageCollection FillMessageCollection(IDataReader dr) - { - var arr = new EventMessageCollection(); - try - { - EventMessage obj; - while (dr.Read()) - { - // fill business object - obj = FillMessage(dr, false); - - // add to collection - arr.Add(obj); - } - } - catch (Exception exc) - { - Exceptions.Exceptions.LogException(exc); - } - finally - { - // close datareader - CBO.CloseDataReader(dr, true); - } - - return arr; - } - - private static string[] GetSubscribers(string eventName) - { - // Get the subscribers to this event - string[] subscribers = null; - PublishedEvent publishedEvent = null; - if (EventQueueConfiguration.GetConfig().PublishedEvents.TryGetValue(eventName, out publishedEvent)) - { - subscribers = publishedEvent.Subscribers.Split(";".ToCharArray()); - } - else - { - subscribers = new string[] { }; - } - - return subscribers; - } /// /// Processes the messages. @@ -210,12 +122,12 @@ public static bool ProcessMessages(EventMessageCollection eventMessages) { log.AddProperty(key, message.Attributes[key]); } - + if (!string.IsNullOrEmpty(message.ExceptionMessage)) { log.AddProperty("ExceptionMessage", message.ExceptionMessage); } - + LogController.Instance.AddLog(log); if (message.ExpirationDate < DateTime.Now) { @@ -224,7 +136,7 @@ public static bool ProcessMessages(EventMessageCollection eventMessages) } } } - + return success; } @@ -252,7 +164,7 @@ public static bool SendMessage(EventMessage message, string eventName) { for (int indx = 0; indx <= subscribers.Length - 1; indx++) { - intMessageID = DataProvider.Instance().AddEventMessage( + intMessageID = DataProvider.Instance().AddEventMessage( eventName, (int)message.Priority, message.ProcessorType, @@ -272,14 +184,102 @@ public static bool SendMessage(EventMessage message, string eventName) Exceptions.Exceptions.LogException(ex); success = Null.NullBoolean; } - + return success; - } - + } + [Obsolete("This method is obsolete. Use Sendmessage(message, eventName) instead. Scheduled removal in v10.0.0.")] public bool SendMessage(EventMessage message, string eventName, bool encryptMessage) { return SendMessage(message, eventName); - } + } + + private static EventMessage FillMessage(IDataReader dr, bool CheckForOpenDataReader) + { + EventMessage message; + + // read datareader + bool canContinue = true; + if (CheckForOpenDataReader) + { + canContinue = false; + if (dr.Read()) + { + canContinue = true; + } + } + + if (canContinue) + { + message = new EventMessage(); + message.EventMessageID = Convert.ToInt32(Null.SetNull(dr["EventMessageID"], message.EventMessageID)); + message.Priority = (MessagePriority)Enum.Parse(typeof(MessagePriority), Convert.ToString(Null.SetNull(dr["Priority"], message.Priority))); + message.ProcessorType = Convert.ToString(Null.SetNull(dr["ProcessorType"], message.ProcessorType)); + message.ProcessorCommand = Convert.ToString(Null.SetNull(dr["ProcessorCommand"], message.ProcessorCommand)); + message.Body = Convert.ToString(Null.SetNull(dr["Body"], message.Body)); + message.Sender = Convert.ToString(Null.SetNull(dr["Sender"], message.Sender)); + message.Subscribers = Convert.ToString(Null.SetNull(dr["Subscriber"], message.Subscribers)); + message.AuthorizedRoles = Convert.ToString(Null.SetNull(dr["AuthorizedRoles"], message.AuthorizedRoles)); + message.ExceptionMessage = Convert.ToString(Null.SetNull(dr["ExceptionMessage"], message.ExceptionMessage)); + message.SentDate = Convert.ToDateTime(Null.SetNull(dr["SentDate"], message.SentDate)); + message.ExpirationDate = Convert.ToDateTime(Null.SetNull(dr["ExpirationDate"], message.ExpirationDate)); + + // Deserialize Attributes + string xmlAttributes = Null.NullString; + xmlAttributes = Convert.ToString(Null.SetNull(dr["Attributes"], xmlAttributes)); + message.DeserializeAttributes(xmlAttributes); + } + else + { + message = null; + } + + return message; + } + + private static EventMessageCollection FillMessageCollection(IDataReader dr) + { + var arr = new EventMessageCollection(); + try + { + EventMessage obj; + while (dr.Read()) + { + // fill business object + obj = FillMessage(dr, false); + + // add to collection + arr.Add(obj); + } + } + catch (Exception exc) + { + Exceptions.Exceptions.LogException(exc); + } + finally + { + // close datareader + CBO.CloseDataReader(dr, true); + } + + return arr; + } + + private static string[] GetSubscribers(string eventName) + { + // Get the subscribers to this event + string[] subscribers = null; + PublishedEvent publishedEvent = null; + if (EventQueueConfiguration.GetConfig().PublishedEvents.TryGetValue(eventName, out publishedEvent)) + { + subscribers = publishedEvent.Subscribers.Split(";".ToCharArray()); + } + else + { + subscribers = new string[] { }; + } + + return subscribers; + } } } diff --git a/DNN Platform/Library/Services/Exceptions/BasePortalException.cs b/DNN Platform/Library/Services/Exceptions/BasePortalException.cs index 5cb960f4342..ea112db2f2b 100644 --- a/DNN Platform/Library/Services/Exceptions/BasePortalException.cs +++ b/DNN Platform/Library/Services/Exceptions/BasePortalException.cs @@ -33,20 +33,20 @@ public BasePortalException() } // constructor with exception message - public BasePortalException(string message) + public BasePortalException(string message) : base(message) { this.InitializePrivateVariables(); } // constructor with message and inner exception - public BasePortalException(string message, Exception inner) + public BasePortalException(string message, Exception inner) : base(message, inner) { this.InitializePrivateVariables(); } - protected BasePortalException(SerializationInfo info, StreamingContext context) + protected BasePortalException(SerializationInfo info, StreamingContext context) : base(info, context) { this.InitializePrivateVariables(); @@ -73,6 +73,15 @@ protected BasePortalException(SerializationInfo info, StreamingContext context) this.m_Source = info.GetString("m_Source"); } + [XmlIgnore] + public new MethodBase TargetSite + { + get + { + return base.TargetSite; + } + } + public string AssemblyVersion { get; private set; } public int PortalID { get; private set; } @@ -107,15 +116,6 @@ protected BasePortalException(SerializationInfo info, StreamingContext context) public string Method { get; private set; } - [XmlIgnore] - public new MethodBase TargetSite - { - get - { - return base.TargetSite; - } - } - private void InitializePrivateVariables() { // Try and get the Portal settings from context @@ -129,7 +129,7 @@ private void InitializePrivateVariables() { innerException = innerException.InnerException; } - + var exceptionInfo = Exceptions.GetExceptionInfo(innerException); this.AssemblyVersion = DotNetNukeContext.Current.Application.Version.ToString(3); @@ -169,7 +169,7 @@ private void InitializePrivateVariables() { this.AbsoluteURLReferrer = HttpUtility.HtmlEncode(context.Request.UrlReferrer.AbsoluteUri); } - + this.UserAgent = HttpUtility.HtmlEncode(context.Request.UserAgent ?? string.Empty); } else @@ -179,7 +179,7 @@ private void InitializePrivateVariables() this.AbsoluteURLReferrer = string.Empty; this.UserAgent = string.Empty; } - + try { ProviderConfiguration objProviderConfiguration = ProviderConfiguration.GetProviderConfiguration("data"); @@ -220,7 +220,7 @@ private void InitializePrivateVariables() this.m_StackTrace = string.Empty; } - + try { this.m_Message = this.Message; @@ -231,7 +231,7 @@ private void InitializePrivateVariables() this.m_Message = string.Empty; } - + try { this.m_Source = this.Source; diff --git a/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs b/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs index 7525066b789..231575ac410 100644 --- a/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs +++ b/DNN Platform/Library/Services/Exceptions/ErrorContainer.cs @@ -58,7 +58,7 @@ private ModuleMessage FormatException(string strError, Exception exc) { m = UI.Skins.Skin.GetModuleMessageControl(Localization.GetString("ErrorOccurred"), strError, ModuleMessage.ModuleMessageType.RedError); } - + return m; } } diff --git a/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs b/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs index 8fecf5615a6..31dda3b91fb 100644 --- a/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs +++ b/DNN Platform/Library/Services/Exceptions/ExceptionExtensions.cs @@ -36,15 +36,15 @@ public static string Hash(this Exception exc) private static void AddException(StringBuilder sb, Exception ex) { - if (!string.IsNullOrEmpty(ex.Message)) - { - sb.AppendLine(ex.Message); - } - - if (!string.IsNullOrEmpty(ex.StackTrace)) - { - sb.AppendLine(ex.StackTrace); - } + if (!string.IsNullOrEmpty(ex.Message)) + { + sb.AppendLine(ex.Message); + } + + if (!string.IsNullOrEmpty(ex.StackTrace)) + { + sb.AppendLine(ex.StackTrace); + } } } } diff --git a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs index d6abfedf59c..86ceabc0816 100644 --- a/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs +++ b/DNN Platform/Library/Services/Exceptions/ExceptionInfo.cs @@ -11,10 +11,10 @@ namespace DotNetNuke.Services.Exceptions [Serializable] public class ExceptionInfo - { - public ExceptionInfo() - { - } + { + public ExceptionInfo() + { + } public ExceptionInfo(Exception e) { @@ -26,10 +26,10 @@ public ExceptionInfo(Exception e) this.InnerMessage = e.InnerException.Message; this.InnerStackTrace = e.InnerException.StackTrace; } - + this.ExceptionHash = e.Hash(); - } - + } + public string AssemblyVersion { get; set; } public int PortalId { get; set; } @@ -62,8 +62,8 @@ public ExceptionInfo(Exception e) public int FileColumnNumber { get; set; } - public string Method { get; set; } - + public string Method { get; set; } + public void Deserialize(string content) { using (XmlReader reader = XmlReader.Create(new StringReader(content))) @@ -72,7 +72,7 @@ public void Deserialize(string content) { this.ReadXml(reader); } - + reader.Close(); } } @@ -135,10 +135,10 @@ public void ReadXml(XmlReader reader) this.Method = reader.ReadContentAsString(); break; } - + reader.ReadEndElement(); reader.Read(); - } + } while (reader.ReadState != ReadState.EndOfFile && reader.NodeType != XmlNodeType.None && !string.IsNullOrEmpty(reader.LocalName)); } @@ -200,6 +200,6 @@ public void WriteXml(XmlWriter writer) writer.WriteElementString("FileColumnNumber", this.FileColumnNumber.ToString()); writer.WriteElementString("Method", this.Method); writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Exceptions/Exceptions.cs b/DNN Platform/Library/Services/Exceptions/Exceptions.cs index d8b08813b21..d88a0e84a4b 100644 --- a/DNN Platform/Library/Services/Exceptions/Exceptions.cs +++ b/DNN Platform/Library/Services/Exceptions/Exceptions.cs @@ -50,7 +50,7 @@ namespace DotNetNuke.Services.Exceptions public sealed class Exceptions { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Exceptions)); - + /// /// Gets the exception info. /// @@ -73,13 +73,13 @@ public static ExceptionInfo GetExceptionInfo(Exception e) { // Get the corresponding method for that stack frame. MemberInfo mi = sf.GetMethod(); - + // Get the namespace where that method is defined. string res = mi.DeclaringType.Namespace + "."; - + // Append the type name. res += mi.DeclaringType.Name + "."; - + // Append the name of the method. res += mi.Name; objExceptionInfo.Method = res; @@ -90,7 +90,7 @@ public static ExceptionInfo GetExceptionInfo(Exception e) objExceptionInfo.Method = "N/A - Reflection Permission required"; } - + if (!string.IsNullOrEmpty(sf.GetFileName())) { objExceptionInfo.FileName = sf.GetFileName(); @@ -98,7 +98,7 @@ public static ExceptionInfo GetExceptionInfo(Exception e) objExceptionInfo.FileLineNumber = sf.GetFileLineNumber(); } } - + return objExceptionInfo; } @@ -116,24 +116,6 @@ public static void ProcessHttpException(string URL) ProcessHttpException(exc, URL); } - /// - /// Threads the abort check if the exception is a ThreadAbortCheck. - /// - /// The exc. - /// - private static bool ThreadAbortCheck(Exception exc) - { - if (exc is ThreadAbortException) - { - Thread.ResetAbort(); - return true; - } - else - { - return false; - } - } - public static void ProcessHttpException(HttpException exc) { ProcessHttpException(exc, HttpContext.Current.Request.RawUrl); @@ -167,28 +149,6 @@ public static void ProcessModuleLoadException(PortalModuleBase objPortalModuleBa ProcessModuleLoadException((Control)objPortalModuleBase, exc, DisplayErrorMessage); } - private static void ProcessHttpException(HttpException exc, string URL) - { - var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); - Logger.Error(notFoundErrorString + ": - " + URL, exc); - - var log = new LogInfo - { - BypassBuffering = true, - LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - }; - log.LogProperties.Add(new LogDetailInfo(notFoundErrorString, "URL")); - var context = HttpContext.Current; - if (context != null) - { - log.LogProperties.Add(new LogDetailInfo("URL:", URL)); - } - - LogController.Instance.AddLog(log); - - throw exc; - } - /// /// Processes the module load exception. /// @@ -213,7 +173,7 @@ public static void ProcessModuleLoadException(Control ctrl, Exception exc) { return; } - + ProcessModuleLoadException(ctrl, exc, true); } @@ -230,7 +190,7 @@ public static void ProcessModuleLoadException(Control ctrl, Exception exc, bool { return; } - + string friendlyMessage = Localization.GetString("ErrorOccurred"); var ctrlModule = ctrl as IModuleControl; if (ctrlModule == null) @@ -246,10 +206,10 @@ public static void ProcessModuleLoadException(Control ctrl, Exception exc, bool { moduleTitle = ctrlModule.ModuleContext.Configuration.ModuleTitle; } - + friendlyMessage = string.Format(Localization.GetString("ModuleUnavailable"), moduleTitle); } - + ProcessModuleLoadException(friendlyMessage, ctrl, exc, DisplayErrorMessage); } @@ -266,7 +226,7 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct { return; } - + ProcessModuleLoadException(FriendlyMessage, ctrl, exc, true); } @@ -278,13 +238,13 @@ 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; } - + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); try { @@ -316,7 +276,7 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct // publish the exception var objExceptionLog = new ExceptionLogController(); objExceptionLog.AddLog(lex); - + // Some modules may want to suppress an error message // and just log the exception. if (DisplayErrorMessage) @@ -326,7 +286,7 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct { ErrorPlaceholder = (PlaceHolder)ctrl.Parent.FindControl("MessagePlaceHolder"); } - + if (ErrorPlaceholder != null) { // hide the module @@ -347,7 +307,7 @@ public static void ProcessModuleLoadException(string FriendlyMessage, Control ct Logger.Fatal(exc2); ProcessPageLoadException(exc2); } - + Logger.ErrorFormat("FriendlyMessage=\"{0}\" ctrl=\"{1}\" exc=\"{2}\"", FriendlyMessage, ctrl, exc); } @@ -367,7 +327,7 @@ public static void ProcessPageLoadException(Exception exc) { appURL += "&def=ErrorMessage"; } - + ProcessPageLoadException(exc, appURL); } @@ -383,7 +343,7 @@ public static void ProcessPageLoadException(Exception exc, string URL) { return; } - + PortalSettings _portalSettings = PortalController.Instance.GetCurrentPortalSettings(); if (!Host.UseCustomErrorMessages) { @@ -392,7 +352,7 @@ public static void ProcessPageLoadException(Exception exc, string URL) else { var lex = new PageLoadException(exc == null ? string.Empty : exc.Message, exc); - + // publish the exception var objExceptionLog = new ExceptionLogController(); objExceptionLog.AddLog(lex); @@ -488,5 +448,45 @@ public static void LogSearchException(SearchException exc) var objExceptionLog = new ExceptionLogController(); objExceptionLog.AddLog(exc, ExceptionLogController.ExceptionLogType.SEARCH_INDEXER_EXCEPTION); } + + /// + /// Threads the abort check if the exception is a ThreadAbortCheck. + /// + /// The exc. + /// + private static bool ThreadAbortCheck(Exception exc) + { + if (exc is ThreadAbortException) + { + Thread.ResetAbort(); + return true; + } + else + { + return false; + } + } + + private static void ProcessHttpException(HttpException exc, string URL) + { + var notFoundErrorString = Localization.GetString("ResourceNotFound", Localization.SharedResourceFile); + Logger.Error(notFoundErrorString + ": - " + URL, exc); + + var log = new LogInfo + { + BypassBuffering = true, + LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), + }; + log.LogProperties.Add(new LogDetailInfo(notFoundErrorString, "URL")); + var context = HttpContext.Current; + if (context != null) + { + log.LogProperties.Add(new LogDetailInfo("URL:", URL)); + } + + LogController.Instance.AddLog(log); + + throw exc; + } } } diff --git a/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs b/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs index af1e987f324..41df868d67d 100644 --- a/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs +++ b/DNN Platform/Library/Services/Exceptions/ModuleLoadException.cs @@ -24,14 +24,14 @@ public ModuleLoadException() } // constructor with exception message - public ModuleLoadException(string message) + public ModuleLoadException(string message) : base(message) { this.InitilizePrivateVariables(); } // constructor with exception message - public ModuleLoadException(string message, Exception inner, ModuleInfo ModuleConfiguration) + public ModuleLoadException(string message, Exception inner, ModuleInfo ModuleConfiguration) : base(message, inner) { this.m_ModuleConfiguration = ModuleConfiguration; @@ -39,13 +39,13 @@ public ModuleLoadException(string message, Exception inner, ModuleInfo ModuleCon } // constructor with message and inner exception - public ModuleLoadException(string message, Exception inner) + public ModuleLoadException(string message, Exception inner) : base(message, inner) { this.InitilizePrivateVariables(); } - protected ModuleLoadException(SerializationInfo info, StreamingContext context) + protected ModuleLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { this.InitilizePrivateVariables(); diff --git a/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs b/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs index 0355a66a286..d2d496abc5c 100644 --- a/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs +++ b/DNN Platform/Library/Services/Exceptions/ObjectHydrationException.cs @@ -14,12 +14,12 @@ public class ObjectHydrationException : BasePortalException private List _Columns; private Type _Type; - public ObjectHydrationException(string message, Exception innerException) + public ObjectHydrationException(string message, Exception innerException) : base(message, innerException) { } - public ObjectHydrationException(string message, Exception innerException, Type type, IDataReader dr) + public ObjectHydrationException(string message, Exception innerException, Type type, IDataReader dr) : base(message, innerException) { this._Type = type; @@ -30,18 +30,34 @@ public ObjectHydrationException(string message, Exception innerException, Type t } } - protected ObjectHydrationException(SerializationInfo info, StreamingContext context) + protected ObjectHydrationException(SerializationInfo info, StreamingContext context) : base(info, context) { } + public override string Message + { + get + { + string _Message = base.Message; + _Message += " Expecting - " + this.Type + "."; + _Message += " Returned - "; + foreach (string columnName in this.Columns) + { + _Message += columnName + ", "; + } + + return _Message; + } + } + public List Columns { get { return this._Columns; } - + set { this._Columns = value; @@ -54,27 +70,11 @@ public Type Type { return this._Type; } - + set { this._Type = value; } } - - public override string Message - { - get - { - string _Message = base.Message; - _Message += " Expecting - " + this.Type + "."; - _Message += " Returned - "; - foreach (string columnName in this.Columns) - { - _Message += columnName + ", "; - } - - return _Message; - } - } } } diff --git a/DNN Platform/Library/Services/Exceptions/PageLoadException.cs b/DNN Platform/Library/Services/Exceptions/PageLoadException.cs index 01e9a5c7c5e..9d239583b11 100644 --- a/DNN Platform/Library/Services/Exceptions/PageLoadException.cs +++ b/DNN Platform/Library/Services/Exceptions/PageLoadException.cs @@ -15,18 +15,18 @@ public PageLoadException() } // constructor with exception message - public PageLoadException(string message) + public PageLoadException(string message) : base(message) { } // constructor with message and inner exception - public PageLoadException(string message, Exception inner) + public PageLoadException(string message, Exception inner) : base(message, inner) { } - protected PageLoadException(SerializationInfo info, StreamingContext context) + protected PageLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/DNN Platform/Library/Services/Exceptions/SchedulerException.cs b/DNN Platform/Library/Services/Exceptions/SchedulerException.cs index 61bab29931c..0536c774bc0 100644 --- a/DNN Platform/Library/Services/Exceptions/SchedulerException.cs +++ b/DNN Platform/Library/Services/Exceptions/SchedulerException.cs @@ -15,18 +15,18 @@ public SchedulerException() } // constructor with exception message - public SchedulerException(string message) + public SchedulerException(string message) : base(message) { } // constructor with message and inner exception - public SchedulerException(string message, Exception inner) + public SchedulerException(string message, Exception inner) : base(message, inner) { } - protected SchedulerException(SerializationInfo info, StreamingContext context) + protected SchedulerException(SerializationInfo info, StreamingContext context) : base(info, context) { } diff --git a/DNN Platform/Library/Services/Exceptions/SearchException.cs b/DNN Platform/Library/Services/Exceptions/SearchException.cs index 6ea75bdf999..668a4b2e0b4 100644 --- a/DNN Platform/Library/Services/Exceptions/SearchException.cs +++ b/DNN Platform/Library/Services/Exceptions/SearchException.cs @@ -17,7 +17,7 @@ public SearchException() { } - public SearchException(string message, Exception inner, SearchItemInfo searchItem) + public SearchException(string message, Exception inner, SearchItemInfo searchItem) : base(message, inner) { this.m_SearchItem = searchItem; diff --git a/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs b/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs index d67ac67e064..76e0f2a7e7f 100644 --- a/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs +++ b/DNN Platform/Library/Services/Exceptions/SearchIndexEmptyException.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.Services.Exceptions public class SearchIndexEmptyException : Exception { - public SearchIndexEmptyException(string message) + public SearchIndexEmptyException(string message) : base(message) { } diff --git a/DNN Platform/Library/Services/Exceptions/SecurityException.cs b/DNN Platform/Library/Services/Exceptions/SecurityException.cs index 29c03632a1f..79852ddbf7b 100644 --- a/DNN Platform/Library/Services/Exceptions/SecurityException.cs +++ b/DNN Platform/Library/Services/Exceptions/SecurityException.cs @@ -23,20 +23,20 @@ public SecurityException() } // constructor with exception message - public SecurityException(string message) + public SecurityException(string message) : base(message) { this.InitilizePrivateVariables(); } // constructor with message and inner exception - public SecurityException(string message, Exception inner) + public SecurityException(string message, Exception inner) : base(message, inner) { this.InitilizePrivateVariables(); } - protected SecurityException(SerializationInfo info, StreamingContext context) + protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { this.InitilizePrivateVariables(); @@ -71,7 +71,7 @@ private void InitilizePrivateVariables() { this.m_IP = HttpContext.Current.Request.UserHostAddress; } - + this.m_Querystring = HttpContext.Current.Request.MapPath(this.Querystring, HttpContext.Current.Request.ApplicationPath, false); } catch (Exception exc) diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs index b7f7a28da37..c308a5bd9ab 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileChangedEventArgs.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.FileSystem.EventArgs public class FileChangedEventArgs : System.EventArgs { public IFileInfo FileInfo { get; set; } - + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs index ee1837bc9a7..d719f1481c8 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FileDownloadedEventArgs.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.FileSystem.EventArgs public class FileDownloadedEventArgs : System.EventArgs { public IFileInfo FileInfo { get; set; } - + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs index 85e60f747a9..04eee5d0dd4 100644 --- a/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs +++ b/DNN Platform/Library/Services/FileSystem/EventArgs/FolderChangedEventArgs.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.FileSystem.EventArgs public class FolderChangedEventArgs : System.EventArgs { public IFolderInfo FolderInfo { get; set; } - + public int UserId { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs index b00259e6fae..b42a89aacdc 100644 --- a/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileContentTypeManager.cs @@ -13,10 +13,10 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.ComponentModel; public class FileContentTypeManager : ComponentBase, IFileContentTypeManager - { - private static readonly object _threadLocker = new object(); + { + private static readonly object _threadLocker = new object(); private IDictionary _contentTypes; - + public virtual IDictionary ContentTypes { get @@ -54,15 +54,15 @@ public virtual IDictionary ContentTypes public virtual string GetContentType(string extension) { - if (string.IsNullOrEmpty(extension)) - { - return "application/octet-stream"; - } - + if (string.IsNullOrEmpty(extension)) + { + return "application/octet-stream"; + } + var key = extension.TrimStart('.').ToLowerInvariant(); return this.ContentTypes.ContainsKey(key) ? this.ContentTypes[key] : "application/octet-stream"; - } - + } + private Dictionary GetDefaultContentTypes() { var contentTypes = new Dictionary(); @@ -103,6 +103,6 @@ private Dictionary GetDefaultContentTypes() contentTypes.Add("ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"); return contentTypes; - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileInfo.cs b/DNN Platform/Library/Services/FileSystem/FileInfo.cs index b5ea750fa37..bc5c4d09b67 100644 --- a/DNN Platform/Library/Services/FileSystem/FileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileInfo.cs @@ -38,8 +38,8 @@ public class FileInfo : BaseEntityInfo, IHydratable, IFileInfo private int? _width = null; private int? _height = null; - private string _sha1Hash = null; - + private string _sha1Hash = null; + public FileInfo() { this.UniqueId = Guid.NewGuid(); @@ -74,49 +74,8 @@ public FileInfo(Guid uniqueId, Guid versionGuid, int portalId, string filename, this.StorageLocation = storageLocation; this.IsCached = cached; this.SHA1Hash = hash; - } - - [XmlElement("contenttype")] - public string ContentType { get; set; } - - [XmlElement("extension")] - public string Extension { get; set; } - - [XmlElement("fileid")] - public int FileId { get; set; } - - [XmlElement("uniqueid")] - public Guid UniqueId { get; set; } - - [XmlElement("versionguid")] - public Guid VersionGuid { get; set; } - - [XmlElement("filename")] - public string FileName { get; set; } - - [XmlElement("folder")] - public string Folder - { - get - { - return this._folder; - } - - set - { - // Make sure folder name ends with / - if (!string.IsNullOrEmpty(value) && !value.EndsWith("/")) - { - value = value + "/"; - } - - this._folder = value; - } } - [XmlElement("folderid")] - public int FolderId { get; set; } - [XmlElement("height")] public int Height { @@ -129,7 +88,7 @@ public int Height return this._height.Value; } - + set { this._height = value; @@ -181,9 +140,6 @@ public string PhysicalPath } } - [XmlIgnore] - public int PortalId { get; set; } - public string RelativePath { get @@ -192,6 +148,103 @@ public string RelativePath } } + public FileAttributes? FileAttributes + { + get + { + FileAttributes? _fileAttributes = null; + + if (this.SupportsFileAttributes) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); + _fileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).GetFileAttributes(this); + } + + return _fileAttributes; + } + } + + public bool SupportsFileAttributes + { + get + { + if (!this._supportsFileAttributes.HasValue) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); + + try + { + this._supportsFileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).SupportsFileAttributes(); + } + catch + { + this._supportsFileAttributes = false; + } + } + + return this._supportsFileAttributes.Value; + } + } + + /// + /// Gets a value indicating whether the file is enabled, + /// considering if the publish period is active and if the current date is within the publish period. + /// + public bool IsEnabled + { + get + { + var today = DateTime.Today; + return !this.EnablePublishPeriod + || (this.StartDate.Date <= today && (this.EndDate == Null.NullDate || today <= this.EndDate.Date)); + } + } + + [XmlElement("contenttype")] + public string ContentType { get; set; } + + [XmlElement("extension")] + public string Extension { get; set; } + + [XmlElement("fileid")] + public int FileId { get; set; } + + [XmlElement("uniqueid")] + public Guid UniqueId { get; set; } + + [XmlElement("versionguid")] + public Guid VersionGuid { get; set; } + + [XmlElement("filename")] + public string FileName { get; set; } + + [XmlElement("folder")] + public string Folder + { + get + { + return this._folder; + } + + set + { + // Make sure folder name ends with / + if (!string.IsNullOrEmpty(value) && !value.EndsWith("/")) + { + value = value + "/"; + } + + this._folder = value; + } + } + + [XmlElement("folderid")] + public int FolderId { get; set; } + + + [XmlIgnore] + public int PortalId { get; set; } + [XmlElement("size")] public int Size { get; set; } @@ -210,7 +263,7 @@ public int Width return this._width.Value; } - + set { this._width = value; @@ -229,51 +282,13 @@ public string SHA1Hash return this._sha1Hash; } - + set { this._sha1Hash = value; } } - public FileAttributes? FileAttributes - { - get - { - FileAttributes? _fileAttributes = null; - - if (this.SupportsFileAttributes) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); - _fileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).GetFileAttributes(this); - } - - return _fileAttributes; - } - } - - public bool SupportsFileAttributes - { - get - { - if (!this._supportsFileAttributes.HasValue) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalId, this.FolderMappingID); - - try - { - this._supportsFileAttributes = FolderProvider.Instance(folderMapping.FolderProviderType).SupportsFileAttributes(); - } - catch - { - this._supportsFileAttributes = false; - } - } - - return this._supportsFileAttributes.Value; - } - } - public DateTime LastModificationTime { get @@ -294,7 +309,7 @@ public DateTime LastModificationTime return this._lastModificationTime.Value; } - + set { this._lastModificationTime = value; @@ -337,7 +352,7 @@ public int FolderMappingID return this._folderMappingID; } - + set { this._folderMappingID = value; @@ -377,24 +392,10 @@ public int FolderMappingID [XmlIgnore] public bool HasBeenPublished { get; private set; } - /// - /// Gets a value indicating whether the file is enabled, - /// considering if the publish period is active and if the current date is within the publish period. - /// - public bool IsEnabled - { - get - { - var today = DateTime.Today; - return !this.EnablePublishPeriod - || (this.StartDate.Date <= today && (this.EndDate == Null.NullDate || today <= this.EndDate.Date)); - } - } - /// /// Gets or sets a reference to ContentItem, to use in Workflows. /// - public int ContentItemID { get; set; } + public int ContentItemID { get; set; } [XmlIgnore] public int KeyID @@ -403,13 +404,13 @@ public int KeyID { return this.FileId; } - + set { this.FileId = value; } - } - + } + public void Fill(IDataReader dr) { this.ContentType = Null.SetNullString(dr["ContentType"]); @@ -439,7 +440,7 @@ public void Fill(IDataReader dr) this.HasBeenPublished = Convert.ToBoolean(dr["HasBeenPublished"]); this.FillBaseProperties(dr); } - + private void LoadImageProperties() { var fileManager = (FileManager)FileManager.Instance; @@ -448,7 +449,7 @@ private void LoadImageProperties() this._width = this._height = 0; return; } - + var fileContent = fileManager.GetFileContent(this); if (fileContent == null) @@ -484,10 +485,10 @@ private void LoadImageProperties() { image.Dispose(); } - + fileContent.Position = 0; } - + fileContent.Close(); } @@ -500,6 +501,6 @@ private void LoadHashProperty() this._sha1Hash = currentHashCode; fileManager.UpdateFile(this); } - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs index 55ada41a337..2c0712673ad 100644 --- a/DNN Platform/Library/Services/FileSystem/FileLinkClickController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileLinkClickController.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 DotNetNuke.Services.FileSystem { using System; @@ -32,23 +31,28 @@ public int GetFileIdFromLinkClick(NameValueCollection queryParams) int fileId; return int.TryParse(strFileId, out fileId) ? fileId : -1; } - + + protected override Func GetFactory() + { + return () => new FileLinkClickController(); + } + 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, }; } @@ -70,16 +74,5 @@ private int GetPortalIdFromLinkClick(NameValueCollection queryParams) return PortalSettings.Current.PortalId; } - - protected override Func GetFactory() - { - return () => new FileLinkClickController(); - } - } - - internal class LinkClickPortalSettings - { - public string PortalGUID; - public bool EnableUrlLanguage; } } diff --git a/DNN Platform/Library/Services/FileSystem/FileManager.cs b/DNN Platform/Library/Services/FileSystem/FileManager.cs index 8c0f807918e..32c65174c24 100644 --- a/DNN Platform/Library/Services/FileSystem/FileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FileManager.cs @@ -46,14 +46,14 @@ namespace DotNetNuke.Services.FileSystem /// public class FileManager : ComponentBase, IFileManager { - private const int BufferSize = 4096; - - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileManager)); - + 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 { @@ -66,7 +66,7 @@ private FileExtensionWhitelist WhiteList { return Host.AllowedExtensionWhitelist; } - + if (!user.IsAdmin) { var settings = PortalSettings.Current; @@ -76,11 +76,11 @@ private FileExtensionWhitelist WhiteList } } } - + return Host.AllowedExtensionWhitelist; } - } - + } + /// /// Adds a file to the specified folder. /// @@ -105,229 +105,6 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil { 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) - { - try - { - if (!fileContent.CanSeek) - { - using (var seekableStream = this.GetSeekableStream(fileContent)) - { - provider.AddFile(destinationFolder, fileName, seekableStream); - } - } - else - { - provider.AddFile(destinationFolder, fileName, fileContent); - } - } - catch (Exception ex) - { - Logger.Error(ex); - throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); - } - } - - private void DeleteFileFromFolderProvider(IFileInfo file, FolderProvider provider) - { - try - { - // We can't delete the file until the fileContent resource has been released - provider.DeleteFile(file); - } - catch (Exception ex) - { - Logger.Error(ex); - throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); - } - } - - private void OnFileDeleted(IFileInfo fileInfo, int userId) - { - EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - IsCascadeDeleting = false, - }); - } - - private void OnFileRenamed(IFileInfo fileInfo, string oldFileName, int userId) - { - EventManager.Instance.OnFileRenamed(new FileRenamedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - OldFileName = oldFileName, - }); - } - - private void OnFileMoved(IFileInfo fileInfo, string oldFilePath, int userId) - { - EventManager.Instance.OnFileMoved(new FileMovedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - OldFilePath = oldFilePath, - }); - } - - private void OnFileOverwritten(IFileInfo fileInfo, int userId) - { - EventManager.Instance.OnFileOverwritten(new FileChangedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - }); - } - - private void OnFileMetadataChanged(IFileInfo fileInfo, int userId) - { - EventManager.Instance.OnFileMetadataChanged(new FileChangedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - }); - } - - private void OnFileAdded(IFileInfo fileInfo, IFolderInfo folderInfo, int userId) - { - EventManager.Instance.OnFileAdded(new FileAddedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - FolderInfo = folderInfo, - }); - } - - /// - /// Rotate/Flip the image as per the metadata and reset the metadata. - /// - /// - private void RotateFlipImage(ref Stream content) - { - try - { - using (var image = this.GetImageFromStream(content)) - { - if (!image.PropertyIdList.Any(x => x == 274)) - { - return; - } - - var orientation = image.GetPropertyItem(274); // Find rotation/flip meta property - if (orientation == null) - { - return; - } - - var flip = OrientationToFlipType(orientation.Value[0].ToString()); - if (flip == RotateFlipType.RotateNoneFlipNone) - { - return; // No rotation or flip required - } - - image.RotateFlip(flip); - var newOrientation = new byte[2]; - newOrientation[0] = 1; // little Endian - newOrientation[1] = 0; - orientation.Value = newOrientation; - image.SetPropertyItem(orientation); - content = ToStream(image, GetImageFormat(image)); - } - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - // Match the orientation code to the correct rotation: - private static RotateFlipType OrientationToFlipType(string orientation) - { - switch (int.Parse(orientation)) - { - case 1: - return RotateFlipType.RotateNoneFlipNone; - case 2: - return RotateFlipType.RotateNoneFlipX; - case 3: - return RotateFlipType.Rotate180FlipNone; - case 4: - return RotateFlipType.Rotate180FlipX; - case 5: - return RotateFlipType.Rotate90FlipX; - case 6: - return RotateFlipType.Rotate90FlipNone; - case 7: - return RotateFlipType.Rotate270FlipX; - case 8: - return RotateFlipType.Rotate270FlipNone; - default: - return RotateFlipType.RotateNoneFlipNone; - } - } /// /// Adds a file to the specified folder. @@ -473,18 +250,18 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil // File Events for updating will be not fired. Only events for adding nust be fired this.UpdateFile(file, true, false); } - + contentFileName = this.ProcessVersioning(folder, oldFile, file, createdByUserID); } else { contentFileName = this.UpdateWhileApproving(folder, createdByUserID, file, oldFile, fileContent); - + // This case will be to overwrite an existing file or initial file workflow this.ManageFileAdding(createdByUserID, folderWorkflow, fileExists, file); } } - + // Versioning else { @@ -556,7 +333,7 @@ public virtual IFileInfo AddFile(IFolderInfo folder, string fileName, Stream fil } throw new FolderProviderException( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "AddFileUnderlyingSystemError", "The underlying system threw an exception. The file has not been added."), ex); @@ -679,225 +456,51 @@ 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) + /// + /// Deletes the specified files. + /// + /// The files to delete. + /// Thrown when files is null. + public virtual void DeleteFiles(IEnumerable files) { - if (checkPermissions && !FolderPermissionController.Instance.CanAddFolder(folder)) - { - throw new PermissionsNotMetException(Localization.GetExceptionMessage( - "AddFilePermissionsNotMet", - "Permissions are not met. The file has not been added.")); - } - - if (!this.IsAllowedExtension(fileName) && !(UserController.Instance.GetCurrentUserInfo().IsSuperUser && ignoreWhiteList)) - { - throw new InvalidFileExtensionException( - string.Format( - Localization.GetExceptionMessage( - "AddFileExtensionNotAllowed", - "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(fileName))); - } + Requires.NotNull("files", files); - if (!this.IsValidFilename(fileName)) + foreach (var file in files) { - throw new InvalidFilenameException( - string.Format( - Localization.GetExceptionMessage( - "AddFilenameNotAllowed", - "The file name '{0}' is not allowed. The file has not been added."), fileName)); + this.DeleteFile(file); } } - private void NotifyFileAddingEvents(IFolderInfo folder, int createdByUserID, bool fileExists, Workflow folderWorkflow, IFileInfo file) + /// + /// Checks the existence of the specified file in the specified folder. + /// + /// The folder where to check the existence of the file. + /// The file name to check the existence of. + /// A bool value indicating whether the file exists or not in the specified folder. + /// Thrown when folder is null. + /// Thrown when fileName is null or empty. + /// Thrown when the underlying system throw an exception. + public virtual bool FileExists(IFolderInfo folder, string fileName) { - // Notify file event - if (fileExists && - (folderWorkflow == null || folderWorkflow.WorkflowID == SystemWorkflowManager.Instance.GetDirectPublishWorkflow(folderWorkflow.PortalID).WorkflowID)) - { - this.OnFileOverwritten(file, createdByUserID); - } - - if (!fileExists) - { - this.OnFileAdded(file, folder, createdByUserID); - } + return this.FileExists(folder, fileName, false); } - private void SetContentItem(IFileInfo file) - { - // Create Content Item if does not exists - if (file.ContentItemID == Null.NullInteger) - { - file.ContentItemID = this.CreateFileContentItem().ContentItemId; - } - } - - private void SetInitialFileMetadata(ref Stream fileContent, FileInfo file, FolderProvider folderProvider) - { - file.Size = (int)fileContent.Length; - var fileHash = folderProvider.GetHashCode(file, fileContent); - file.SHA1Hash = fileHash; - fileContent.Position = 0; - - file.Width = 0; - file.Height = 0; - - if (this.IsImageFile(file)) - { - this.RotateFlipImage(ref fileContent); - this.SetImageProperties(file, fileContent); - } - } - - private void SetImageProperties(IFileInfo file, Stream fileContent) - { - try - { - using (var image = this.GetImageFromStream(fileContent)) - { - file.Width = image.Width; - 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; - } - - /// - /// Deletes the specified files. - /// - /// The files to delete. - /// Thrown when files is null. - public virtual void DeleteFiles(IEnumerable files) - { - Requires.NotNull("files", files); - - foreach (var file in files) - { - this.DeleteFile(file); - } - } - - /// - /// Checks the existence of the specified file in the specified folder. - /// - /// The folder where to check the existence of the file. - /// The file name to check the existence of. - /// A bool value indicating whether the file exists or not in the specified folder. - /// Thrown when folder is null. - /// Thrown when fileName is null or empty. - /// Thrown when the underlying system throw an exception. - public virtual bool FileExists(IFolderInfo folder, string fileName) - { - return this.FileExists(folder, fileName, false); - } - - /// - /// Checks the existence of the specified file in the specified folder. - /// - /// The folder where to check the existence of the file. - /// The file name to check the existence of. - /// Indicates if the file is retrieved from All files or from Published files. - /// A bool value indicating whether the file exists or not in the specified folder. - /// Thrown when folder is null. - /// Thrown when fileName is null or empty. - /// Thrown when the underlying system throw an exception. - public virtual bool FileExists(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles) + /// + /// Checks the existence of the specified file in the specified folder. + /// + /// The folder where to check the existence of the file. + /// The file name to check the existence of. + /// Indicates if the file is retrieved from All files or from Published files. + /// A bool value indicating whether the file exists or not in the specified folder. + /// Thrown when folder is null. + /// Thrown when fileName is null or empty. + /// Thrown when the underlying system throw an exception. + public virtual bool FileExists(IFolderInfo folder, string fileName, bool retrieveUnpublishedFiles) { Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("fileName", fileName); @@ -964,7 +567,7 @@ public virtual IFileInfo GetFile(int fileID, bool retrieveUnpublishedFiles) DataCache.SetCache(strCacheKey, file, TimeSpan.FromMinutes(intCacheTimeout)); } } - + return (IFileInfo)file; } @@ -1077,18 +680,18 @@ public virtual Stream GetSeekableStream(Stream stream) { Requires.NotNull("stream", stream); - if (stream.CanSeek) - { - return stream; - } - + if (stream.CanSeek) + { + return stream; + } + var folderPath = this.GetHostMapPath(); string filePath; do { filePath = Path.Combine(folderPath, Path.GetRandomFileName()) + ".resx"; - } + } while (File.Exists(filePath)); var fileStream = this.GetAutoDeleteFileStream(filePath); @@ -1201,7 +804,7 @@ public virtual IFileInfo MoveFile(IFileInfo file, IFolderInfo destinationFolder) this.AddFileToFolderProvider(fileContent, file.FileName, destinationFolder, destinationFolderProvider); } } - + this.DeleteFileFromFolderProvider(file, sourceFolderProvider); } @@ -1239,11 +842,11 @@ public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) Requires.NotNull("file", file); Requires.NotNullOrEmpty("newFileName", newFileName); - if (file.FileName == newFileName) - { - return file; - } - + if (file.FileName == newFileName) + { + return file; + } + if (!this.IsAllowedExtension(newFileName)) { throw new InvalidFileExtensionException(string.Format(Localization.GetExceptionMessage("AddFileExtensionNotAllowed", "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(newFileName))); @@ -1280,7 +883,7 @@ public virtual IFileInfo RenameFile(IFileInfo file, string newFileName) { file.Extension = Path.GetExtension(newFileName).Replace(".", string.Empty); } - + var renamedFile = this.UpdateFile(file); // Notify File Renamed event @@ -1486,15 +1089,15 @@ public virtual void WriteFileToResponse(IFileInfo file, ContentDisposition conte } this.WriteFileToHttpContext(file, contentDisposition); - } - + } + internal virtual int CopyContentItem(int contentItemId) { - if (contentItemId == Null.NullInteger) - { - return Null.NullInteger; - } - + if (contentItemId == Null.NullInteger) + { + return Null.NullInteger; + } + var newContentItem = this.CreateFileContentItem(); // Clone terms @@ -1527,17 +1130,17 @@ internal virtual ContentItem CreateFileContentItem() objContent.ContentItemId = Util.GetContentController().AddContentItem(objContent); return objContent; - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder, FolderProvider sourceFolderProvider, FolderProvider destinationFolderProvider) { var versions = FileVersionController.Instance.GetFileVersions(file).ToArray(); - if (!versions.Any()) - { - return; - } - + if (!versions.Any()) + { + return; + } + var folder = FolderManager.Instance.GetFolder(file.FolderId); foreach (var version in versions) @@ -1546,11 +1149,11 @@ internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder using (var fileContent = sourceFolderProvider.GetFileStream(folder, version.FileName)) { // This scenario is when the file is in the Database Folder Provider - if (fileContent == null) - { - continue; - } - + if (fileContent == null) + { + continue; + } + this.AddFileToFolderProvider(fileContent, version.FileName, destinationFolder, destinationFolderProvider); } @@ -1564,8 +1167,8 @@ internal virtual void MoveVersions(IFileInfo file, IFolderInfo destinationFolder this.DeleteFileFromFolderProvider(fileVersion, sourceFolderProvider); } - } - + } + /// This member is reserved for internal use and is not intended to be used directly from your code. internal virtual void AutoSyncFile(IFileInfo file) { @@ -1589,9 +1192,9 @@ 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. + } + + /// 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) { @@ -1603,7 +1206,7 @@ internal virtual int ExtractFiles(IFileInfo file, IFolderInfo destinationFolder, { invalidFiles = new List(); } - + var exactFilesCount = 0; try @@ -1673,92 +1276,33 @@ 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) + /// 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) { - if (WorkflowEngine.Instance.IsWorkflowCompleted(contentItemID)) + var folderManager = FolderManager.Instance; + + var folderMappingController = FolderMappingController.Instance; + var folderMapping = folderMappingController.GetFolderMapping(destinationFolder.PortalID, destinationFolder.FolderMappingID); + + if (fileName.LastIndexOf('/') == -1) { - WorkflowEngine.Instance.StartWorkflow(folderWorkflow.WorkflowID, contentItemID, createdByUserID); - return true; + return; } - - 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"; + var zipFolder = fileName.Substring(0, fileName.LastIndexOf('/')); - // 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) + var folderPath = PathUtils.Instance.RemoveTrailingSlash(zipFolder); + + if (folderPath.IndexOf("/") == -1) { - return file.FileName; + var newFolderPath = destinationFolder.FolderPath + PathUtils.Instance.FormatFolderPath(folderPath); + if (!folderManager.FolderExists(destinationFolder.PortalID, newFolderPath)) + { + folderManager.AddFolder(folderMapping, newFolderPath); + } } - - 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) - { - var folderManager = FolderManager.Instance; - - var folderMappingController = FolderMappingController.Instance; - var folderMapping = folderMappingController.GetFolderMapping(destinationFolder.PortalID, destinationFolder.FolderMappingID); - - if (fileName.LastIndexOf('/') == -1) - { - return; - } - - var zipFolder = fileName.Substring(0, fileName.LastIndexOf('/')); - - var folderPath = PathUtils.Instance.RemoveTrailingSlash(zipFolder); - - if (folderPath.IndexOf("/") == -1) - { - var newFolderPath = destinationFolder.FolderPath + PathUtils.Instance.FormatFolderPath(folderPath); - if (!folderManager.FolderExists(destinationFolder.PortalID, newFolderPath)) - { - folderManager.AddFolder(folderMapping, newFolderPath); - } - } - else + else { var zipFolders = folderPath.Split('/'); @@ -1775,16 +1319,16 @@ 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. + } + + /// 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. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual int GetCurrentUserID() { @@ -1817,30 +1361,30 @@ 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. + } + + /// 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. + } + + /// 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. + } + + /// 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. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual bool IsAllowedExtension(string fileName) { @@ -1852,17 +1396,17 @@ 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. + } + + /// 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. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual bool IsFileAutoSyncEnabled() { @@ -1893,11 +1437,11 @@ internal virtual void WriteFileToHttpContext(IFileInfo file, ContentDisposition } // Do not send negative Content-Length (file.Size could be negative due to integer overflow for files > 2GB) - if (file.Size >= 0) - { - objResponse.AppendHeader("Content-Length", file.Size.ToString(CultureInfo.InvariantCulture)); - } - + if (file.Size >= 0) + { + objResponse.AppendHeader("Content-Length", file.Size.ToString(CultureInfo.InvariantCulture)); + } + objResponse.ContentType = this.GetContentType(file.Extension.Replace(".", string.Empty)); try @@ -1953,7 +1497,7 @@ internal virtual void WriteStream(HttpResponse objResponse, Stream objStream) } } } - + /// /// Update file info to database. /// @@ -1965,7 +1509,7 @@ internal virtual IFileInfo UpdateFile(IFileInfo file, bool updateLazyload) // By default File Events will be fired return this.UpdateFile(file, updateLazyload, true); } - + /// /// Update file info to database. /// @@ -1977,7 +1521,7 @@ internal virtual IFileInfo UpdateFile(IFileInfo file, bool updateLazyload, bool { Requires.NotNull("file", file); - DataProvider.Instance().UpdateFile( + DataProvider.Instance().UpdateFile( file.FileId, file.VersionGuid, file.FileName, @@ -2005,7 +1549,7 @@ internal virtual IFileInfo UpdateFile(IFileInfo file, bool updateLazyload, bool { this.OnFileMetadataChanged(updatedFile ?? this.GetFile(file.FileId, true), this.GetCurrentUserID()); } - + return updatedFile; } @@ -2015,10 +1559,96 @@ internal virtual void ClearFolderCache(int portalId) DataCache.ClearFolderCache(portalId); } + 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) + { + switch (int.Parse(orientation)) + { + case 1: + return RotateFlipType.RotateNoneFlipNone; + case 2: + return RotateFlipType.RotateNoneFlipX; + case 3: + return RotateFlipType.Rotate180FlipNone; + case 4: + return RotateFlipType.Rotate180FlipX; + case 5: + return RotateFlipType.Rotate90FlipX; + case 6: + return RotateFlipType.Rotate90FlipNone; + case 7: + return RotateFlipType.Rotate270FlipX; + case 8: + return RotateFlipType.Rotate270FlipNone; + default: + return RotateFlipType.RotateNoneFlipNone; + } + } + private static bool ValidMetadata(IFileInfo file, out string exceptionMessage) { exceptionMessage = string.Empty; - + // TODO check dynamically all required fields from MetadataInfo // TODO check dynamically all max lengths from MetadataInfo @@ -2049,6 +1679,376 @@ private static bool ValidMetadata(IFileInfo file, out string exceptionMessage) } return true; - } + } + + private void AddFileToFolderProvider(Stream fileContent, string fileName, IFolderInfo destinationFolder, FolderProvider provider) + { + try + { + if (!fileContent.CanSeek) + { + using (var seekableStream = this.GetSeekableStream(fileContent)) + { + provider.AddFile(destinationFolder, fileName, seekableStream); + } + } + else + { + provider.AddFile(destinationFolder, fileName, fileContent); + } + } + catch (Exception ex) + { + Logger.Error(ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + } + } + + private void DeleteFileFromFolderProvider(IFileInfo file, FolderProvider provider) + { + try + { + // We can't delete the file until the fileContent resource has been released + provider.DeleteFile(file); + } + catch (Exception ex) + { + Logger.Error(ex); + throw new FolderProviderException(Localization.GetExceptionMessage("UnderlyingSystemError", "The underlying system threw an exception."), ex); + } + } + + private void OnFileDeleted(IFileInfo fileInfo, int userId) + { + EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + IsCascadeDeleting = false, + }); + } + + private void OnFileRenamed(IFileInfo fileInfo, string oldFileName, int userId) + { + EventManager.Instance.OnFileRenamed(new FileRenamedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + OldFileName = oldFileName, + }); + } + + private void OnFileMoved(IFileInfo fileInfo, string oldFilePath, int userId) + { + EventManager.Instance.OnFileMoved(new FileMovedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + OldFilePath = oldFilePath, + }); + } + + private void OnFileOverwritten(IFileInfo fileInfo, int userId) + { + EventManager.Instance.OnFileOverwritten(new FileChangedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + }); + } + + private void OnFileMetadataChanged(IFileInfo fileInfo, int userId) + { + EventManager.Instance.OnFileMetadataChanged(new FileChangedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + }); + } + + private void OnFileAdded(IFileInfo fileInfo, IFolderInfo folderInfo, int userId) + { + EventManager.Instance.OnFileAdded(new FileAddedEventArgs + { + FileInfo = fileInfo, + UserId = userId, + FolderInfo = folderInfo, + }); + } + + /// + /// Rotate/Flip the image as per the metadata and reset the metadata. + /// + /// + private void RotateFlipImage(ref Stream content) + { + try + { + using (var image = this.GetImageFromStream(content)) + { + if (!image.PropertyIdList.Any(x => x == 274)) + { + return; + } + + var orientation = image.GetPropertyItem(274); // Find rotation/flip meta property + if (orientation == null) + { + return; + } + + var flip = OrientationToFlipType(orientation.Value[0].ToString()); + if (flip == RotateFlipType.RotateNoneFlipNone) + { + return; // No rotation or flip required + } + + image.RotateFlip(flip); + var newOrientation = new byte[2]; + newOrientation[0] = 1; // little Endian + newOrientation[1] = 0; + orientation.Value = newOrientation; + image.SetPropertyItem(orientation); + content = ToStream(image, GetImageFormat(image)); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + private void CheckFileAddingRestrictions(IFolderInfo folder, string fileName, bool checkPermissions, + bool ignoreWhiteList) + { + if (checkPermissions && !FolderPermissionController.Instance.CanAddFolder(folder)) + { + throw new PermissionsNotMetException(Localization.GetExceptionMessage( + "AddFilePermissionsNotMet", + "Permissions are not met. The file has not been added.")); + } + + if (!this.IsAllowedExtension(fileName) && !(UserController.Instance.GetCurrentUserInfo().IsSuperUser && ignoreWhiteList)) + { + throw new InvalidFileExtensionException( + string.Format( + Localization.GetExceptionMessage( + "AddFileExtensionNotAllowed", + "The extension '{0}' is not allowed. The file has not been added."), Path.GetExtension(fileName))); + } + + if (!this.IsValidFilename(fileName)) + { + throw new InvalidFilenameException( + string.Format( + Localization.GetExceptionMessage( + "AddFilenameNotAllowed", + "The file name '{0}' is not allowed. The file has not been added."), fileName)); + } + } + + private void NotifyFileAddingEvents(IFolderInfo folder, int createdByUserID, bool fileExists, Workflow folderWorkflow, IFileInfo file) + { + // Notify file event + if (fileExists && + (folderWorkflow == null || folderWorkflow.WorkflowID == SystemWorkflowManager.Instance.GetDirectPublishWorkflow(folderWorkflow.PortalID).WorkflowID)) + { + this.OnFileOverwritten(file, createdByUserID); + } + + if (!fileExists) + { + this.OnFileAdded(file, folder, createdByUserID); + } + } + + private void SetContentItem(IFileInfo file) + { + // Create Content Item if does not exists + if (file.ContentItemID == Null.NullInteger) + { + file.ContentItemID = this.CreateFileContentItem().ContentItemId; + } + } + + private void SetInitialFileMetadata(ref Stream fileContent, FileInfo file, FolderProvider folderProvider) + { + file.Size = (int)fileContent.Length; + var fileHash = folderProvider.GetHashCode(file, fileContent); + file.SHA1Hash = fileHash; + fileContent.Position = 0; + + file.Width = 0; + file.Height = 0; + + if (this.IsImageFile(file)) + { + this.RotateFlipImage(ref fileContent); + this.SetImageProperties(file, fileContent); + } + } + + private void SetImageProperties(IFileInfo file, Stream fileContent) + { + try + { + using (var image = this.GetImageFromStream(fileContent)) + { + file.Width = image.Width; + 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; + } + + 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")); + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs index 8d1bf75c243..c2485aa685a 100644 --- a/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs +++ b/DNN Platform/Library/Services/FileSystem/FileServerHandler.cs @@ -21,10 +21,10 @@ namespace DotNetNuke.Services.FileSystem public class FileServerHandler : IHttpHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileServerHandler)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileServerHandler)); + + public bool IsReusable => true; - public bool IsReusable => true; - /// ----------------------------------------------------------------------------- /// /// This handler handles requests for LinkClick.aspx, but only those specifc @@ -72,7 +72,7 @@ public void ProcessRequest(HttpContext context) Language = context.Request.Cookies["language"].Value; } } - + if (LocaleController.Instance.IsEnabled(ref Language, _portalSettings.PortalId)) { Localization.SetThreadCultures(new CultureInfo(Language), _portalSettings); @@ -85,12 +85,12 @@ public void ProcessRequest(HttpContext context) { URL = "FileID=" + FileLinkClickController.Instance.GetFileIdFromLinkClick(context.Request.QueryString); } - + if (context.Request.QueryString["userticket"] != null) { URL = "UserId=" + UrlUtils.DecryptParameter(context.Request.QueryString["userticket"]); } - + if (context.Request.QueryString["link"] != null) { URL = context.Request.QueryString["link"]; @@ -99,7 +99,7 @@ public void ProcessRequest(HttpContext context) URL = string.Empty; // restrict direct access by FileID } } - + if (!string.IsNullOrEmpty(URL)) { URL = URL.Replace(@"\", @"/"); @@ -116,7 +116,7 @@ public void ProcessRequest(HttpContext context) this.Handle404Exception(context, context.Request.RawUrl); } } - + if (UrlType != TabType.File) { URL = Globals.LinkClick(URL, TabId, ModuleId, false); @@ -138,10 +138,10 @@ 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); } - + var contentDisposition = blnForceDownload ? ContentDisposition.Attachment : ContentDisposition.Inline; // clear the current response @@ -213,7 +213,7 @@ public void ProcessRequest(HttpContext context) { this.Handle404Exception(context, URL); } - + break; case TabType.Url: // prevent phishing by verifying that URL exists in URLs table for Portal @@ -221,7 +221,7 @@ public void ProcessRequest(HttpContext context) { context.Response.Redirect(URL, true); } - + break; default: // redirect to URL @@ -249,7 +249,7 @@ private bool HasAPublishedVersion(IFileInfo file) { return true; } - + // We should allow creator to see the file that is pending to be approved var user = UserController.Instance.GetCurrentUserInfo(); return user != null && user.UserID == file.CreatedByUserID; diff --git a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs index e3070a89adf..caab420bce5 100644 --- a/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs +++ b/DNN Platform/Library/Services/FileSystem/FileUrlHelper.cs @@ -28,11 +28,11 @@ public static bool IsStandardFileURLFormat(string requestPath, out IFileInfo fil { portalId = int.Parse(portal); } - + fileRequested = FileManager.Instance.GetFile(portalId, filePath); return true; } - + fileRequested = null; return false; } @@ -45,7 +45,7 @@ public static bool IsLinkClickURLFormat(string requestPath, NameValueCollection fileRequested = FileManager.Instance.GetFile(fileId); return true; } - + fileRequested = null; return false; } diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs index 01c2bbd9821..0cd21853e51 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionController.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionController.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Services.FileSystem.EventArgs; public class FileVersionController : ComponentBase, IFileVersionController - { + { public string AddFileVersion(IFileInfo file, int userId, bool published, bool removeOldestVersions, Stream content = null) { Requires.NotNull("file", file); @@ -43,7 +43,7 @@ public string AddFileVersion(IFileInfo file, int userId, bool published, bool re } var newVersion = DataProvider.Instance() - .AddFileVersion( + .AddFileVersion( file.FileId, file.UniqueId, file.VersionGuid, @@ -90,11 +90,11 @@ public void SetPublishedVersion(IFileInfo file, int newPublishedVersion) // Rename the original file to the versioned name // Rename the new versioned name to the original file name var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) - { - return; - } - + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); folderProvider.RenameFile(file, GetVersionedFilename(file, file.PublishedVersion)); @@ -113,11 +113,11 @@ public int DeleteFileVersion(IFileInfo file, int version) int newVersion; var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) - { - return Null.NullInteger; - } - + if (folderMapping == null) + { + return Null.NullInteger; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); if (file.PublishedVersion == version) @@ -161,11 +161,11 @@ public void DeleteAllUnpublishedVersions(IFileInfo file, bool resetPublishedVers Requires.NotNull("file", file); var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) - { - return; - } - + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); foreach (var version in this.GetFileVersions(file)) @@ -218,11 +218,11 @@ public IEnumerable GetFileVersionsInFolder(int folderId) public Stream GetVersionContent(IFileInfo file, int version) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) - { - return null; - } - + if (folderMapping == null) + { + return null; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); var folder = FolderManager.Instance.GetFolder(file.FolderId); return this.GetVersionContent(folderProvider, folder, file, version); @@ -231,11 +231,11 @@ public Stream GetVersionContent(IFileInfo file, int version) public void RollbackFileVersion(IFileInfo file, int version, int userId) { var folderMapping = FolderMappingController.Instance.GetFolderMapping(file.PortalId, file.FolderMappingID); - if (folderMapping == null) - { - return; - } - + if (folderMapping == null) + { + return; + } + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); var folder = FolderManager.Instance.GetFolder(file.FolderId); using (var content = this.GetVersionContent(folderProvider, folder, file, version)) @@ -254,7 +254,7 @@ public void RollbackFileVersion(IFileInfo file, int version, int userId) FileManager.Instance.UpdateFile(file); this.RemoveOldestsVersions(file); - } + } internal static string GetVersionedFilename(IFileInfo file, int version) { @@ -271,14 +271,14 @@ private static void RenameFile(IFileInfo file, string 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, }); } diff --git a/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs b/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs index 68246edb7e6..934ab50ee49 100644 --- a/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FileVersionInfo.cs @@ -11,12 +11,12 @@ namespace DotNetNuke.Services.FileSystem [Serializable] public class FileVersionInfo : BaseEntityInfo - { + { public FileVersionInfo() { this.Version = 1; - } - + } + [XmlElement("fileid")] public int FileId { get; set; } @@ -42,6 +42,6 @@ public FileVersionInfo() public int Width { get; set; } [XmlElement("sha1hash")] - public string SHA1Hash { get; set; } + public string SHA1Hash { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderController.cs b/DNN Platform/Library/Services/FileSystem/FolderController.cs index 07100589034..d528e819486 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderController.cs @@ -25,12 +25,12 @@ namespace DotNetNuke.Services.FileSystem /// /// ----------------------------------------------------------------------------- public class FolderController - { + { public enum StorageLocationTypes { InsecureFileSystem = 0, SecureFileSystem = 1, DatabaseSecure = 2, - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs index ebc5e85ef51..dd6fda2c8c9 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderInfo.cs @@ -26,13 +26,13 @@ public class FolderInfo : BaseEntityInfo, IHydratable, IFolderInfo private string _displayName; private string _displayPath; private FolderPermissionCollection _folderPermissions; - private int _folderMappingId; - - public FolderInfo() + private int _folderMappingId; + + 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) @@ -53,7 +53,7 @@ public FolderInfo(Guid uniqueId, int portalId, string folderpath, int storageLoc this.IsProtected = isProtected; this.IsCached = isCached; this.LastUpdated = lastUpdated; - } + } internal FolderInfo(bool initialiseEmptyPermissions) { @@ -65,10 +65,7 @@ internal FolderInfo(bool initialiseEmptyPermissions) { this._folderPermissions = new FolderPermissionCollection(); } - } - - [XmlElement("folderid")] - public int FolderID { get; set; } + } [XmlElement("uniqueid")] public Guid UniqueId { get; set; } @@ -86,7 +83,7 @@ public string FolderName { folderName = folderName.Substring(folderName.LastIndexOf("/", StringComparison.Ordinal) + 1); } - + return folderName; } } @@ -103,74 +100,12 @@ public bool HasChildren } } - [XmlElement("displayname")] - public string DisplayName - { - get - { - if (string.IsNullOrEmpty(this._displayName)) - { - this._displayName = this.FolderName; - } - - return this._displayName; - } - - set - { - this._displayName = value; - } - } - - [XmlElement("folderpath")] - public string FolderPath { get; set; } - - [XmlElement("displaypath")] - public string DisplayPath - { - get - { - if (string.IsNullOrEmpty(this._displayPath)) - { - this._displayPath = this.FolderPath; - } - - return this._displayPath; - } - - set - { - this._displayPath = value; - } - } - - [XmlElement("iscached")] - public bool IsCached { get; set; } - - [XmlElement("isprotected")] - public bool IsProtected { get; set; } - - /// - /// Gets or sets a value indicating whether file versions are active for the folder. - /// - [XmlElement("isversioned")] - public bool IsVersioned { get; set; } - - /// - /// Gets or sets the path this folder is mapped on its provider file system. - /// - [XmlElement("mappedpath")] - public string MappedPath { get; set; } - /// /// Gets or sets a reference to the active Workflow for the folder. /// [XmlElement("workflowid")] public int WorkflowID { get; set; } - [XmlIgnore] - public DateTime LastUpdated { get; set; } - /// /// Gets or sets a reference to the parent folder. /// @@ -227,6 +162,83 @@ public FolderPermissionCollection FolderPermissions } } + public bool IsStorageSecure + { + get + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalID, this.FolderMappingID); + return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; + } + } + + [XmlElement("folderid")] + public int FolderID { get; set; } + + + [XmlElement("displayname")] + public string DisplayName + { + get + { + if (string.IsNullOrEmpty(this._displayName)) + { + this._displayName = this.FolderName; + } + + return this._displayName; + } + + set + { + this._displayName = value; + } + } + + [XmlElement("folderpath")] + public string FolderPath { get; set; } + + [XmlElement("displaypath")] + public string DisplayPath + { + get + { + if (string.IsNullOrEmpty(this._displayPath)) + { + this._displayPath = this.FolderPath; + } + + return this._displayPath; + } + + set + { + this._displayPath = value; + } + } + + [XmlElement("iscached")] + public bool IsCached { get; set; } + + [XmlElement("isprotected")] + public bool IsProtected { get; set; } + + /// + /// Gets or sets a value indicating whether file versions are active for the folder. + /// + [XmlElement("isversioned")] + public bool IsVersioned { get; set; } + + /// + /// Gets or sets the path this folder is mapped on its provider file system. + /// + [XmlElement("mappedpath")] + public string MappedPath { get; set; } + + + [XmlIgnore] + public DateTime LastUpdated { get; set; } + + public int FolderMappingID { get @@ -252,22 +264,13 @@ public int FolderMappingID return this._folderMappingId; } - + set { this._folderMappingId = value; } } - public bool IsStorageSecure - { - get - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(this.PortalID, this.FolderMappingID); - return FolderProvider.Instance(folderMapping.FolderProviderType).IsStorageSecure; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Key ID. @@ -281,13 +284,13 @@ public int KeyID { return this.FolderID; } - + set { this.FolderID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a FolderInfo from a Data Reader. diff --git a/DNN Platform/Library/Services/FileSystem/FolderManager.cs b/DNN Platform/Library/Services/FileSystem/FolderManager.cs index 6153368532d..ded6cc7c30c 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderManager.cs @@ -42,16 +42,16 @@ public class FolderManager : ComponentBase, IFold 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(); - + private static readonly object _threadLocker = new object(); + public virtual string MyFolderName { get { return Localization.GetString("MyFolderName"); } - } - + } + /// /// Creates a new folder using the provided folder path. /// @@ -94,7 +94,7 @@ public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string fol var parentFolder = this.GetParentFolder(folderMapping.PortalID, folderPath); if (parentFolder != null) { - var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping( + var parentFolderMapping = FolderMappingController.Instance.GetFolderMapping( parentFolder.PortalID, parentFolder.FolderMappingID); if (FolderProvider.Instance(parentFolderMapping.FolderProviderType).SupportsMappedPaths) @@ -141,645 +141,275 @@ public virtual IFolderInfo AddFolder(FolderMappingInfo folderMapping, string fol return folder; } - private static Regex WildcardToRegex(string pattern) + /// + /// Creates a new folder in the given portal using the provided folder path. + /// The same mapping than the parent folder will be used to create this folder. So this method have to be used only to create subfolders. + /// + /// The portal identifier. + /// The path of the new folder. + /// Thrown when folderPath is null or empty. + /// The added folder. + public virtual IFolderInfo AddFolder(int portalId, string folderPath) { - if (!pattern.Contains("*") && !pattern.Contains("?")) - { - pattern = "^" + pattern + ".*$"; - } - else - { - pattern = "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"; - } + Requires.NotNullOrEmpty("folderPath", folderPath); - return RegexUtils.GetCachedRegex(pattern, RegexOptions.IgnoreCase); - } + folderPath = PathUtils.Instance.FormatFolderPath(folderPath); - 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 - var tmpfolder = this.GetFolder(folder.PortalID, folder.FolderPath); + var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); + var parentFolder = this.GetFolder(portalId, parentFolderPath) ?? this.AddFolder(portalId, parentFolderPath); - if (tmpfolder != null && folder.FolderID == Null.NullInteger) - { - folder.FolderID = tmpfolder.FolderID; - } + var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, parentFolder.FolderMappingID); - if (folder.FolderID == Null.NullInteger) - { - var isVersioned = folder.IsVersioned; - var workflowId = folder.WorkflowID; + return this.AddFolder(folderMapping, folderPath); + } - // Inherit some configuration from its Parent Folder - var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); - var parentId = Null.NullInteger; - if (parentFolder != null) - { - isVersioned = parentFolder.IsVersioned; - workflowId = parentFolder.WorkflowID; - parentId = parentFolder.FolderID; - } + /// + /// Deletes the specified folder. + /// + /// The folder to delete. + /// Thrown when folder is null. + /// Thrown when the underlying system throw an exception. + public virtual void DeleteFolder(IFolderInfo folder) + { + this.DeleteFolderInternal(folder, false); + } - folder.FolderPath = PathUtils.Instance.FormatFolderPath(folder.FolderPath); - folder.FolderID = DataProvider.Instance().AddFolder( - folder.PortalID, - folder.UniqueId, - folder.VersionGuid, - folder.FolderPath, - folder.MappedPath, - folder.StorageLocation, - folder.IsProtected, - folder.IsCached, - folder.LastUpdated, - this.GetCurrentUserId(), - folder.FolderMappingID, - isVersioned, - workflowId, - parentId); + public virtual void UnlinkFolder(IFolderInfo folder) + { + this.DeleteFolderRecursive(folder, new Collection(), true, true); + } - // Refetch folder for logging - folder = this.GetFolder(folder.PortalID, folder.FolderPath); + /// + /// Deletes the specified folder. + /// + /// The folder identifier. + public virtual void DeleteFolder(int folderId) + { + var folder = this.GetFolder(folderId); - this.AddLogEntry(folder, EventLogController.EventLogType.FOLDER_CREATED); + this.DeleteFolder(folder); + } - if (parentFolder != null) - { - this.UpdateFolderInternal(parentFolder, false); - } - else - { - this.UpdateParentFolder(folder.PortalID, folder.FolderPath); - } - } - else - { - var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); - if (parentFolder != null) - { - // Ensure that Parent Id is repaired - folder.ParentID = parentFolder.FolderID; - } - - this.UpdateFolderInternal(folder, false); - } + /// + /// Deletes the specified folder and all its content. + /// + /// The folder to delete. + /// A collection with all not deleted subfolders after processiong the action. + public void DeleteFolder(IFolderInfo folder, ICollection notDeletedSubfolders) + { + this.DeleteFolderRecursive(folder, notDeletedSubfolders, true, this.GetOnlyUnmap(folder)); + } - // Invalidate Cache - this.ClearFolderCache(folder.PortalID); + /// + /// Checks the existence of the specified folder in the specified portal. + /// + /// The portal where to check the existence of the folder. + /// The path of folder to check the existence of. + /// A bool value indicating whether the folder exists or not in the specified portal. + public virtual bool FolderExists(int portalId, string folderPath) + { + Requires.PropertyNotNull("folderPath", folderPath); - return folder.FolderID; + return this.GetFolder(portalId, folderPath) != null; } - private bool GetOnlyUnmap(IFolderInfo folder) + /// + /// Gets the files contained in the specified folder. + /// + /// The folder from which to retrieve the files. + /// The list of files contained in the specified folder. + public virtual IEnumerable GetFiles(IFolderInfo folder) { - if (folder == null || folder.ParentID == Null.NullInteger) - { - return true; - } - - return FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(folder.FolderMappingID).FolderProviderType).SupportsMappedPaths && - this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID; + return this.GetFiles(folder, false); } - private void UnmapFolderInternal(IFolderInfo folder, bool isCascadeDeleting) + /// + /// Gets the files contained in the specified folder. + /// + /// The folder from which to retrieve the files. + /// Whether or not to include all the subfolders. + /// The list of files contained in the specified folder. + public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive) { - Requires.NotNull("folder", folder); - - if (DirectoryWrapper.Instance.Exists(folder.PhysicalPath)) - { - DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); - } - - this.DeleteFolder(folder.PortalID, folder.FolderPath); - - // Notify folder deleted event - this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); + return this.GetFiles(folder, recursive, false); } - private void DeleteFolderInternal(IFolderInfo folder, bool isCascadeDeleting) + /// + /// Gets the files contained in the specified folder. + /// + /// The folder from which to retrieve the files. + /// Whether or not to include all the subfolders. + /// Indicates if the file is retrieved from All files or from Published files. + /// The list of files contained in the specified folder. + public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles) { Requires.NotNull("folder", folder); - var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - - try - { - FolderProvider.Instance(folderMapping.FolderProviderType).DeleteFolder(folder); - } - catch (Exception ex) - { - Logger.Error(ex); - - throw new FolderProviderException( - Localization.GetExceptionMessage( - "DeleteFolderUnderlyingSystemError", - "The underlying system threw an exception. The folder has not been deleted."), - ex); - } - - if (DirectoryWrapper.Instance.Exists(folder.PhysicalPath)) - { - DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); - } - - this.DeleteFolder(folder.PortalID, folder.FolderPath); - - // Notify folder deleted event - this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); + return CBO.Instance.FillCollection(DataProvider.Instance().GetFiles(folder.FolderID, retrieveUnpublishedFiles, recursive)); } - private IFolderInfo GetParentFolder(int portalId, string folderPath) + /// + /// Gets the list of Standard folders the specified user has the provided permissions. + /// + /// The user info. + /// The permissions the folders have to met. + /// The list of Standard folders the specified user has the provided permissions. + /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. + public virtual IEnumerable GetFileSystemFolders(UserInfo user, string permissions) { - if (!string.IsNullOrEmpty(folderPath)) - { - var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - return this.GetFolder(portalId, parentFolderPath); - } + var userFolders = new List(); - return null; - } + var portalId = user.PortalID; - private IEnumerable SearchFiles(IFolderInfo folder, Regex regex, bool recursive) - { - var fileCollection = - CBO.Instance.FillCollection(DataProvider.Instance().GetFiles(folder.FolderID, false, false)); + var userFolder = this.GetUserFolder(user); - var files = (from f in fileCollection where regex.IsMatch(f.FileName) select f).Cast().ToList(); + var defaultFolderMaping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - if (recursive) + var folders = this.GetFolders(portalId, permissions, user.UserID).Where(f => f.FolderPath != null && f.FolderMappingID == defaultFolderMaping.FolderMappingID); + + foreach (var folder in folders) { - foreach (var subFolder in this.GetFolders(folder)) + if (folder.FolderPath.StartsWith(DefaultUsersFoldersPath + "/", StringComparison.InvariantCultureIgnoreCase)) { - if (FolderPermissionController.Instance.CanViewFolder(subFolder)) + if (folder.FolderID == userFolder.FolderID) { - files.AddRange(this.SearchFiles(subFolder, regex, true)); + folder.DisplayPath = this.MyFolderName + "/"; + folder.DisplayName = this.MyFolderName; + } + else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) // Allow UserFolder children + { + continue; } } + + userFolders.Add(folder); } - return files; + return userFolders; } - private IFolderInfo UpdateFolderInternal(IFolderInfo folder, bool clearCache) + /// + /// Gets a folder entity by providing a folder identifier. + /// + /// The identifier of the folder. + /// The folder entity or null if the folder cannot be located. + public virtual IFolderInfo GetFolder(int folderId) { - Requires.NotNull("folder", folder); - - DataProvider.Instance().UpdateFolder( - folder.PortalID, - folder.VersionGuid, - folder.FolderID, - PathUtils.Instance.FormatFolderPath(folder.FolderPath), - folder.StorageLocation, - folder.MappedPath, - folder.IsProtected, - folder.IsCached, - folder.LastUpdated, - this.GetCurrentUserId(), - folder.FolderMappingID, - folder.IsVersioned, - folder.WorkflowID, - folder.ParentID); - - if (clearCache) + // Try and get the folder from the portal cache + IFolderInfo folder = null; + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (portalSettings != null) { - this.ClearFolderCache(folder.PortalID); + var folders = this.GetFolders(portalSettings.PortalId); + folder = folders.SingleOrDefault(f => f.FolderID == folderId) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); } - return folder; + return folder ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); } - private int FindFolderMappingId(MergedTreeItem item, int portalId) + /// + /// Gets a folder entity by providing a portal identifier and folder path. + /// + /// The portal where the folder exists. + /// The path of the folder. + /// The folder entity or null if the folder cannot be located. + public virtual IFolderInfo GetFolder(int portalId, string folderPath) { - if (item.ExistsInFolderMapping) - { - return item.FolderMappingID; - } + Requires.PropertyNotNull("folderPath", folderPath); - if (item.FolderPath.IndexOf('/') != item.FolderPath.LastIndexOf('/')) - { - var parentPath = item.FolderPath.Substring(0, item.FolderPath.TrimEnd('/').LastIndexOf('/') + 1); - var folder = this.GetFolder(portalId, parentPath); - if (folder != null) - { - return folder.FolderMappingID; - } - } + folderPath = PathUtils.Instance.FormatFolderPath(folderPath); - return FolderMappingController.Instance.GetDefaultFolderMapping(portalId).FolderMappingID; + var folders = this.GetFolders(portalId); + return folders.SingleOrDefault(f => f.FolderPath == folderPath) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(portalId, folderPath)); } - private bool DeleteFolderRecursive(IFolderInfo folder, ICollection notDeletedSubfolders, bool isRecursiveDeletionFolder, bool unmap) + /// + /// Gets a folder entity by providing its unique id. + /// + /// The unique id of the folder. + /// The folder entity or null if the folder cannot be located. + public virtual IFolderInfo GetFolder(Guid uniqueId) { - Requires.NotNull("folder", folder); - - if (UserSecurityController.Instance.HasFolderPermission(folder, "DELETE")) - { - var subfolders = this.GetFolders(folder); - - var allSubFoldersHasBeenDeleted = true; - - foreach (var subfolder in subfolders) - { - if (!this.DeleteFolderRecursive(subfolder, notDeletedSubfolders, false, unmap || this.GetOnlyUnmap(subfolder))) - { - allSubFoldersHasBeenDeleted = false; - } - } - - var files = this.GetFiles(folder, false, true); - foreach (var file in files) - { - if (unmap) - { - FileDeletionController.Instance.UnlinkFile(file); - } - else - { - FileDeletionController.Instance.DeleteFile(file); - } - - this.OnFileDeleted(file, this.GetCurrentUserId(), true); - } - - if (allSubFoldersHasBeenDeleted) - { - if (unmap) - { - this.UnmapFolderInternal(folder, !isRecursiveDeletionFolder); - } - else - { - this.DeleteFolderInternal(folder, !isRecursiveDeletionFolder); - } - - return true; - } - } - - notDeletedSubfolders.Add(folder); - return false; + return CBO.Instance.FillObject(DataProvider.Instance().GetFolderByUniqueID(uniqueId)); } - private string GetDefaultMappedPath(FolderMappingInfo folderMapping) + /// + /// Gets the list of subfolders for the specified folder. + /// + /// The folder to get the list of subfolders. + /// The list of subfolders for the specified folder. + /// Thrown when parentFolder is null. + public virtual IEnumerable GetFolders(IFolderInfo parentFolder) { - var defaultMappedPath = folderMapping.FolderMappingSettings[DefaultMappedPathSetting]; - if (defaultMappedPath == null) - { - return string.Empty; - } - - return defaultMappedPath.ToString(); + return this.GetFolders(parentFolder, false); } - private IEnumerable GetFolders(IFolderInfo parentFolder, bool allSubFolders) + /// + /// Gets the sorted list of folders of the provided portal. + /// + /// The portal identifier. + /// True = Read from Cache, False = Read from DB. + /// The sorted list of folders of the provided portal. + public virtual IEnumerable GetFolders(int portalId, bool useCache) { - Requires.NotNull("parentFolder", parentFolder); - - if (allSubFolders) + if (!useCache) { - var subFolders = - this.GetFolders(parentFolder.PortalID) - .Where( - f => - f.FolderPath.StartsWith( - parentFolder.FolderPath, - StringComparison.InvariantCultureIgnoreCase)); - - return subFolders.Where(f => f.FolderID != parentFolder.FolderID); + this.ClearFolderCache(portalId); } - return this.GetFolders(parentFolder.PortalID).Where(f => f.ParentID == parentFolder.FolderID); - } - - private void OnFolderMoved(IFolderInfo folderInfo, int userId, string 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, - }); - } - - private void OnFolderDeleted(IFolderInfo folderInfo, int userId, bool 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, - }); + return this.GetFolders(portalId); } - private void OnFileDeleted(IFileInfo fileInfo, int userId, bool isCascadeDeleting) - { - EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs - { - FileInfo = fileInfo, - UserId = userId, - IsCascadeDeleting = isCascadeDeleting, - }); - } - /// - /// Creates a new folder in the given portal using the provided folder path. - /// The same mapping than the parent folder will be used to create this folder. So this method have to be used only to create subfolders. + /// Gets the sorted list of folders of the provided portal. /// /// The portal identifier. - /// The path of the new folder. - /// Thrown when folderPath is null or empty. - /// The added folder. - public virtual IFolderInfo AddFolder(int portalId, string folderPath) + /// The sorted list of folders of the provided portal. + public virtual IEnumerable GetFolders(int portalId) { - Requires.NotNullOrEmpty("folderPath", folderPath); - - folderPath = PathUtils.Instance.FormatFolderPath(folderPath); - - var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - var parentFolder = this.GetFolder(portalId, parentFolderPath) ?? this.AddFolder(portalId, parentFolderPath); + var folders = new List(); - var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, parentFolder.FolderMappingID); + var cacheKey = string.Format(DataCache.FolderCacheKey, portalId); + CBO.Instance.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.FolderCacheTimeOut, DataCache.FolderCachePriority, portalId), this.GetFoldersSortedCallBack, false).ForEach(folders.Add); - return this.AddFolder(folderMapping, folderPath); + return folders; } /// - /// Deletes the specified folder. + /// Gets the sorted list of folders that match the provided permissions in the specified portal. /// - /// The folder to delete. - /// Thrown when folder is null. - /// Thrown when the underlying system throw an exception. - public virtual void DeleteFolder(IFolderInfo folder) + /// The portal identifier. + /// The permissions to match. + /// The user identifier to be used to check permissions. + /// The list of folders that match the provided permissions in the specified portal. + public virtual IEnumerable GetFolders(int portalId, string permissions, int userId) { - this.DeleteFolderInternal(folder, false); - } + var folders = new List(); - 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("."); - } + var cacheKey = string.Format(DataCache.FolderUserCacheKey, portalId, permissions, userId); + var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.FolderUserCacheTimeOut, DataCache.FolderUserCachePriority, portalId, permissions, userId); + CBO.Instance.GetCachedObject>(cacheItemArgs, this.GetFoldersByPermissionSortedCallBack, false).ForEach(folders.Add); - public virtual void UnlinkFolder(IFolderInfo folder) - { - this.DeleteFolderRecursive(folder, new Collection(), true, true); + return folders; } /// - /// Deletes the specified folder. + /// Gets the list of folders the specified user has read permissions. /// - /// The folder identifier. - public virtual void DeleteFolder(int folderId) + /// The user info. + /// The list of folders the specified user has read permissions. + public virtual IEnumerable GetFolders(UserInfo user) { - var folder = this.GetFolder(folderId); - - this.DeleteFolder(folder); + return this.GetFolders(user, "READ"); } /// - /// Deletes the specified folder and all its content. - /// - /// The folder to delete. - /// A collection with all not deleted subfolders after processiong the action. - 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. + /// Gets the list of folders the specified user has the provided permissions. /// - /// The portal where to check the existence of the folder. - /// The path of folder to check the existence of. - /// A bool value indicating whether the folder exists or not in the specified portal. - public virtual bool FolderExists(int portalId, string folderPath) - { - Requires.PropertyNotNull("folderPath", folderPath); - - return this.GetFolder(portalId, folderPath) != null; - } - - /// - /// Gets the files contained in the specified folder. - /// - /// The folder from which to retrieve the files. - /// The list of files contained in the specified folder. - public virtual IEnumerable GetFiles(IFolderInfo folder) - { - return this.GetFiles(folder, false); - } - - /// - /// Gets the files contained in the specified folder. - /// - /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders. - /// The list of files contained in the specified folder. - public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive) - { - return this.GetFiles(folder, recursive, false); - } - - /// - /// Gets the files contained in the specified folder. - /// - /// The folder from which to retrieve the files. - /// Whether or not to include all the subfolders. - /// Indicates if the file is retrieved from All files or from Published files. - /// The list of files contained in the specified folder. - public virtual IEnumerable GetFiles(IFolderInfo folder, bool recursive, bool retrieveUnpublishedFiles) - { - Requires.NotNull("folder", folder); - - return CBO.Instance.FillCollection(DataProvider.Instance().GetFiles(folder.FolderID, retrieveUnpublishedFiles, recursive)); - } - - /// - /// Gets the list of Standard folders the specified user has the provided permissions. - /// - /// The user info. - /// The permissions the folders have to met. - /// The list of Standard folders the specified user has the provided permissions. - /// This method is used to support legacy behaviours and situations where we know the file/folder is in the file system. - public virtual IEnumerable GetFileSystemFolders(UserInfo user, string permissions) - { - var userFolders = new List(); - - var portalId = user.PortalID; - - var userFolder = this.GetUserFolder(user); - - var defaultFolderMaping = FolderMappingController.Instance.GetDefaultFolderMapping(portalId); - - var folders = this.GetFolders(portalId, permissions, user.UserID).Where(f => f.FolderPath != null && f.FolderMappingID == defaultFolderMaping.FolderMappingID); - - foreach (var folder in folders) - { - if (folder.FolderPath.StartsWith(DefaultUsersFoldersPath + "/", StringComparison.InvariantCultureIgnoreCase)) - { - if (folder.FolderID == userFolder.FolderID) - { - folder.DisplayPath = this.MyFolderName + "/"; - folder.DisplayName = this.MyFolderName; - } - else if (!folder.FolderPath.StartsWith(userFolder.FolderPath, StringComparison.InvariantCultureIgnoreCase)) // Allow UserFolder children - { - continue; - } - } - - userFolders.Add(folder); - } - - return userFolders; - } - - /// - /// Gets a folder entity by providing a folder identifier. - /// - /// The identifier of the folder. - /// The folder entity or null if the folder cannot be located. - public virtual IFolderInfo GetFolder(int folderId) - { - // Try and get the folder from the portal cache - IFolderInfo folder = null; - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (portalSettings != null) - { - var folders = this.GetFolders(portalSettings.PortalId); - folder = folders.SingleOrDefault(f => f.FolderID == folderId) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); - } - - return folder ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(folderId)); - } - - /// - /// Gets a folder entity by providing a portal identifier and folder path. - /// - /// The portal where the folder exists. - /// The path of the folder. - /// The folder entity or null if the folder cannot be located. - public virtual IFolderInfo GetFolder(int portalId, string folderPath) - { - Requires.PropertyNotNull("folderPath", folderPath); - - folderPath = PathUtils.Instance.FormatFolderPath(folderPath); - - var folders = this.GetFolders(portalId); - return folders.SingleOrDefault(f => f.FolderPath == folderPath) ?? CBO.Instance.FillObject(DataProvider.Instance().GetFolder(portalId, folderPath)); - } - - /// - /// Gets a folder entity by providing its unique id. - /// - /// The unique id of the folder. - /// The folder entity or null if the folder cannot be located. - public virtual IFolderInfo GetFolder(Guid uniqueId) - { - return CBO.Instance.FillObject(DataProvider.Instance().GetFolderByUniqueID(uniqueId)); - } - - /// - /// Gets the list of subfolders for the specified folder. - /// - /// The folder to get the list of subfolders. - /// The list of subfolders for the specified folder. - /// Thrown when parentFolder is null. - public virtual IEnumerable GetFolders(IFolderInfo parentFolder) - { - return this.GetFolders(parentFolder, false); - } - - /// - /// Gets the sorted list of folders of the provided portal. - /// - /// The portal identifier. - /// True = Read from Cache, False = Read from DB. - /// The sorted list of folders of the provided portal. - public virtual IEnumerable GetFolders(int portalId, bool useCache) - { - if (!useCache) - { - this.ClearFolderCache(portalId); - } - - return this.GetFolders(portalId); - } - - /// - /// Gets the sorted list of folders of the provided portal. - /// - /// The portal identifier. - /// The sorted list of folders of the provided portal. - public virtual IEnumerable GetFolders(int portalId) - { - var folders = new List(); - - var cacheKey = string.Format(DataCache.FolderCacheKey, portalId); - CBO.Instance.GetCachedObject>(new CacheItemArgs(cacheKey, DataCache.FolderCacheTimeOut, DataCache.FolderCachePriority, portalId), this.GetFoldersSortedCallBack, false).ForEach(folders.Add); - - return folders; - } - - /// - /// Gets the sorted list of folders that match the provided permissions in the specified portal. - /// - /// The portal identifier. - /// The permissions to match. - /// The user identifier to be used to check permissions. - /// The list of folders that match the provided permissions in the specified portal. - public virtual IEnumerable GetFolders(int portalId, string permissions, int userId) - { - var folders = new List(); - - var cacheKey = string.Format(DataCache.FolderUserCacheKey, portalId, permissions, userId); - var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.FolderUserCacheTimeOut, DataCache.FolderUserCachePriority, portalId, permissions, userId); - CBO.Instance.GetCachedObject>(cacheItemArgs, this.GetFoldersByPermissionSortedCallBack, false).ForEach(folders.Add); - - return folders; - } - - /// - /// Gets the list of folders the specified user has read permissions. - /// - /// The user info. - /// The list of folders the specified user has read permissions. - public virtual IEnumerable GetFolders(UserInfo user) - { - return this.GetFolders(user, "READ"); - } - - /// - /// Gets the list of folders the specified user has the provided permissions. - /// - /// The user info. - /// The permissions the folders have to met. - /// The list of folders the specified user has the provided permissions. - public virtual IEnumerable GetFolders(UserInfo user, string permissions) + /// The user info. + /// The permissions the folders have to met. + /// The list of folders the specified user has the provided permissions. + public virtual IEnumerable GetFolders(UserInfo user, string permissions) { var userFolders = new List(); @@ -824,15 +454,15 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio var newFolderPath = PathUtils.Instance.FormatFolderPath(destinationFolder.FolderPath + folder.FolderName + "/"); - if (folder.FolderPath == destinationFolder.FolderPath) - { - return folder; - } - + if (folder.FolderPath == destinationFolder.FolderPath) + { + return folder; + } + if (this.FolderExists(folder.PortalID, newFolderPath)) { throw new InvalidOperationException(string.Format( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "CannotMoveFolderAlreadyExists", "The folder with name '{0}' cannot be moved. A folder with that name already exists under the folder '{1}'.", folder.FolderName, destinationFolder.FolderName))); } @@ -843,7 +473,7 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, IFolderInfo destinatio if (!this.CanMoveBetweenFolderMappings(folderMapping, destinationFolderMapping)) { throw new InvalidOperationException(string.Format( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "CannotMoveFolderBetweenFolderType", "The folder with name '{0}' cannot be moved. Move Folder operation between this two folder types is not allowed", folder.FolderName))); } @@ -896,11 +526,11 @@ public virtual void RenameFolder(IFolderInfo folder, string newFolderName) Requires.NotNull("folder", folder); Requires.NotNullOrEmpty("newFolderName", newFolderName); - if (folder.FolderName.Equals(newFolderName)) - { - return; - } - + if (folder.FolderName.Equals(newFolderName)) + { + return; + } + var currentFolderName = folder.FolderName; var newFolderPath = folder.FolderPath.Substring(0, folder.FolderPath.LastIndexOf(folder.FolderName, StringComparison.Ordinal)) + PathUtils.Instance.FormatFolderPath(newFolderName); @@ -1011,7 +641,7 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi var item = mergedTree.Values[i]; this.ProcessMergedTreeItemInAddMode(item, portalId); } - + this.RemoveSyncFoldersData(relativePath); // Step 2: Delete Files and Folders @@ -1045,7 +675,7 @@ public virtual int Synchronize(int portalId, string relativePath, bool isRecursi /// Updates metadata of the specified folder. /// /// The folder to update. - /// Thrown when folder is null. + /// Thrown when folder is null. /// public virtual IFolderInfo UpdateFolder(IFolderInfo folder) { @@ -1056,8 +686,8 @@ public virtual IFolderInfo UpdateFolder(IFolderInfo folder) this.SaveFolderPermissions(updatedFolder); return updatedFolder; - } - + } + /// /// Adds read permissions for all users to the specified folder. /// @@ -1098,11 +728,11 @@ public virtual void CopyParentFolderPermissions(IFolderInfo folder) { Requires.NotNull("folder", folder); - if (string.IsNullOrEmpty(folder.FolderPath)) - { - return; - } - + if (string.IsNullOrEmpty(folder.FolderPath)) + { + return; + } + var parentFolderPath = folder.FolderPath.Substring(0, folder.FolderPath.Substring(0, folder.FolderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); foreach (FolderPermissionInfo objPermission in @@ -1160,28 +790,6 @@ 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. /// @@ -1203,8 +811,8 @@ public virtual void SetFolderPermissions(IFolderInfo folder, int administratorRo } FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); - } - + } + /// /// Moves the specified folder and its contents to a new location. /// @@ -1228,17 +836,23 @@ public virtual IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath) } 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); } - internal virtual void AddLogEntry(string propertyName, string propertyValue, EventLogController.EventLogType eventLogType) + internal virtual bool IsValidFolderPath(string folderPath) { - EventLogController.Instance.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), eventLogType); - } + var illegalInFolderPath = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars()))), RegexOptions.Compiled); + return !illegalInFolderPath.IsMatch(folderPath) && !folderPath.TrimEnd('/', '\\').EndsWith("."); + } + + internal virtual void AddLogEntry(IFolderInfo folder, EventLogController.EventLogType eventLogType) + { + EventLogController.Instance.AddLog(folder, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), string.Empty, eventLogType); + } + + internal virtual void AddLogEntry(string propertyName, string propertyValue, EventLogController.EventLogType eventLogType) + { + EventLogController.Instance.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), this.GetCurrentUserId(), eventLogType); + } /// This member is reserved for internal use and is not intended to be used directly from your code. internal void DeleteFilesFromCache(int portalId, string newFolderPath) @@ -1252,9 +866,9 @@ 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. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual IFolderInfo AddUserFolder(UserInfo user) { @@ -1321,9 +935,9 @@ 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. + } + + /// 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) { @@ -1382,9 +996,9 @@ 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. + } + + /// 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) { @@ -1406,17 +1020,17 @@ internal virtual int CreateFolderInDatabase(int portalId, string folderPath, int break; } } - - 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); @@ -1474,23 +1088,23 @@ internal virtual void DeleteFoldersFromExternalStorageLocations(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This 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. + } + + /// 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. + } + + /// 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) { @@ -1520,9 +1134,9 @@ 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. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual SortedList GetDatabaseFoldersRecursive(IFolderInfo folder) { @@ -1535,13 +1149,13 @@ 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)) @@ -1556,9 +1170,9 @@ internal virtual SortedList GetDatabaseFoldersRecursive( } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// 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) { @@ -1594,9 +1208,9 @@ 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. + } + + /// 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) { @@ -1641,9 +1255,9 @@ internal virtual SortedList GetFileSystemFoldersRecursiv } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// 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) { @@ -1653,9 +1267,9 @@ internal virtual FolderMappingInfo GetFolderMapping(DictionaryThis member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This 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) { @@ -1706,9 +1320,9 @@ internal virtual SortedList GetFolderMappingFoldersRecur } return result; - } - - /// This member is reserved for internal use and is not intended to be used directly from your code. + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. /// internal virtual object GetFoldersByPermissionSortedCallBack(CacheItemArgs cacheItemArgs) { @@ -1716,17 +1330,17 @@ internal virtual object GetFoldersByPermissionSortedCallBack(CacheItemArgs cache 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. + } + + /// 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. + } + + /// 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) { @@ -1741,11 +1355,11 @@ internal virtual SortedList GetMergedTree(int portalId, foreach (var mergedItem in mergedTree.Values) { - if (mergedItem.FolderMappingID == Null.NullInteger) - { - continue; - } - + if (mergedItem.FolderMappingID == Null.NullInteger) + { + continue; + } + var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, mergedItem.FolderMappingID); // Add any folders from non-core providers @@ -1778,16 +1392,16 @@ 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. + } + + /// 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. + } + + /// 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) { @@ -1809,9 +1423,9 @@ 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. + } + + /// 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) { @@ -1828,16 +1442,16 @@ 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. + } + + /// 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. + } + + /// 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) { @@ -1850,430 +1464,816 @@ internal virtual SortedList MergeFolderLists(SortedList< { existingItem.FolderID = item.FolderID; } - + if (existingItem.FolderMappingID < 0) { existingItem.FolderMappingID = item.FolderMappingID; } - + if (string.IsNullOrEmpty(existingItem.MappedPath)) { existingItem.MappedPath = item.MappedPath; } - existingItem.ExistsInFileSystem = existingItem.ExistsInFileSystem || item.ExistsInFileSystem; - existingItem.ExistsInDatabase = existingItem.ExistsInDatabase || item.ExistsInDatabase; - existingItem.ExistsInFolderMapping = existingItem.ExistsInFolderMapping || item.ExistsInFolderMapping; + existingItem.ExistsInFileSystem = existingItem.ExistsInFileSystem || item.ExistsInFileSystem; + existingItem.ExistsInDatabase = existingItem.ExistsInDatabase || item.ExistsInDatabase; + existingItem.ExistsInFolderMapping = existingItem.ExistsInFolderMapping || item.ExistsInFolderMapping; + } + else + { + list1.Add(item.FolderPath, item); + } + } + + return list1; + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void MoveDirectory(string source, string target) + { + var stack = new Stack(); + stack.Push(new MoveFoldersInfo(source, target)); + + // ReSharper disable AssignNullToNotNullAttribute + while (stack.Count > 0) + { + var folders = stack.Pop(); + Directory.CreateDirectory(folders.Target); + foreach (var file in Directory.GetFiles(folders.Source, "*.*")) + { + var targetFile = Path.Combine(folders.Target, Path.GetFileName(file)); + if (File.Exists(targetFile)) + { + File.Delete(targetFile); + } + + File.Move(file, targetFile); + } + + foreach (var folder in Directory.GetDirectories(folders.Source)) + { + stack.Push(new MoveFoldersInfo(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); + } + } + + // ReSharper restore AssignNullToNotNullAttribute + Directory.Delete(source, true); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void MoveFolderWithinProvider(IFolderInfo folder, IFolderInfo destinationFolder) + { + var newFolderPath = destinationFolder.FolderPath + folder.FolderName + "/"; + this.RenameFolderInFileSystem(folder, newFolderPath); + + // Update provider + var newMappedPath = destinationFolder.MappedPath + folder.FolderName + "/"; + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); + var provider = FolderProvider.Instance(folderMapping.FolderProviderType); + provider.MoveFolder(folder.MappedPath, newMappedPath, folderMapping); + + // Update database + this.UpdateChildFolders(folder, Path.Combine(destinationFolder.FolderPath, folder.FolderName)); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void MoveFolderBetweenProviders(IFolderInfo folder, string newFolderPath) + { + this.RenameFolderInFileSystem(folder, newFolderPath); + + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath)).ToArray(); + var tmpFolderPath = folder.FolderPath; + + foreach (var folderInfo in folderInfos) + { + var folderPath = newFolderPath + folderInfo.FolderPath.Substring(tmpFolderPath.Length); + + var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); + folderInfo.ParentID = parentFolder.FolderID; + folderInfo.FolderPath = folderPath; + this.UpdateFolderInternal(folderInfo, true); + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void OverwriteFolder(IFolderInfo sourceFolder, IFolderInfo destinationFolder, Dictionary folderMappings, SortedList foldersToDelete) + { + var fileManager = FileManager.Instance; + var files = this.GetFiles(sourceFolder, true); + + foreach (var file in files) + { + fileManager.MoveFile(file, destinationFolder); + } + + // Delete source folder in database + this.DeleteFolder(sourceFolder.PortalID, sourceFolder.FolderPath); + + var folderMapping = this.GetFolderMapping(folderMappings, sourceFolder.FolderMappingID); + + if (this.IsFolderMappingEditable(folderMapping)) + { + foldersToDelete.Add(sourceFolder.FolderPath, sourceFolder); + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int portalId) + { + try + { + if (item.ExistsInFileSystem) + { + if (!item.ExistsInDatabase) + { + var folderMappingId = this.FindFolderMappingId(item, portalId); + this.CreateFolderInDatabase(portalId, item.FolderPath, folderMappingId); + } + } + else + { + if (item.ExistsInDatabase) + { + if (item.ExistsInFolderMapping) + { + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); + } + } + else // by exclusion it exists in the Folder Mapping + { + this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); + this.CreateFolderInDatabase(portalId, item.FolderPath, item.FolderMappingID, item.MappedPath); + } + } + } + catch (Exception ex) + { + Logger.Error(string.Format("Could not create folder {0}. EXCEPTION: {1}", item.FolderPath, ex.Message), ex); + } + } + + /// 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) + { + if (item.ExistsInFileSystem) + { + if (item.ExistsInDatabase) + { + if (item.FolderPath == string.Empty) + { + return; // Do not process root folder + } + + if (!item.ExistsInFolderMapping) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, item.FolderMappingID); + + if (folderMapping.IsEditable) + { + DirectoryWrapper.Instance.Delete(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath), false); + this.DeleteFolder(portalId, item.FolderPath); + } + } + } + } + else + { + if (item.ExistsInDatabase && !item.ExistsInFolderMapping) + { + this.DeleteFolder(portalId, item.FolderPath); + } + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void RemoveOrphanedFiles(IFolderInfo folder) + { + var files = this.GetFiles(folder, false, true); + + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); + + if (folderMapping != null) + { + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + + foreach (var file in files) + { + try + { + if (!folderProvider.FileExists(folder, file.FileName)) + { + FileDeletionController.Instance.DeleteFileData(file); + } + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + } + + /// 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) + { + var source = folder.PhysicalPath; + + var di = new DirectoryInfo(source); + if (!di.Exists) + { + return; + } + + var target = PathUtils.Instance.GetPhysicalPath(folder.PortalID, newFolderPath); + this.MoveDirectory(source, target); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void SaveFolderPermissions(IFolderInfo folder) + { + FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void SetScriptTimeout(int timeout) + { + HttpContext.Current.Server.ScriptTimeout = timeout; + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void SynchronizeFiles(MergedTreeItem item, int portalId) + { + var folder = this.GetFolder(portalId, item.FolderPath); + + if (folder == null) + { + return; + } + + var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, folder.FolderMappingID); + + if (folderMapping == null) + { + return; + } + + try + { + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + var fileManager = FileManager.Instance; + + if (folderProvider.FolderExists(folder.MappedPath, folderMapping)) + { + var files = folderProvider.GetFiles(folder); + + files = files.Except(FileVersionController.Instance.GetFileVersionsInFolder(folder.FolderID).Select(f => f.FileName)).ToArray(); + + foreach (var fileName in files) + { + try + { + var file = fileManager.GetFile(folder, fileName, true); + + if (file == null) + { + fileManager.AddFile(folder, fileName, null, false); + } + else if (!folderProvider.IsInSync(file)) + { + fileManager.UpdateFile(file, null); + } + } + catch (InvalidFileExtensionException ex) + { + Logger.Info(ex.Message); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + } + + this.RemoveOrphanedFiles(folder); + } + catch (Exception ex) + { + Logger.Error(ex); + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void UpdateParentFolder(int portalId, string folderPath) + { + if (!string.IsNullOrEmpty(folderPath)) + { + var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); + var objFolder = this.GetFolder(portalId, parentFolderPath); + if (objFolder != null) + { + // UpdateFolder(objFolder); + this.UpdateFolderInternal(objFolder, false); + } + } + } + + /// This member is reserved for internal use and is not intended to be used directly from your code. + internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPath) + { + var originalFolderPath = folder.FolderPath; + + var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath)).ToArray(); + + foreach (var folderInfo in folderInfos) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folderInfo.FolderMappingID); + var provider = FolderProvider.Instance(folderMapping.FolderProviderType); + + var folderPath = newFolderPath + (newFolderPath.EndsWith("/") ? string.Empty : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); + + var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); + folderInfo.ParentID = parentFolder.FolderID; + folderInfo.FolderPath = folderPath; + + var parentProvider = FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(parentFolder.PortalID, parentFolder.FolderMappingID).FolderProviderType); + if (parentProvider.SupportsMappedPaths || !provider.SupportsMappedPaths) + { + if (provider.SupportsMappedPaths) + { + var mappedPath = parentFolder.FolderPath == string.Empty ? string.Empty : folderPath.Replace(parentFolder.FolderPath, string.Empty); + folderInfo.MappedPath = PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + mappedPath); + } + else + { + folderInfo.MappedPath = folderPath; + } + } + else if (provider.SupportsMappedPaths) + { + if (originalFolderPath == folderInfo.MappedPath) + { + folderInfo.MappedPath = folderPath; + } + else if (folderInfo.MappedPath.EndsWith("/" + originalFolderPath, StringComparison.Ordinal)) + { + var newMappedPath = PathUtils.Instance.FormatFolderPath( + folderInfo.MappedPath.Substring(0, folderInfo.MappedPath.LastIndexOf("/" + originalFolderPath, StringComparison.Ordinal)) + "/" + folderPath); + folderInfo.MappedPath = newMappedPath; + } + } + + this.UpdateFolderInternal(folderInfo, false); + } + + 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 + if (sourceFolderMapping.FolderMappingID == destinationFolderMapping.FolderMappingID) + { + return true; + } + + return IsStandardFolderProviderType(sourceFolderMapping) && IsStandardFolderProviderType(destinationFolderMapping); + } + + 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 + var tmpfolder = this.GetFolder(folder.PortalID, folder.FolderPath); + + if (tmpfolder != null && folder.FolderID == Null.NullInteger) + { + folder.FolderID = tmpfolder.FolderID; + } + + if (folder.FolderID == Null.NullInteger) + { + var isVersioned = folder.IsVersioned; + var workflowId = folder.WorkflowID; + + // Inherit some configuration from its Parent Folder + var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); + var parentId = Null.NullInteger; + if (parentFolder != null) + { + isVersioned = parentFolder.IsVersioned; + workflowId = parentFolder.WorkflowID; + parentId = parentFolder.FolderID; + } + + folder.FolderPath = PathUtils.Instance.FormatFolderPath(folder.FolderPath); + folder.FolderID = DataProvider.Instance().AddFolder( + folder.PortalID, + folder.UniqueId, + folder.VersionGuid, + folder.FolderPath, + folder.MappedPath, + folder.StorageLocation, + folder.IsProtected, + folder.IsCached, + folder.LastUpdated, + this.GetCurrentUserId(), + folder.FolderMappingID, + isVersioned, + workflowId, + parentId); + + // Refetch folder for logging + folder = this.GetFolder(folder.PortalID, folder.FolderPath); + + this.AddLogEntry(folder, EventLogController.EventLogType.FOLDER_CREATED); + + if (parentFolder != null) + { + this.UpdateFolderInternal(parentFolder, false); } else { - list1.Add(item.FolderPath, item); + this.UpdateParentFolder(folder.PortalID, folder.FolderPath); + } + } + else + { + var parentFolder = this.GetParentFolder(folder.PortalID, folder.FolderPath); + if (parentFolder != null) + { + // Ensure that Parent Id is repaired + folder.ParentID = parentFolder.FolderID; } + + this.UpdateFolderInternal(folder, false); } - return list1; + // Invalidate Cache + this.ClearFolderCache(folder.PortalID); + + return folder.FolderID; } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void MoveDirectory(string source, string target) + private bool GetOnlyUnmap(IFolderInfo folder) { - var stack = new Stack(); - stack.Push(new MoveFoldersInfo(source, target)); - - // ReSharper disable AssignNullToNotNullAttribute - while (stack.Count > 0) + if (folder == null || folder.ParentID == Null.NullInteger) { - var folders = stack.Pop(); - Directory.CreateDirectory(folders.Target); - foreach (var file in Directory.GetFiles(folders.Source, "*.*")) - { - var targetFile = Path.Combine(folders.Target, Path.GetFileName(file)); - if (File.Exists(targetFile)) - { - File.Delete(targetFile); - } - - File.Move(file, targetFile); - } - - foreach (var folder in Directory.GetDirectories(folders.Source)) - { - stack.Push(new MoveFoldersInfo(folder, Path.Combine(folders.Target, Path.GetFileName(folder)))); - } + return true; } - - // ReSharper restore AssignNullToNotNullAttribute - Directory.Delete(source, true); + + return FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(folder.FolderMappingID).FolderProviderType).SupportsMappedPaths && + this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID; } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void MoveFolderWithinProvider(IFolderInfo folder, IFolderInfo destinationFolder) + private void UnmapFolderInternal(IFolderInfo folder, bool isCascadeDeleting) { - var newFolderPath = destinationFolder.FolderPath + folder.FolderName + "/"; - this.RenameFolderInFileSystem(folder, newFolderPath); + Requires.NotNull("folder", folder); - // Update provider - var newMappedPath = destinationFolder.MappedPath + folder.FolderName + "/"; - var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - var provider = FolderProvider.Instance(folderMapping.FolderProviderType); - provider.MoveFolder(folder.MappedPath, newMappedPath, folderMapping); + if (DirectoryWrapper.Instance.Exists(folder.PhysicalPath)) + { + DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); + } - // Update database - this.UpdateChildFolders(folder, Path.Combine(destinationFolder.FolderPath, folder.FolderName)); + this.DeleteFolder(folder.PortalID, folder.FolderPath); + + // Notify folder deleted event + this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void MoveFolderBetweenProviders(IFolderInfo folder, string newFolderPath) + private void DeleteFolderInternal(IFolderInfo folder, bool isCascadeDeleting) { - this.RenameFolderInFileSystem(folder, newFolderPath); + Requires.NotNull("folder", folder); - var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(folder.FolderPath)).ToArray(); - var tmpFolderPath = folder.FolderPath; + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); - foreach (var folderInfo in folderInfos) + try { - var folderPath = newFolderPath + folderInfo.FolderPath.Substring(tmpFolderPath.Length); - - var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); - folderInfo.ParentID = parentFolder.FolderID; - folderInfo.FolderPath = folderPath; - this.UpdateFolderInternal(folderInfo, true); + FolderProvider.Instance(folderMapping.FolderProviderType).DeleteFolder(folder); } - } + catch (Exception ex) + { + Logger.Error(ex); - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void OverwriteFolder(IFolderInfo sourceFolder, IFolderInfo destinationFolder, Dictionary folderMappings, SortedList foldersToDelete) - { - var fileManager = FileManager.Instance; - var files = this.GetFiles(sourceFolder, true); + throw new FolderProviderException( + Localization.GetExceptionMessage( + "DeleteFolderUnderlyingSystemError", + "The underlying system threw an exception. The folder has not been deleted."), + ex); + } - foreach (var file in files) + if (DirectoryWrapper.Instance.Exists(folder.PhysicalPath)) { - fileManager.MoveFile(file, destinationFolder); + DirectoryWrapper.Instance.Delete(folder.PhysicalPath, true); } - // Delete source folder in database - this.DeleteFolder(sourceFolder.PortalID, sourceFolder.FolderPath); + this.DeleteFolder(folder.PortalID, folder.FolderPath); - var folderMapping = this.GetFolderMapping(folderMappings, sourceFolder.FolderMappingID); + // Notify folder deleted event + this.OnFolderDeleted(folder, this.GetCurrentUserId(), isCascadeDeleting); + } - if (this.IsFolderMappingEditable(folderMapping)) + private IFolderInfo GetParentFolder(int portalId, string folderPath) + { + if (!string.IsNullOrEmpty(folderPath)) { - foldersToDelete.Add(sourceFolder.FolderPath, sourceFolder); + var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); + return this.GetFolder(portalId, parentFolderPath); } + + return null; } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void ProcessMergedTreeItemInAddMode(MergedTreeItem item, int portalId) + private IEnumerable SearchFiles(IFolderInfo folder, Regex regex, bool recursive) { - try + var fileCollection = + CBO.Instance.FillCollection(DataProvider.Instance().GetFiles(folder.FolderID, false, false)); + + var files = (from f in fileCollection where regex.IsMatch(f.FileName) select f).Cast().ToList(); + + if (recursive) { - if (item.ExistsInFileSystem) - { - if (!item.ExistsInDatabase) - { - var folderMappingId = this.FindFolderMappingId(item, portalId); - this.CreateFolderInDatabase(portalId, item.FolderPath, folderMappingId); - } - } - else + foreach (var subFolder in this.GetFolders(folder)) { - if (item.ExistsInDatabase) - { - if (item.ExistsInFolderMapping) - { - this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); - } - } - else // by exclusion it exists in the Folder Mapping + if (FolderPermissionController.Instance.CanViewFolder(subFolder)) { - this.CreateFolderInFileSystem(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath)); - this.CreateFolderInDatabase(portalId, item.FolderPath, item.FolderMappingID, item.MappedPath); + files.AddRange(this.SearchFiles(subFolder, regex, true)); } } } - catch (Exception ex) + + return files; + } + + private IFolderInfo UpdateFolderInternal(IFolderInfo folder, bool clearCache) + { + Requires.NotNull("folder", folder); + + DataProvider.Instance().UpdateFolder( + folder.PortalID, + folder.VersionGuid, + folder.FolderID, + PathUtils.Instance.FormatFolderPath(folder.FolderPath), + folder.StorageLocation, + folder.MappedPath, + folder.IsProtected, + folder.IsCached, + folder.LastUpdated, + this.GetCurrentUserId(), + folder.FolderMappingID, + folder.IsVersioned, + folder.WorkflowID, + folder.ParentID); + + if (clearCache) { - Logger.Error(string.Format("Could not create folder {0}. EXCEPTION: {1}", item.FolderPath, ex.Message), ex); + this.ClearFolderCache(folder.PortalID); } + + return folder; } - /// 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) + private int FindFolderMappingId(MergedTreeItem item, int portalId) { - if (item.ExistsInFileSystem) + if (item.ExistsInFolderMapping) { - if (item.ExistsInDatabase) - { - if (item.FolderPath == string.Empty) - { - return; // Do not process root folder - } - - if (!item.ExistsInFolderMapping) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, item.FolderMappingID); - - if (folderMapping.IsEditable) - { - DirectoryWrapper.Instance.Delete(PathUtils.Instance.GetPhysicalPath(portalId, item.FolderPath), false); - this.DeleteFolder(portalId, item.FolderPath); - } - } - } + return item.FolderMappingID; } - else + + if (item.FolderPath.IndexOf('/') != item.FolderPath.LastIndexOf('/')) { - if (item.ExistsInDatabase && !item.ExistsInFolderMapping) + var parentPath = item.FolderPath.Substring(0, item.FolderPath.TrimEnd('/').LastIndexOf('/') + 1); + var folder = this.GetFolder(portalId, parentPath); + if (folder != null) { - this.DeleteFolder(portalId, item.FolderPath); + return folder.FolderMappingID; } } + + return FolderMappingController.Instance.GetDefaultFolderMapping(portalId).FolderMappingID; } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void RemoveOrphanedFiles(IFolderInfo folder) + private bool DeleteFolderRecursive(IFolderInfo folder, ICollection notDeletedSubfolders, bool isRecursiveDeletionFolder, bool unmap) { - var files = this.GetFiles(folder, false, true); - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folder.FolderMappingID); + Requires.NotNull("folder", folder); - if (folderMapping != null) + if (UserSecurityController.Instance.HasFolderPermission(folder, "DELETE")) { - var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + var subfolders = this.GetFolders(folder); + + var allSubFoldersHasBeenDeleted = true; + + foreach (var subfolder in subfolders) + { + if (!this.DeleteFolderRecursive(subfolder, notDeletedSubfolders, false, unmap || this.GetOnlyUnmap(subfolder))) + { + allSubFoldersHasBeenDeleted = false; + } + } + var files = this.GetFiles(folder, false, true); foreach (var file in files) { - try + if (unmap) + { + FileDeletionController.Instance.UnlinkFile(file); + } + else + { + FileDeletionController.Instance.DeleteFile(file); + } + + this.OnFileDeleted(file, this.GetCurrentUserId(), true); + } + + if (allSubFoldersHasBeenDeleted) + { + if (unmap) { - if (!folderProvider.FileExists(folder, file.FileName)) - { - FileDeletionController.Instance.DeleteFileData(file); - } + this.UnmapFolderInternal(folder, !isRecursiveDeletionFolder); } - catch (Exception ex) + else { - Logger.Error(ex); + this.DeleteFolderInternal(folder, !isRecursiveDeletionFolder); } + + return true; } } + + notDeletedSubfolders.Add(folder); + return false; } - - private void InitialiseSyncFoldersData(int portalId, string relativePath) + + private string GetDefaultMappedPath(FolderMappingInfo folderMapping) { - 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 + var defaultMappedPath = folderMapping.FolderMappingSettings[DefaultMappedPathSetting]; + if (defaultMappedPath == null) { - SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + return string.Empty; } + + return defaultMappedPath.ToString(); } - private void RemoveSyncFoldersData(string relativePath) + private IEnumerable GetFolders(IFolderInfo parentFolder, bool allSubFolders) { - var threadId = Thread.CurrentThread.ManagedThreadId; - if (SyncFoldersData.ContainsKey(threadId)) + Requires.NotNull("parentFolder", parentFolder); + + if (allSubFolders) { - SyncFoldersData.Remove(threadId); - } - } + var subFolders = + this.GetFolders(parentFolder.PortalID) + .Where( + f => + f.FolderPath.StartsWith( + parentFolder.FolderPath, + StringComparison.InvariantCultureIgnoreCase)); - /// 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) - { - var source = folder.PhysicalPath; + return subFolders.Where(f => f.FolderID != parentFolder.FolderID); + } - var di = new DirectoryInfo(source); - if (!di.Exists) - { - return; - } - - var target = PathUtils.Instance.GetPhysicalPath(folder.PortalID, newFolderPath); - this.MoveDirectory(source, target); + return this.GetFolders(parentFolder.PortalID).Where(f => f.ParentID == parentFolder.FolderID); } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void SaveFolderPermissions(IFolderInfo folder) + private void OnFolderMoved(IFolderInfo folderInfo, int userId, string oldFolderPath) { - FolderPermissionController.SaveFolderPermissions((FolderInfo)folder); + EventManager.Instance.OnFolderMoved(new FolderMovedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderPath = oldFolderPath, + }); } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void SetScriptTimeout(int timeout) + private void OnFolderRenamed(IFolderInfo folderInfo, int userId, string oldFolderName) { - HttpContext.Current.Server.ScriptTimeout = timeout; + EventManager.Instance.OnFolderRenamed(new FolderRenamedEventArgs + { + FolderInfo = folderInfo, + UserId = userId, + OldFolderName = oldFolderName, + }); } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void SynchronizeFiles(MergedTreeItem item, int portalId) + private void OnFolderDeleted(IFolderInfo folderInfo, int userId, bool isCascadeDeleting) { - var folder = this.GetFolder(portalId, item.FolderPath); - - if (folder == null) - { - return; - } - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, folder.FolderMappingID); - - if (folderMapping == null) + EventManager.Instance.OnFolderDeleted(new FolderDeletedEventArgs { - return; - } + FolderInfo = folderInfo, + UserId = userId, + IsCascadeDeletng = isCascadeDeleting, + }); + } - try + private void OnFolderAdded(IFolderInfo folderInfo, int userId) + { + EventManager.Instance.OnFolderAdded(new FolderChangedEventArgs { - var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - var fileManager = FileManager.Instance; - - if (folderProvider.FolderExists(folder.MappedPath, folderMapping)) - { - var files = folderProvider.GetFiles(folder); - - files = files.Except(FileVersionController.Instance.GetFileVersionsInFolder(folder.FolderID).Select(f => f.FileName)).ToArray(); - - foreach (var fileName in files) - { - try - { - var file = fileManager.GetFile(folder, fileName, true); - - if (file == null) - { - fileManager.AddFile(folder, fileName, null, false); - } - else if (!folderProvider.IsInSync(file)) - { - fileManager.UpdateFile(file, null); - } - } - catch (InvalidFileExtensionException ex) - { - Logger.Info(ex.Message); - } - catch (Exception ex) - { - Logger.Error(ex); - } - } - } + FolderInfo = folderInfo, + UserId = userId, + }); + } - this.RemoveOrphanedFiles(folder); - } - catch (Exception ex) + private void OnFileDeleted(IFileInfo fileInfo, int userId, bool isCascadeDeleting) + { + EventManager.Instance.OnFileDeleted(new FileDeletedEventArgs { - Logger.Error(ex); - } + FileInfo = fileInfo, + UserId = userId, + IsCascadeDeleting = isCascadeDeleting, + }); } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void UpdateParentFolder(int portalId, string folderPath) + private FolderPermissionCollection GetFolderPermissionsFromSyncData(int portalId, string relativePath) { - if (!string.IsNullOrEmpty(folderPath)) + var threadId = Thread.CurrentThread.ManagedThreadId; + FolderPermissionCollection permissions = null; + if (SyncFoldersData.ContainsKey(threadId)) { - var parentFolderPath = folderPath.Substring(0, folderPath.Substring(0, folderPath.Length - 1).LastIndexOf("/", StringComparison.Ordinal) + 1); - var objFolder = this.GetFolder(portalId, parentFolderPath); - if (objFolder != null) + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) { - // UpdateFolder(objFolder); - this.UpdateFolderInternal(objFolder, false); + return SyncFoldersData[threadId].Permissions; } + + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; + return permissions; } - } - /// This member is reserved for internal use and is not intended to be used directly from your code. - internal virtual void UpdateChildFolders(IFolderInfo folder, string newFolderPath) - { - var originalFolderPath = folder.FolderPath; + permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); - var folderInfos = this.GetFolders(folder.PortalID).Where(f => f.FolderPath != string.Empty && f.FolderPath.StartsWith(originalFolderPath)).ToArray(); + return permissions; + } - foreach (var folderInfo in folderInfos) + private void InitialiseSyncFoldersData(int portalId, string relativePath) + { + var threadId = Thread.CurrentThread.ManagedThreadId; + var permissions = FolderPermissionController.GetFolderPermissionsCollectionByFolder(portalId, relativePath); + if (SyncFoldersData.ContainsKey(threadId)) { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(folder.PortalID, folderInfo.FolderMappingID); - var provider = FolderProvider.Instance(folderMapping.FolderProviderType); - - var folderPath = newFolderPath + (newFolderPath.EndsWith("/") ? string.Empty : "/") + folderInfo.FolderPath.Substring(originalFolderPath.Length); - - var parentFolder = this.GetParentFolder(folder.PortalID, folderPath); - folderInfo.ParentID = parentFolder.FolderID; - folderInfo.FolderPath = folderPath; - - var parentProvider = FolderProvider.Instance(FolderMappingController.Instance.GetFolderMapping(parentFolder.PortalID, parentFolder.FolderMappingID).FolderProviderType); - if (parentProvider.SupportsMappedPaths || !provider.SupportsMappedPaths) + if (SyncFoldersData[threadId].FolderPath == relativePath && SyncFoldersData[threadId].PortalId == portalId) { - if (provider.SupportsMappedPaths) - { - var mappedPath = parentFolder.FolderPath == string.Empty ? string.Empty : folderPath.Replace(parentFolder.FolderPath, string.Empty); - folderInfo.MappedPath = PathUtils.Instance.FormatFolderPath(parentFolder.MappedPath + mappedPath); - } - else - { - folderInfo.MappedPath = folderPath; - } + SyncFoldersData[threadId].Permissions = permissions; } - else if (provider.SupportsMappedPaths) + else { - if (originalFolderPath == folderInfo.MappedPath) - { - folderInfo.MappedPath = folderPath; - } - else if (folderInfo.MappedPath.EndsWith("/" + originalFolderPath, StringComparison.Ordinal)) - { - var newMappedPath = PathUtils.Instance.FormatFolderPath( - folderInfo.MappedPath.Substring(0, folderInfo.MappedPath.LastIndexOf("/" + originalFolderPath, StringComparison.Ordinal)) + "/" + folderPath); - folderInfo.MappedPath = newMappedPath; - } + SyncFoldersData[threadId] = new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }; } - - this.UpdateFolderInternal(folderInfo, false); } - - 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) + else + { + SyncFoldersData.Add(threadId, new SyncFolderData { PortalId = portalId, FolderPath = relativePath, Permissions = permissions }); + } + } + + private void RemoveSyncFoldersData(string relativePath) { - // If Folder Mappings are exactly the same - if (sourceFolderMapping.FolderMappingID == destinationFolderMapping.FolderMappingID) + var threadId = Thread.CurrentThread.ManagedThreadId; + if (SyncFoldersData.ContainsKey(threadId)) { - return true; + SyncFoldersData.Remove(threadId); } + } - return IsStandardFolderProviderType(sourceFolderMapping) && IsStandardFolderProviderType(destinationFolderMapping); - } - /// /// This class and its members are reserved for internal use and are not intended to be used in your code. /// internal class MergedTreeItem { public bool ExistsInFileSystem { get; set; } - + public bool ExistsInDatabase { get; set; } - + public bool ExistsInFolderMapping { get; set; } - + public int FolderID { get; set; } - + public int FolderMappingID { get; set; } - + public string FolderPath { get; set; } - + public string MappedPath { get; set; } } @@ -2298,19 +2298,19 @@ public MoveFoldersInfo(string source, string target) this.Source = source; this.Target = target; } - + public string Source { get; private set; } - + public string Target { get; private set; } - } + } } internal class SyncFolderData { public int PortalId { get; set; } - + public string FolderPath { get; set; } - + public FolderPermissionCollection Permissions { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs index 64df51a8011..f53733e1b5d 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingController.cs @@ -18,14 +18,14 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Services.FileSystem.Internal; public class FolderMappingController : ComponentBase, IFolderMappingController - { - private const string CacheKeyPrefix = "GetFolderMappingSettings"; + { + private const string CacheKeyPrefix = "GetFolderMappingSettings"; private static readonly DataProvider dataProvider = DataProvider.Instance(); - + internal FolderMappingController() { - } - + } + public FolderMappingInfo GetDefaultFolderMapping(int portalId) { var defaultFolderMapping = Config.GetSection("dotnetnuke/folder") != null ? @@ -36,7 +36,7 @@ public FolderMappingInfo GetDefaultFolderMapping(int portalId) public int AddFolderMapping(FolderMappingInfo objFolderMapping) { - objFolderMapping.FolderMappingID = dataProvider.AddFolderMapping( + objFolderMapping.FolderMappingID = dataProvider.AddFolderMapping( objFolderMapping.PortalID, objFolderMapping.MappingName, objFolderMapping.FolderProviderType, @@ -102,7 +102,7 @@ public void DeleteFolderMapping(int portalID, int folderMappingID) public void UpdateFolderMapping(FolderMappingInfo objFolderMapping) { - dataProvider.UpdateFolderMapping( + dataProvider.UpdateFolderMapping( objFolderMapping.FolderMappingID, objFolderMapping.MappingName, objFolderMapping.Priority, @@ -130,8 +130,8 @@ public FolderMappingInfo GetFolderMapping(int portalId, string mappingName) public List GetFolderMappings(int portalId) { var cacheKey = string.Format(DataCache.FolderMappingCacheKey, portalId); - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( cacheKey, DataCache.FolderMappingCacheTimeOut, DataCache.FolderMappingCachePriority), @@ -174,14 +174,14 @@ public Hashtable GetFolderMappingSettings(int folderMappingID) { CBO.CloseDataReader(dr, true); } - + var intCacheTimeout = 20 * Convert.ToInt32(Host.PerformanceSetting); DataCache.SetCache(strCacheKey, objSettings, TimeSpan.FromMinutes(intCacheTimeout)); } - + return objSettings; - } - + } + private static void UpdateFolderMappingSettings(FolderMappingInfo objFolderMapping) { foreach (string sKey in objFolderMapping.FolderMappingSettings.Keys) @@ -227,6 +227,6 @@ private static void ClearFolderMappingCache(int portalId) private static void ClearFolderMappingSettingsCache(int folderMappingID) { DataCache.RemoveCache(CacheKeyPrefix + folderMappingID); - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs index 9e7f1bd6338..4f6e0b12023 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingInfo.cs @@ -18,10 +18,10 @@ namespace DotNetNuke.Services.FileSystem [Serializable] public class FolderMappingInfo : IHydratable { - private Hashtable _folderMappingSettings; + private Hashtable _folderMappingSettings; private string _imageUrl; - + public FolderMappingInfo() { this.FolderMappingID = Null.NullInteger; @@ -34,17 +34,7 @@ public FolderMappingInfo(int portalID, string mappingName, string folderProvider this.PortalID = portalID; this.MappingName = mappingName; this.FolderProviderType = folderProviderType; - } - - public int FolderMappingID { get; set; } - - public int PortalID { get; set; } - - public string MappingName { get; set; } - - public string FolderProviderType { get; set; } - - public int Priority { get; set; } + } public Hashtable FolderMappingSettings { @@ -61,11 +51,11 @@ public Hashtable FolderMappingSettings this._folderMappingSettings = FolderMappingController.Instance.GetFolderMappingSettings(this.FolderMappingID); } } - + return this._folderMappingSettings; } } - + public string ImageUrl { get @@ -87,6 +77,16 @@ public bool IsEditable } } + public int FolderMappingID { get; set; } + + public int PortalID { get; set; } + + public string MappingName { get; set; } + + public string FolderProviderType { get; set; } + + public int Priority { get; set; } + public bool SyncAllSubFolders { get @@ -98,12 +98,12 @@ public bool SyncAllSubFolders return true; } - + set { this.FolderMappingSettings["SyncAllSubFolders"] = value; } - } + } /// /// Gets or sets and sets the Key ID. @@ -114,13 +114,13 @@ public int KeyID { return this.FolderMappingID; } - + set { this.FolderMappingID = value; } - } - + } + /// /// Fills a FolderInfo from a Data Reader. /// diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs index 6ed64485396..8f10b460dd2 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderMappingsConfigController.cs @@ -17,26 +17,26 @@ 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"); - + private static readonly string defaultConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); + public FolderMappingsConfigController() { this.FolderMappings = new Dictionary(); this.FolderTypes = new List(); this.LoadConfig(); - } - - public IList FolderTypes { get; internal set; } - + } + public string ConfigNode { get { return configNode; } - } - + } + + public IList FolderTypes { get; internal set; } + private IDictionary FolderMappings { get; set; } - + public void LoadConfig() { try @@ -55,6 +55,34 @@ public void LoadConfig() } } + public void SaveConfig(string folderMappinsSettings) + { + if (!File.Exists(defaultConfigFilePath)) + { + var folderMappingsConfigContent = "<" + this.ConfigNode + ">" + folderMappinsSettings + ""; + File.AppendAllText(defaultConfigFilePath, folderMappingsConfigContent); + var configDocument = new XmlDocument { XmlResolver = null }; + configDocument.LoadXml(folderMappingsConfigContent); + this.FillFolderMappings(configDocument); + this.FillFolderTypes(configDocument); + } + } + + public FolderMappingInfo GetFolderMapping(int portalId, string folderPath) + { + if (!this.FolderMappings.ContainsKey(folderPath)) + { + return null; + } + + return FolderMappingController.Instance.GetFolderMapping(portalId, this.FolderMappings[folderPath]); + } + + protected override Func GetFactory() + { + return () => new FolderMappingsConfigController(); + } + private void FillFolderMappings(XmlDocument configDocument) { var folderMappingsNode = configDocument.SelectSingleNode(this.ConfigNode + "/folderMappings"); @@ -62,7 +90,7 @@ private void FillFolderMappings(XmlDocument configDocument) { return; } - + this.FolderMappings.Clear(); foreach (XmlNode folderMappingNode in folderMappingsNode) { @@ -77,7 +105,7 @@ private void FillFolderTypes(XmlDocument configDocument) { return; } - + this.FolderTypes.Clear(); foreach (XmlNode folderTypeNode in folderTypesNode) { @@ -107,39 +135,11 @@ private FolderTypeConfig GetFolderMappingFromConfigNode(XmlNode node) Encrypt = !string.IsNullOrEmpty(encryptValue) && bool.Parse(encryptValue), }); } - + folderType.Settings = settings; } return folderType; - } - - public void SaveConfig(string folderMappinsSettings) - { - if (!File.Exists(defaultConfigFilePath)) - { - var folderMappingsConfigContent = "<" + this.ConfigNode + ">" + folderMappinsSettings + ""; - File.AppendAllText(defaultConfigFilePath, folderMappingsConfigContent); - var configDocument = new XmlDocument { XmlResolver = null }; - configDocument.LoadXml(folderMappingsConfigContent); - this.FillFolderMappings(configDocument); - this.FillFolderTypes(configDocument); - } - } - - public FolderMappingInfo GetFolderMapping(int portalId, string folderPath) - { - if (!this.FolderMappings.ContainsKey(folderPath)) - { - return null; - } - - return FolderMappingController.Instance.GetFolderMapping(portalId, this.FolderMappings[folderPath]); - } - - protected override Func GetFactory() - { - return () => new FolderMappingsConfigController(); } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs index 3f18891e9b4..fa1d537d6e0 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeConfig.cs @@ -16,11 +16,11 @@ public FolderTypeConfig() { this.Settings = new List(); } - + public string Name { get; set; } - + public string Provider { get; set; } - + public IList Settings { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs index 4571ef3d9c4..ea815056bd9 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/FolderTypeSettingConfig.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Services.FileSystem public class FolderTypeSettingConfig { public string Name { get; set; } - + public string Value { get; set; } - + public bool Encrypt { get; set; } } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs index e0d800f567b..10ed646b561 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingController.cs @@ -10,23 +10,23 @@ namespace DotNetNuke.Services.FileSystem public interface IFolderMappingController { void AddDefaultFolderTypes(int portalId); - + int AddFolderMapping(FolderMappingInfo objFolderMapping); - + void DeleteFolderMapping(int portalId, int folderMappingId); - + FolderMappingInfo GetDefaultFolderMapping(int portalId); - + FolderMappingInfo GetFolderMapping(int folderMappingId); - + FolderMappingInfo GetFolderMapping(int portalId, int folderMappingId); - + FolderMappingInfo GetFolderMapping(int portalId, string mappingName); - + List GetFolderMappings(int portalId); - + Hashtable GetFolderMappingSettings(int folderMappingId); - + void UpdateFolderMapping(FolderMappingInfo objFolderMapping); } } diff --git a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs index f52bf25f616..34a33694218 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderMappings/IFolderMappingsConfigController.cs @@ -36,7 +36,7 @@ public interface IFolderMappingsConfigController /// Gets the folderMapping configured for a specific folder. /// /// Portal Id where the folder is. - /// Specific folder path. + /// Specific folder path. /// FolderMappingInfo GetFolderMapping(int portalId, string folderPath); } diff --git a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs index b9476747ea1..df44a61f342 100644 --- a/DNN Platform/Library/Services/FileSystem/FolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/FolderProvider.cs @@ -22,10 +22,10 @@ namespace DotNetNuke.Services.FileSystem /// Base class that provides common functionallity to work with files and folders. /// public abstract class FolderProvider - { - private const string SettingsControlId = "Settings.ascx"; - private string _providerName; - + { + private const string SettingsControlId = "Settings.ascx"; + private string _providerName; + /// /// Gets a value indicating whether gets a value indicating if the provider ensures the files/folders it manages are secure from outside access. /// @@ -65,10 +65,28 @@ public virtual bool SupportsMappedPaths return false; } } - + + /// + /// Gets a value indicating whether the provider supports the MoveFile method. If a provider supports the MoveFile method, the + /// folder manager does nt have to implement move by copying the file and then deleting the original. + /// + public virtual bool SupportsMoveFile + { + get { return false; } + } + + /// + /// Gets a value indicating whether the provider supports the MoveFolder method. If a provider supports the MoveFolder method, the + /// folder manager does not have to implement move by copying the folder and then deleting the original. + /// + public virtual bool SupportsMoveFolder + { + get { return false; } + } + /// /// Get the list of all the folder providers. - /// + /// /// public static Dictionary GetProviderList() { @@ -84,7 +102,7 @@ public static Dictionary GetProviderList() /// /// Gets an instance of a specific FolderProvider of a given name. - /// + /// /// public static FolderProvider Instance(string friendlyName) { @@ -93,26 +111,8 @@ public static FolderProvider Instance(string 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 - /// folder manager does nt have to implement move by copying the file and then deleting the original. - /// - public virtual bool SupportsMoveFile - { - get { return false; } } - /// - /// Gets a value indicating whether the provider supports the MoveFolder method. If a provider supports the MoveFolder method, the - /// folder manager does not have to implement move by copying the folder and then deleting the original. - /// - public virtual bool SupportsMoveFolder - { - get { return false; } - } - public virtual void AddFolder(string folderPath, FolderMappingInfo folderMapping, string mappedPath) { this.AddFolder(folderPath, folderMapping); @@ -128,11 +128,11 @@ public virtual void CopyFile(string folderPath, string fileName, string newFolde Requires.PropertyNotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) - { - return; - } - + if (folderPath == newFolderPath) + { + return; + } + var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); @@ -154,51 +154,10 @@ 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. - /// + /// /// public virtual Stream GetFileStream(IFolderInfo folder, IFileInfo file, int version) { @@ -295,7 +254,7 @@ public virtual string GetHashCode(IFileInfo file) { currentHashCode = this.GetHashCode(file, fileContent); } - + return currentHashCode; } @@ -321,8 +280,8 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) } return hashText.ToString(); - } - + } + /// /// Adds a new file to the specified folder. /// @@ -348,13 +307,13 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Checks the existence of the specified file in the underlying system. - /// + /// /// public abstract bool FileExists(IFolderInfo folder, string fileName); /// /// Checks the existence of the specified folder in the underlying system. - /// + /// /// public abstract bool FolderExists(string folderPath, FolderMappingInfo folderMapping); @@ -363,61 +322,61 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// /// Because some Providers don't support file attributes, this methods returns a nullable type to allow them to return null. - /// + /// /// public abstract FileAttributes? GetFileAttributes(IFileInfo file); /// /// Gets the list of file names contained in the specified folder. - /// + /// /// public abstract string[] GetFiles(IFolderInfo folder); /// /// Gets the file length. - /// + /// /// public abstract long GetFileSize(IFileInfo file); /// /// Gets a file Stream of the specified file. - /// + /// /// public abstract Stream GetFileStream(IFileInfo file); /// /// Gets a file Stream of the specified file. - /// + /// /// public abstract Stream GetFileStream(IFolderInfo folder, string fileName); /// /// Gets the direct Url to the file. - /// + /// /// public abstract string GetFileUrl(IFileInfo file); /// /// Gets the URL of the image to display in FileManager tree. - /// + /// /// public abstract string GetFolderProviderIconPath(); /// /// Gets the time when the specified file was last modified. - /// + /// /// public abstract DateTime GetLastModificationTime(IFileInfo file); /// /// Gets the list of subfolders for the specified folder. - /// + /// /// public abstract IEnumerable GetSubFolders(string folderPath, FolderMappingInfo folderMapping); /// /// Indicates if the specified file is synchronized. - /// + /// /// public abstract bool IsInSync(IFileInfo file); @@ -438,7 +397,7 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Gets a value indicating if the underlying system supports file attributes. - /// + /// /// public abstract bool SupportsFileAttributes(); @@ -456,6 +415,47 @@ public virtual string GetHashCode(IFileInfo file, Stream fileContent) /// /// Do not close content Stream. /// - public abstract void UpdateFile(IFolderInfo folder, string fileName, Stream content); + public abstract void UpdateFile(IFolderInfo folder, string fileName, Stream content); + + 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 }); + } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs index 9b3d33e87ba..c99137dd4e5 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileContentTypeManager.cs @@ -15,7 +15,7 @@ public interface IFileContentTypeManager /// Gets get all content types dictionary. /// IDictionary ContentTypes { get; } - + /// /// Gets the Content Type for the specified file extension. /// diff --git a/DNN Platform/Library/Services/FileSystem/IFileInfo.cs b/DNN Platform/Library/Services/FileSystem/IFileInfo.cs index ff55f8f9b09..f6254159a9d 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileInfo.cs @@ -11,46 +11,64 @@ namespace DotNetNuke.Services.FileSystem public interface IFileInfo { + string PhysicalPath { get; } + + string RelativePath { get; } + + FileAttributes? FileAttributes { get; } + + bool SupportsFileAttributes { get; } + + /// + /// Gets a value indicating whether the file is enabled, + /// considering if the publish period is active and if the current date is within the publish period. + /// + bool IsEnabled { get; } + + /// + /// Gets a value indicating whether gets a flag which says whether the file has ever been published. + /// + bool HasBeenPublished { get; } + + int CreatedByUserID { get; } + + DateTime CreatedOnDate { get; } + + int LastModifiedByUserID { get; } + + DateTime LastModifiedOnDate { get; } string ContentType { get; set; } - + string Extension { get; set; } - + int FileId { get; set; } - + string FileName { get; set; } - + string Folder { get; set; } - + int FolderId { get; set; } - + int Height { get; set; } - + bool IsCached { get; set; } - - string PhysicalPath { get; } - + int PortalId { get; set; } - - string RelativePath { get; } - + string SHA1Hash { get; set; } - + int Size { get; set; } - + int StorageLocation { get; set; } - + Guid UniqueId { get; set; } - + Guid VersionGuid { get; set; } - + int Width { get; set; } - - FileAttributes? FileAttributes { get; } - - bool SupportsFileAttributes { get; } - + DateTime LastModificationTime { get; set; } - + int FolderMappingID { get; set; } /// @@ -75,12 +93,6 @@ public interface IFileInfo /// DateTime EndDate { get; set; } - /// - /// Gets a value indicating whether the file is enabled, - /// considering if the publish period is active and if the current date is within the publish period. - /// - bool IsEnabled { get; } - /// /// Gets or sets a reference to ContentItem, to use in Workflows. /// @@ -91,21 +103,8 @@ public interface IFileInfo /// int PublishedVersion { get; set; } - /// - /// Gets a value indicating whether gets a flag which says whether the file has ever been published. - /// - bool HasBeenPublished { get; } - - int CreatedByUserID { get; } - - DateTime CreatedOnDate { get; } - - int LastModifiedByUserID { get; } - - DateTime LastModifiedOnDate { get; } - UserInfo CreatedByUser(int portalId); - UserInfo LastModifiedByUser(int portalId); + UserInfo LastModifiedByUser(int portalId); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFileManager.cs b/DNN Platform/Library/Services/FileSystem/IFileManager.cs index bfb39dd8dea..9cea7ceb7f3 100644 --- a/DNN Platform/Library/Services/FileSystem/IFileManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFileManager.cs @@ -19,7 +19,7 @@ public interface IFileManager /// [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. /// diff --git a/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs b/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs index fd29c66643a..30805c039f3 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderInfo.cs @@ -11,37 +11,49 @@ namespace DotNetNuke.Services.FileSystem public interface IFolderInfo { + string FolderName { get; } + + FolderPermissionCollection FolderPermissions { get; } + + string PhysicalPath { get; } + + bool IsStorageSecure { get; } + + /// + /// Gets a value indicating whether the folder has any child subfolder. + /// + bool HasChildren { get; } + + int CreatedByUserID { get; } + + DateTime CreatedOnDate { get; } + + int LastModifiedByUserID { get; } + + DateTime LastModifiedOnDate { get; } string DisplayName { get; set; } - + string DisplayPath { get; set; } - + int FolderID { get; set; } - - string FolderName { get; } - + string FolderPath { get; set; } - - FolderPermissionCollection FolderPermissions { get; } - + bool IsCached { get; set; } - + bool IsProtected { get; set; } - + DateTime LastUpdated { get; set; } - - string PhysicalPath { get; } - + int PortalID { get; set; } - + int StorageLocation { get; set; } - + Guid UniqueId { get; set; } - + Guid VersionGuid { get; set; } - + int FolderMappingID { get; set; } - - bool IsStorageSecure { get; } /// /// Gets or sets a value indicating whether file versions are active for the folder. @@ -63,21 +75,8 @@ public interface IFolderInfo /// string MappedPath { get; set; } - /// - /// Gets a value indicating whether the folder has any child subfolder. - /// - bool HasChildren { get; } - - int CreatedByUserID { get; } - - DateTime CreatedOnDate { get; } - - int LastModifiedByUserID { get; } - - DateTime LastModifiedOnDate { get; } - UserInfo CreatedByUser(int portalId); - UserInfo LastModifiedByUser(int portalId); + UserInfo LastModifiedByUser(int portalId); } } diff --git a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs index 008b1ce6ed9..c2e72cd8d1c 100644 --- a/DNN Platform/Library/Services/FileSystem/IFolderManager.cs +++ b/DNN Platform/Library/Services/FileSystem/IFolderManager.cs @@ -21,7 +21,7 @@ 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. /// @@ -280,8 +280,8 @@ public interface IFolderManager /// /// The folder to update. /// The updated folder. - IFolderInfo UpdateFolder(IFolderInfo folder); - + IFolderInfo UpdateFolder(IFolderInfo folder); + /// /// Moves the specified folder and its contents to a new location. /// @@ -290,6 +290,6 @@ public interface IFolderManager /// 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.")] - IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); + IFolderInfo MoveFolder(IFolderInfo folder, string newFolderPath); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs index e5e8a3fc595..1d966279011 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileDeletionController.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Services.FileSystem.Internal public class FileDeletionController : ServiceLocator, IFileDeletionController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileDeletionController)); - + public void DeleteFile(IFileInfo file) { string lockReason; @@ -55,7 +55,7 @@ public void UnlinkFile(IFileInfo file) this.DeleteFileData(file); } - + public void DeleteFileData(IFileInfo file) { DataProvider.Instance().DeleteFile(file.PortalId, file.FileName, file.FolderId); @@ -69,11 +69,11 @@ protected override Func GetFactory() private void DeleteContentItem(int contentItemId) { - if (contentItemId == Null.NullInteger) - { - return; - } - + if (contentItemId == Null.NullInteger) + { + return; + } + Util.GetContentController().DeleteContentItem(contentItemId); } } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs index 928ca3dc2b3..6dfefe93699 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/FileSecurityController.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Services.FileSystem.Internal public class FileSecurityController : ServiceLocator, IFileSecurityController { private const int BufferSize = 4096; - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FileSecurityController)); public bool Validate(string fileName, Stream fileContent) @@ -73,7 +73,7 @@ private Stream CopyStream(Stream stream) do { filePath = Path.Combine(folderPath, Path.GetRandomFileName()) + ".resx"; - } + } while (File.Exists(filePath)); var fileStream = ((FileManager)FileManager.Instance).GetAutoDeleteFileStream(filePath); diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs index 7f43e92e2be..68d8ab9ccbe 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityChecker.cs @@ -14,7 +14,7 @@ public interface IFileSecurityChecker /// /// Checks if the file has valid content. /// - /// The File Content. + /// The File Content. /// bool Validate(Stream fileContent); } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs index 4cb8ce1f055..587c76f64bf 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/IFileSecurityController.cs @@ -15,7 +15,7 @@ public interface IFileSecurityController /// Checks if the file has valid content. /// /// The File Name. - /// The File Content. + /// The File Content. /// bool Validate(string fileName, Stream fileContent); } diff --git a/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs b/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs index 49c37c06061..3d88f031249 100644 --- a/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs +++ b/DNN Platform/Library/Services/FileSystem/Internal/UserSecurityController.cs @@ -23,7 +23,7 @@ public bool IsHostAdminUser(int portalId, int userId) { return false; } - + var user = UserController.Instance.GetUserById(portalId, userId); return user.IsSuperUser || (portalId > Null.NullInteger && user.IsInRole(PortalController.Instance.GetPortal(portalId).AdministratorRoleName)); } diff --git a/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs b/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs new file mode 100644 index 00000000000..00870040216 --- /dev/null +++ b/DNN Platform/Library/Services/FileSystem/LinkClickPortalSettings.cs @@ -0,0 +1,11 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.FileSystem +{ + internal class LinkClickPortalSettings + { + public string PortalGUID; + public bool EnableUrlLanguage; + } +} diff --git a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs index c69fb304093..8b797d72950 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/DatabaseFolderProvider.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Data; public class DatabaseFolderProvider : SecureFolderProvider - { + { /// /// Clears the content of the file in the database. /// @@ -48,7 +48,7 @@ public static void UpdateFileContent(int fileId, Stream content) { ms.Write(buffer, 0, read); } - + fileContent = ms.ToArray(); } @@ -61,7 +61,25 @@ public static void UpdateFileContent(int fileId, Stream content) 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, byte[] content) + { + if (content != null) + { + DataProvider.Instance().UpdateFileContent(fileId, content); + DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); + } + else + { + ClearFileContent(fileId); + } + } + public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) { Requires.PropertyNotNull("folderPath", folderPath); @@ -69,11 +87,11 @@ public override void CopyFile(string folderPath, string fileName, string newFold Requires.PropertyNotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) - { - return; - } - + if (folderPath == newFolderPath) + { + return; + } + var sourceFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, folderPath); var destinationFolder = FolderManager.Instance.GetFolder(folderMapping.PortalID, newFolderPath); @@ -103,62 +121,6 @@ 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) { @@ -288,30 +250,68 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont var file = FileManager.Instance.GetFile(folder, fileName, true); - if (file == null) - { - return; - } - + if (file == null) + { + return; + } + this.UpdateFileInternal(file.FileId, content); - } + } - /// - /// Updates the content of the file in the database. - /// - /// The file identifier. - /// The new content. - public static void UpdateFileContent(int fileId, byte[] content) + private Stream GetFileStreamInternal(IDataReader dr) { - if (content != null) + byte[] bytes = null; + try { - DataProvider.Instance().UpdateFileContent(fileId, content); - DataProvider.Instance().UpdateFileVersion(fileId, Guid.NewGuid()); + if (dr.Read()) + { + bytes = (byte[])dr["Content"]; + } } - else + finally { - ClearFileContent(fileId); + 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); + } } } diff --git a/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs index c68d704aa8b..c9ed7c30dfb 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/SecureFolderProvider.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Services.FileSystem.Internal; public class SecureFolderProvider : StandardFolderProvider - { + { /// /// Gets the file extension to use for protected files. /// @@ -35,8 +35,8 @@ public override bool IsStorageSecure { return true; } - } - + } + public override string[] GetFiles(IFolderInfo folder) { Requires.NotNull("folder", folder); @@ -49,11 +49,11 @@ public override string[] GetFiles(IFolderInfo folder) if (!fileName.EndsWith(this.ProtectedExtension, StringComparison.InvariantCultureIgnoreCase)) { var destFileName = fileNames[i] + this.ProtectedExtension; - if (FileWrapper.Instance.Exists(destFileName)) - { - FileWrapper.Instance.Delete(destFileName); - } - + if (FileWrapper.Instance.Exists(destFileName)) + { + FileWrapper.Instance.Delete(destFileName); + } + FileWrapper.Instance.Move(fileNames[i], destFileName); } else @@ -75,8 +75,8 @@ public override string GetFileUrl(IFileInfo file) public override string GetFolderProviderIconPath() { return IconControllerWrapper.Instance.IconURL("FolderSecure", "32x32"); - } - + } + protected override string GetActualPath(FolderMappingInfo folderMapping, string folderPath, string fileName) { return base.GetActualPath(folderMapping, folderPath, fileName) + this.ProtectedExtension; @@ -90,6 +90,6 @@ protected override string GetActualPath(IFileInfo file) protected override string GetActualPath(IFolderInfo folder, string fileName) { return base.GetActualPath(folder, fileName) + this.ProtectedExtension; - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs index b603a8e1a24..a33e6c6f5de 100644 --- a/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs +++ b/DNN Platform/Library/Services/FileSystem/Providers/StandardFolderProvider.cs @@ -23,8 +23,8 @@ public class StandardFolderProvider : FolderProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(StandardFolderProvider)); - private static readonly char[] InvalidFileUrlChars = new char[] { '%', ';', '?', ':', '@', '&', '=', '+', '$', ',' }; - + private static readonly char[] InvalidFileUrlChars = new char[] { '%', ';', '?', ':', '@', '&', '=', '+', '$', ',' }; + /// /// Gets a value indicating whether gets a value indicating if the provider requires network connectivity to do its tasks. /// @@ -47,8 +47,8 @@ public override bool SupportsMoveFile public override bool SupportsMoveFolder { get { return true; } - } - + } + public override void CopyFile(string folderPath, string fileName, string newFolderPath, FolderMappingInfo folderMapping) { Requires.PropertyNotNull("folderPath", folderPath); @@ -56,11 +56,11 @@ public override void CopyFile(string folderPath, string fileName, string newFold Requires.PropertyNotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) - { - return; - } - + if (folderPath == newFolderPath) + { + return; + } + var filePath = this.GetActualPath(folderMapping, folderPath, fileName); var newFilePath = this.GetActualPath(folderMapping, newFolderPath, fileName); @@ -186,7 +186,7 @@ public override string GetFileUrl(IFileInfo file) // check if a filename has a character that is not valid for urls if (fullPath.IndexOfAny(InvalidFileUrlChars) >= 0) { - return Globals.LinkClick( + return Globals.LinkClick( $"fileid={file.FileId}", Null.NullInteger, Null.NullInteger, @@ -341,8 +341,8 @@ public override void UpdateFile(IFolderInfo folder, string fileName, Stream cont content.Position = originalPosition; } } - } - + } + internal virtual string GetHash(IFileInfo file) { var fileManager = new FileManager(); @@ -352,8 +352,8 @@ internal virtual string GetHash(IFileInfo file) internal virtual PortalSettings GetPortalSettings(int portalId) { return new PortalSettings(portalId); - } - + } + /// /// Get actual path to a file. /// @@ -438,6 +438,6 @@ protected Stream GetFileStreamInternal(string filePath) protected virtual string GetRelativePath(FolderMappingInfo folderMapping, string path) { return PathUtils.Instance.GetRelativePath(folderMapping.PortalID, path); - } + } } } diff --git a/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs b/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs index c7af66da24d..d7b1627cf4a 100644 --- a/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs +++ b/DNN Platform/Library/Services/FileSystem/SynchronizeFileSystem.cs @@ -52,7 +52,7 @@ private void Synchronize() folderManager.Synchronize(Null.NullInteger); var portals = PortalController.Instance.GetPortals(); - + // Sync Portals for (var intIndex = 0; intIndex <= portals.Count - 1; intIndex++) { diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs index 76da3259450..371cd68450a 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IDirectory.cs @@ -7,15 +7,15 @@ namespace DotNetNuke.Services.FileSystem.Internal public interface IDirectory { void Delete(string path, bool recursive); - + bool Exists(string path); - + string[] GetDirectories(string path); - + string[] GetFiles(string path); - + void Move(string sourceDirName, string destDirName); - + void CreateDirectory(string path); } } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs index 3e04778401b..f5e6de8a1c7 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IFile.cs @@ -10,23 +10,23 @@ namespace DotNetNuke.Services.FileSystem.Internal public interface IFile { Stream Create(string path); - + void Delete(string path); - + bool Exists(string path); - + FileAttributes GetAttributes(string path); - + DateTime GetLastWriteTime(string path); - + void Move(string sourceFileName, string destFileName); - + void Copy(string sourceFileName, string destinationFileName, bool overwrite); - + Stream OpenRead(string path); - + byte[] ReadAllBytes(string path); - + void SetAttributes(string path, FileAttributes fileAttributes); } } diff --git a/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs b/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs index dc45baf98b4..4d8dfab0f3a 100644 --- a/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs +++ b/DNN Platform/Library/Services/FileSystem/Wrappers/IconControllerWrapper.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Services.FileSystem using DotNetNuke.Entities.Icons; internal class IconControllerWrapper : ComponentBase, IIconController - { + { public string IconURL(string key) { return IconController.IconURL(key); @@ -19,6 +19,6 @@ public string IconURL(string key) public string IconURL(string key, string size) { return IconController.IconURL(key, size); - } + } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs index 46a417f85f5..26a0cbd3815 100644 --- a/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/DnnImageHandler.cs @@ -31,7 +31,7 @@ public class DnnImageHandler : ImageHandler /// While list of server folders where the system allow the dnn image handler to /// read to serve image files from it and its subfolders. /// - private static readonly string[] WhiteListFolderPaths = + private static readonly string[] WhiteListFolderPaths = { Globals.DesktopModulePath, Globals.ImagePath, @@ -147,7 +147,7 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) { uid = -1; } - + var uppTrans = new UserProfilePicTransform { UserID = uid, @@ -164,31 +164,31 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) case "placeholder": var placeHolderTrans = new PlaceholderTransform(); int width, height; - if (TryParseDimension(parameters["w"], out width)) - { - placeHolderTrans.Width = width; - } - - if (TryParseDimension(parameters["h"], out height)) - { - placeHolderTrans.Height = height; - } - - if (!string.IsNullOrEmpty(parameters["Color"])) - { - placeHolderTrans.Color = color; - } - - if (!string.IsNullOrEmpty(parameters["Text"])) - { - placeHolderTrans.Text = text; - } - - if (!string.IsNullOrEmpty(parameters["BackColor"])) - { - placeHolderTrans.BackColor = backColor; - } - + if (TryParseDimension(parameters["w"], out width)) + { + placeHolderTrans.Width = width; + } + + if (TryParseDimension(parameters["h"], out height)) + { + placeHolderTrans.Height = height; + } + + if (!string.IsNullOrEmpty(parameters["Color"])) + { + placeHolderTrans.Color = color; + } + + if (!string.IsNullOrEmpty(parameters["Text"])) + { + placeHolderTrans.Text = text; + } + + if (!string.IsNullOrEmpty(parameters["BackColor"])) + { + placeHolderTrans.BackColor = backColor; + } + this.ImageTransforms.Add(placeHolderTrans); break; @@ -202,19 +202,19 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) { return this.GetEmptyImageInfo(); } - + var folder = FolderManager.Instance.GetFolder(file.FolderId); if (!secureFileTrans.DoesHaveReadFolderPermission(folder)) { return this.GetEmptyImageInfo(); } - + this.ContentType = GetImageFormat(file.Extension); secureFileTrans.SecureFile = file; secureFileTrans.EmptyImage = this.EmptyImage; this.ImageTransforms.Add(secureFileTrans); } - + break; case "file": @@ -231,13 +231,13 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) { return this.GetEmptyImageInfo(); } - + imgFile = fullFilePath; } else if (!string.IsNullOrEmpty(parameters["Url"])) { var url = parameters["Url"]; - + // allow only site resources when using the url parameter if (!url.StartsWith("http") || !UriBelongsToSite(new Uri(url))) { @@ -260,10 +260,10 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) string[] parts = parameters["Url"].Split('.'); extension = parts[parts.Length - 1].ToLowerInvariant(); } - + this.ContentType = GetImageFormat(extension); } - + var imageFileTrans = new ImageFileTransform { ImageFilePath = imgFile, ImageUrl = imgUrl }; this.ImageTransforms.Add(imageFileTrans); break; @@ -303,12 +303,12 @@ public override ImageInfo GenerateImage(NameValueCollection parameters) pi.SetValue(imageTransform, parameters[key], null); break; } - + break; } } } - + this.ImageTransforms.Add(imageTransform); break; } @@ -471,7 +471,7 @@ private static string NormalizeFilePath(string filePath) { normalizeFilePath = "/" + normalizeFilePath; } - + return normalizeFilePath; } @@ -496,7 +496,7 @@ private static bool TryParseDimension(string value, out int dimension) dimension = 0; return false; } - + return true; } @@ -524,7 +524,7 @@ private static ImageFormat GetImageFormat(string extension) private static bool UriBelongsToSite(Uri uri) { IEnumerable hostAliases = - from PortalAliasInfo alias in PortalAliasController.Instance.GetPortalAliases().Values + 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 @@ -598,11 +598,11 @@ private void ReadSettings() private void SetupCulture() { var settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings == null) - { - return; - } - + if (settings == null) + { + return; + } + var pageLocale = TestableLocalization.Instance.GetPageLocale(settings); if (pageLocale != null) { diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs index 804aac37bfb..64d2f05124c 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageBrightnessTransform.cs @@ -20,17 +20,17 @@ public ImageBrightnessTransform() this.CompositingQuality = CompositingQuality.HighQuality; this.Brightness = 0; } - - /// - /// Gets or sets the brightness value. Defaultvalue is 0. Range is -255 .. 255. - /// - public int Brightness { get; set; } /// /// Gets provides an Unique String for this class. /// public override string UniqueString => base.UniqueString + "-" + this.Brightness; + /// + /// Gets or sets the brightness value. Defaultvalue is 0. Range is -255 .. 255. + /// + public int Brightness { get; set; } + /// /// Processes an input image applying a brightness image transformation. /// @@ -40,16 +40,16 @@ public override Image ProcessImage(Image image) { var temp = (Bitmap)image; var bmap = (Bitmap)temp.Clone(); - if (this.Brightness < -255) - { - this.Brightness = -255; - } - - if (this.Brightness > 255) - { - this.Brightness = 255; - } - + if (this.Brightness < -255) + { + this.Brightness = -255; + } + + if (this.Brightness > 255) + { + this.Brightness = 255; + } + Color c; for (int i = 0; i < bmap.Width; i++) { @@ -60,40 +60,40 @@ public override Image ProcessImage(Image image) int cG = c.G + this.Brightness; int cB = c.B + this.Brightness; - if (cR < 0) - { - cR = 1; - } - - if (cR > 255) - { - cR = 255; - } - - if (cG < 0) - { - cG = 1; - } - - if (cG > 255) - { - cG = 255; - } - - if (cB < 0) - { - cB = 1; - } - - if (cB > 255) - { - cB = 255; - } - + if (cR < 0) + { + cR = 1; + } + + if (cR > 255) + { + cR = 255; + } + + if (cG < 0) + { + cG = 1; + } + + if (cG > 255) + { + cG = 255; + } + + if (cB < 0) + { + cB = 1; + } + + if (cB > 255) + { + cB = 255; + } + bmap.SetPixel(i, j, Color.FromArgb((byte)cR, (byte)cG, (byte)cB)); } } - + return (Bitmap)bmap.Clone(); } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs index f69e5cc12c1..e5b9290637e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageContrastTransform.cs @@ -20,17 +20,17 @@ public ImageContrastTransform() this.CompositingQuality = CompositingQuality.HighQuality; this.Contrast = 0; } - - /// - /// Gets or sets the contrast value. Defaultvalue is 0. Range is -100 .. 100. - /// - public double Contrast { get; set; } /// /// Gets provides an Unique String for this class. /// public override string UniqueString => base.UniqueString + "-" + this.Contrast; + /// + /// Gets or sets the contrast value. Defaultvalue is 0. Range is -100 .. 100. + /// + public double Contrast { get; set; } + /// /// Processes an input image applying a contrast image transformation. /// @@ -40,16 +40,16 @@ public override Image ProcessImage(Image image) { var temp = (Bitmap)image; var bmap = (Bitmap)temp.Clone(); - if (this.Contrast < -100) - { - this.Contrast = -100; - } - - if (this.Contrast > 100) - { - this.Contrast = 100; - } - + if (this.Contrast < -100) + { + this.Contrast = -100; + } + + if (this.Contrast > 100) + { + this.Contrast = 100; + } + this.Contrast = (100.0 + this.Contrast) / 100.0; this.Contrast *= this.Contrast; Color c; @@ -63,50 +63,50 @@ public override Image ProcessImage(Image image) pR *= this.Contrast; pR += 0.5; pR *= 255; - if (pR < 0) - { - pR = 0; - } - - if (pR > 255) - { - pR = 255; - } - + if (pR < 0) + { + pR = 0; + } + + if (pR > 255) + { + pR = 255; + } + double pG = c.G / 255.0; pG -= 0.5; pG *= this.Contrast; pG += 0.5; pG *= 255; - if (pG < 0) - { - pG = 0; - } - - if (pG > 255) - { - pG = 255; - } - + if (pG < 0) + { + pG = 0; + } + + if (pG > 255) + { + pG = 255; + } + double pB = c.B / 255.0; pB -= 0.5; pB *= this.Contrast; pB += 0.5; pB *= 255; - if (pB < 0) - { - pB = 0; - } - - if (pB > 255) - { - pB = 255; - } - + if (pB < 0) + { + pB = 0; + } + + if (pB > 255) + { + pB = 255; + } + bmap.SetPixel(i, j, Color.FromArgb((byte)pR, (byte)pG, (byte)pB)); } } - + return (Bitmap)bmap.Clone(); } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs index 0078d94d812..aecaa48ebcd 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGammaTransform.cs @@ -21,17 +21,17 @@ public ImageGammaTransform() this.CompositingQuality = CompositingQuality.HighQuality; this.Gamma = 1; } - - /// - /// Gets or sets the gamma value. Defaultvalue is 0. Range is 0.2 .. 5. - /// - public double Gamma { get; set; } /// /// Gets provides an Unique String for this class. /// public override string UniqueString => base.UniqueString + "-" + this.Gamma; + /// + /// Gets or sets the gamma value. Defaultvalue is 0. Range is 0.2 .. 5. + /// + public double Gamma { get; set; } + /// /// Processes an input image applying a gamma image transformation. /// @@ -53,12 +53,12 @@ public override Image ProcessImage(Image image) for (var j = 0; j < bmap.Height; j++) { c = bmap.GetPixel(i, j); - bmap.SetPixel(i, j, Color.FromArgb( + bmap.SetPixel(i, j, Color.FromArgb( gammaArray[c.R], gammaArray[c.G], gammaArray[c.B])); } } - + return (Image)bmap.Clone(); } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs index e61e9904c8b..fc2fb06afb6 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageGreyscaleTransform.cs @@ -40,7 +40,7 @@ public override Image ProcessImage(Image image) bmap.SetPixel(i, j, Color.FromArgb(gray, gray, gray)); } } - + return (Bitmap)bmap.Clone(); } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs index b93c81c8f2f..db5e54f3752 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageInvertTransform.cs @@ -38,7 +38,7 @@ public override Image ProcessImage(Image image) bmap.SetPixel(i, j, Color.FromArgb(255 - c.R, 255 - c.G, 255 - c.B)); } } - + return (Bitmap)bmap.Clone(); } } diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs index 70ee838dc0c..002e1c54f84 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageResizeTransform.cs @@ -15,13 +15,13 @@ namespace DotNetNuke.Services.GeneratedImage.FilterTransform /// public class ImageResizeTransform : ImageTransform { - private int _width; - private int _height; - private int _border; - private int _maxWidth; + private int _width; + private int _height; + private int _border; + private int _maxWidth; private int _maxHeight; - public ImageResizeTransform() + public ImageResizeTransform() { this.InterpolationMode = InterpolationMode.HighQualityBicubic; this.SmoothingMode = SmoothingMode.HighQuality; @@ -30,6 +30,12 @@ public ImageResizeTransform() 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; + /// /// Gets or sets the resize mode. The default value is Fit. /// @@ -38,13 +44,13 @@ public ImageResizeTransform() /// /// Gets or sets the width of the resulting image. /// - public int Width + public int Width { get { return this._width; } - + set { CheckValue(value); @@ -61,7 +67,7 @@ public int MaxWidth { return this._maxWidth; } - + set { CheckValue(value); @@ -72,14 +78,14 @@ public int MaxWidth /// /// Gets or sets the height of the resulting image. /// - public int Height + public int Height { - get + get { return this._height; } - - set + + set { CheckValue(value); this._height = value; @@ -95,7 +101,7 @@ public int MaxHeight { return this._maxHeight; } - + set { CheckValue(value); @@ -112,7 +118,7 @@ public int Border { return this._border; } - + set { CheckValue(value); @@ -125,12 +131,6 @@ public int Border /// public Color BackColor { get; set; } = Color.White; - /// - /// 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. /// @@ -138,11 +138,11 @@ public int Border /// Image result after image transformation. public override Image ProcessImage(Image image) { - if (image == null) - { - return null; - } - + if (image == null) + { + return null; + } + if (this.MaxWidth > 0) { this.Width = image.Width > this.MaxWidth ? this.MaxWidth : image.Width; @@ -157,7 +157,7 @@ public override Image ProcessImage(Image image) int scaledWidth = (int)(image.Width * ((float)this.Height / (float)image.Height)); Image procImage; - switch (this.Mode) + switch (this.Mode) { case ImageResizeMode.Fit: procImage = this.FitImage(image, scaledHeight, scaledWidth); @@ -175,11 +175,11 @@ public override Image ProcessImage(Image image) Debug.Fail("Should not reach this"); return null; } - + return procImage; } - public override string ToString() + public override string ToString() { return "ImageResizeTransform"; } @@ -192,28 +192,28 @@ private static void CheckValue(int value) } } - private Image FitImage(Image img, int scaledHeight, int scaledWidth) + private Image FitImage(Image img, int scaledHeight, int scaledWidth) { int resizeWidth; int resizeHeight; - if (this.Height == 0) + if (this.Height == 0) { resizeWidth = this.Width; resizeHeight = scaledHeight; } - else if (this.Width == 0) + else if (this.Width == 0) { resizeWidth = scaledWidth; resizeHeight = this.Height; } - else + else { - if ((float)this.Width / (float)img.Width < this.Height / (float)img.Height) + if ((float)this.Width / (float)img.Width < this.Height / (float)img.Height) { resizeWidth = this.Width; resizeHeight = scaledHeight; } - else + else { resizeWidth = scaledWidth; resizeHeight = this.Height; @@ -265,11 +265,11 @@ private Image FitSquareImage(Image img) return newimage; } - private Image CropImage(Image img, int scaledHeight, int scaledWidth) + private Image CropImage(Image img, int scaledHeight, int scaledWidth) { int resizeWidth; int resizeHeight; - if ((float)this.Width / (float)img.Width > this.Height / (float)img.Height) + if ((float)this.Width / (float)img.Width > this.Height / (float)img.Height) { resizeWidth = this.Width; resizeHeight = scaledHeight; diff --git a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs index b35f5c7cb05..1dd77c68ae3 100644 --- a/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/FilterTransform/ImageRotateFlipTransform.cs @@ -20,17 +20,17 @@ public ImageRotateFlipTransform() this.CompositingQuality = CompositingQuality.HighQuality; this.RotateFlip = RotateFlipType.RotateNoneFlipNone; } - - /// - /// Gets or sets the type of rotation / flip . Defaultvalue is RotateNoneFlipNone. - /// - public RotateFlipType RotateFlip { get; set; } /// /// Gets provides an Unique String for this transformation. /// public override string UniqueString => base.UniqueString + "-" + this.RotateFlip; + /// + /// Gets or sets the type of rotation / flip . Defaultvalue is RotateNoneFlipNone. + /// + public RotateFlipType RotateFlip { get; set; } + /// /// 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 c56e9f1ba7d..39f3beedb44 100644 --- a/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs +++ b/DNN Platform/Library/Services/GeneratedImage/GeneratedImage.cs @@ -14,9 +14,9 @@ namespace DotNetNuke.Services.GeneratedImage public class GeneratedImage : Image { private const string TimestampField = "__timestamp"; - private string _timestamp; private readonly Control _bindingContainer; private readonly HttpContextBase _context; + private string _timestamp; private string _imageHandlerUrl; public GeneratedImage() @@ -24,20 +24,22 @@ public GeneratedImage() this.Parameters = new List(); } - internal GeneratedImage(HttpContextBase context, Control bindingContainer) + internal GeneratedImage(HttpContextBase context, Control bindingContainer) : this() { this._context = context; this._bindingContainer = bindingContainer; } + public List Parameters { get; } + public string ImageHandlerUrl { get { return this._imageHandlerUrl ?? string.Empty; } - + set { this._imageHandlerUrl = value; @@ -50,15 +52,13 @@ public string Timestamp { return this._timestamp ?? string.Empty; } - + set { this._timestamp = value; } } - public List Parameters { get; } - private new HttpContextBase Context => this._context ?? new HttpContextWrapper(HttpContext.Current); private new Control BindingContainer => this._bindingContainer ?? base.BindingContainer; diff --git a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs index efb376bdef9..90cb5edd127 100644 --- a/DNN Platform/Library/Services/GeneratedImage/IPCount.cs +++ b/DNN Platform/Library/Services/GeneratedImage/IPCount.cs @@ -19,11 +19,11 @@ public class IPCount { private const string TempFileExtension = ".tmp"; private const string CacheAppRelativePath = @"~\App_Data\_ipcount\"; - private static string _cachePath; private static readonly object PurgeQueuedLock = new object(); + private static readonly object FileLock = new object(); + private static string _cachePath; private static bool _purgeQueued; private static TimeSpan _purgeInterval; - private static readonly object FileLock = new object(); static IPCount() { @@ -35,19 +35,19 @@ static IPCount() public static string CachePath { get { return _cachePath; } - + set { if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException(nameof(value)); } - + if (!Directory.Exists(value)) { Directory.CreateDirectory(value); } - + _cachePath = value; } } @@ -58,19 +58,19 @@ public static TimeSpan PurgeInterval { return _purgeInterval; } - + set { if (value == null) { throw new ArgumentNullException(nameof(value)); } - + if (value.Ticks < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } - + _purgeInterval = value; } } @@ -91,10 +91,10 @@ private static DateTime LastPurge { File.WriteAllText(CachePath + "_lastpurge", string.Empty); } - + return lastPurge; } - + set { File.WriteAllText(CachePath + "_lastpurge", string.Empty); @@ -129,7 +129,7 @@ public static bool CheckIp(string ipAddress) } } } - + Thread.Sleep(0); foreach (var fileinfo in toTryDeleteAgain) { @@ -142,7 +142,7 @@ public static bool CheckIp(string ipAddress) // do nothing at this point, try to delete file during next purge } } - + LastPurge = DateTime.Now; _purgeQueued = false; @@ -159,15 +159,15 @@ public static bool CheckIp(string ipAddress) var strCount = File.ReadAllText(path); if (int.TryParse(strCount, out count)) { - if (count > MaxCount) - { - return false; - } - + if (count > MaxCount) + { + return false; + } + count++; } } - + File.WriteAllText(path, count.ToString()); return true; } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs index cfbebcb8013..ba931898e0e 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandler.cs @@ -20,7 +20,7 @@ internal ImageHandler(IImageStore imageStore, DateTime now) : this(new ImageHandlerInternal(imageStore, now)) { } - + protected ImageHandler() : this(new ImageHandlerInternal()) { @@ -31,6 +31,8 @@ private ImageHandler(ImageHandlerInternal implementation) this.Implementation = implementation; } + public virtual bool IsReusable => false; + /// /// Gets or sets a value indicating whether enables server-side caching of the result. /// @@ -48,8 +50,6 @@ 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. @@ -127,13 +127,13 @@ 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; + private ImageHandlerInternal Implementation { get; set; } + public abstract ImageInfo GenerateImage(NameValueCollection parameters); public void ProcessRequest(HttpContext context) @@ -142,7 +142,7 @@ public void ProcessRequest(HttpContext context) { throw new ArgumentNullException(nameof(context)); } - + HttpContextBase contextWrapper = new HttpContextWrapper(context); this.ProcessRequest(contextWrapper); } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs index f9193940ef2..4f8bc7ec5f2 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageHandlerInternal.cs @@ -53,14 +53,14 @@ public TimeSpan ClientCacheExpiration { return this._clientCacheExpiration; } - + set { if (value.Ticks < 0) { throw new ArgumentOutOfRangeException(nameof(value), "ClientCacheExpiration must be positive"); } - + this._clientCacheExpiration = value; this.EnableClientCache = true; } @@ -82,22 +82,6 @@ public TimeSpan IpCountPurgeInterval set { IPCount.PurgeInterval = value; } } - private DateTime DateTime_Now - { - get - { - return this._now ?? DateTime.Now; - } - } - - private IImageStore ImageStore - { - get - { - return this._imageStore ?? DiskImageStore.Instance; - } - } - public bool EnableClientCache { get; set; } public bool EnableServerCache { get; set; } @@ -116,6 +100,22 @@ public List ImageTransforms private set; } + private DateTime DateTime_Now + { + get + { + return this._now ?? DateTime.Now; + } + } + + private IImageStore ImageStore + { + get + { + return this._imageStore ?? DiskImageStore.Instance; + } + } + public void HandleImageRequest(HttpContextBase context, Func imageGenCallback, string uniqueIdStringSeed) { context.Response.Clear(); @@ -139,7 +139,7 @@ public void HandleImageRequest(HttpContextBase context, Func userIds; - if ((userIds = DataCache.GetCache>(cacheKey)) == null || !userIds.ContainsKey(userId)) - { - return false; - } - + if ((userIds = DataCache.GetCache>(cacheKey)) == null || !userIds.ContainsKey(userId)) + { + return false; + } + this.ImageStore.ForcePurgeFromServerCache(cacheId); DateTime expiry; - + // The clear mechanism is performed for ClientCacheExpiration timespan so that all active clients clears the cache and don't see old data. - if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(this.ClientCacheExpiration)) - { - return true; - } - - // Remove the userId from the clear list when timespan is > ClientCacheExpiration. + if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(this.ClientCacheExpiration)) + { + return true; + } + + // Remove the userId from the clear list when timespan is > ClientCacheExpiration. userIds.Remove(userId); DataCache.SetCache(cacheKey, userIds); return true; diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs index 09ff6e9de40..4dc342dea52 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageInfo.cs @@ -24,7 +24,7 @@ public ImageInfo(Image image) { throw new ArgumentNullException(nameof(image)); } - + this.Image = image; } @@ -34,10 +34,10 @@ public ImageInfo(byte[] imageBuffer) { throw new ArgumentNullException(nameof(imageBuffer)); } - + this.ImageByteBuffer = imageBuffer; } - + /// /// Gets image. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs index 3315f1499f8..3e99ddc3c5f 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageParameter.cs @@ -20,11 +20,11 @@ public class ImageParameter : IDataBindingsAccessor public string Value { get; set; } - public Control BindingContainer { get; internal set; } - + public Control BindingContainer { get; internal set; } + DataBindingCollection IDataBindingsAccessor.DataBindings => this._dataBindings; - bool IDataBindingsAccessor.HasDataBindings => this._dataBindings.Count != 0; + bool IDataBindingsAccessor.HasDataBindings => this._dataBindings.Count != 0; public override string ToString() { @@ -32,7 +32,7 @@ public override string ToString() { return base.ToString(); } - + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", this.Name, this.Value); } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs index a68a3e0b919..0264d14a623 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/GrayscaleQuantizer.cs @@ -13,15 +13,15 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization /// [CLSCompliant(false)] public class GrayscaleQuantizer : PaletteQuantizer - { - /// + { + /// /// Initializes a new instance of the class. /// Construct the palette quantizer. /// /// /// Palette quantization only requires a single quantization step. /// - public GrayscaleQuantizer() + public GrayscaleQuantizer() : base(new ArrayList()) { this._colors = new Color[256]; @@ -44,7 +44,7 @@ public GrayscaleQuantizer() // Otherwise, use your favorite color reduction algorithm // and an optimum palette for that algorithm generated here. // For example, a color histogram, or a median cut palette. - this._colors[i] = Color.FromArgb( + this._colors[i] = Color.FromArgb( (int)Alpha, (int)intensity, (int)intensity, diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs index fffe4e09aeb..877f6502f73 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/OctreeQuantizer.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization /// Quantize using an Octree. /// public class OctreeQuantizer : Quantizer - { + { /// /// Stores the tree. /// @@ -23,8 +23,8 @@ public class OctreeQuantizer : Quantizer /// Maximum allowed color depth. /// private int _maxColors; - - /// + + /// /// Initializes a new instance of the class. /// Construct the octree quantizer. /// @@ -34,20 +34,20 @@ public class OctreeQuantizer : Quantizer /// /// The maximum number of colors to return. /// The number of significant bits. - public OctreeQuantizer(int maxColors, int maxColorBits) + public OctreeQuantizer(int maxColors, int maxColorBits) : base(false) { - if (maxColors > 255) - { - throw new ArgumentOutOfRangeException(nameof(maxColors), maxColors, "The number of colors should be less than 256"); - } - - if ((maxColorBits < 1) | (maxColorBits > 8)) - { - throw new ArgumentOutOfRangeException(nameof(maxColorBits), maxColorBits, "This should be between 1 and 8"); - } - - // Construct the octree + if (maxColors > 255) + { + throw new ArgumentOutOfRangeException(nameof(maxColors), maxColors, "The number of colors should be less than 256"); + } + + if ((maxColorBits < 1) | (maxColorBits > 8)) + { + throw new ArgumentOutOfRangeException(nameof(maxColorBits), maxColorBits, "This should be between 1 and 8"); + } + + // Construct the octree this._octree = new Octree(maxColorBits); this._maxColors = maxColors; } @@ -74,13 +74,13 @@ protected override void InitialQuantizePixel(Color32 pixel) protected override byte QuantizePixel(Color32 pixel) { 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) - { - paletteIndex = (byte)this._octree.GetPaletteIndex(pixel); - } - + if (pixel.Alpha > 0) + { + paletteIndex = (byte)this._octree.GetPaletteIndex(pixel); + } + return paletteIndex; } @@ -95,12 +95,12 @@ protected override ColorPalette GetPalette(ColorPalette original) ArrayList palette = this._octree.Palletize(this._maxColors - 1); // Then convert the palette based on those colors - for (int index = 0; index < palette.Count; index++) - { - original.Entries[index] = (Color)palette[index]; - } - - // Add the transparent color + for (int index = 0; index < palette.Count; index++) + { + original.Entries[index] = (Color)palette[index]; + } + + // Add the transparent color original.Entries[this._maxColors] = Color.FromArgb(0, 0, 0, 0); return original; @@ -110,7 +110,7 @@ protected override ColorPalette GetPalette(ColorPalette original) /// Class which does the actual quantization. /// private class Octree - { + { /// /// Mask used when getting the appropriate pixels for a given node. /// @@ -125,8 +125,28 @@ private class Octree /// Number of leaves in the tree. /// private int _leafCount; - - /// + + /// + /// Array of reducible nodes. + /// + private OctreeNode[] _reducibleNodes; + + /// + /// Maximum number of significant bits in the image. + /// + private int _maxColorBits; + + /// + /// Store the last node quantized. + /// + private OctreeNode _previousNode; + + /// + /// Cache the previous color quantized. + /// + private int _previousColor; + + /// /// Initializes a new instance of the class. /// Construct the octree. /// @@ -174,12 +194,12 @@ public void AddColor(Color32 pixel) this._previousColor = pixel.ARGB; this._root.AddColor(pixel, this._maxColorBits, 0, this); } - else - { - - // Just update the previous node - this._previousNode.Increment(pixel); - } + else + { + + // Just update the previous node + this._previousNode.Increment(pixel); + } } else { @@ -196,8 +216,8 @@ public void Reduce() int index; // Find the deepest level containing at least one reducible node - for (index = this._maxColorBits - 1; (index > 0) && (this._reducibleNodes[index] == null); index--) - { + for (index = this._maxColorBits - 1; (index > 0) && (this._reducibleNodes[index] == null); index--) + { } // Reduce the node most recently added to the list at level 'index' @@ -206,7 +226,7 @@ public void Reduce() // Decrement the leaf count after reducing the node this._leafCount -= node.Reduce(); - + // And just in case I've reduced the last color to be added, and the next color to // be added is the same, invalidate the previousNode... this._previousNode = null; @@ -219,12 +239,12 @@ public void Reduce() /// An arraylist with the palettized colors. public ArrayList Palletize(int colorCount) { - while (this.Leaves > colorCount) - { - this.Reduce(); - } - - // Now palettize the nodes + while (this.Leaves > colorCount) + { + this.Reduce(); + } + + // Now palettize the nodes ArrayList palette = new ArrayList(this.Leaves); int paletteIndex = 0; this._root.ConstructPalette(palette, ref paletteIndex); @@ -252,31 +272,11 @@ protected void TrackPrevious(OctreeNode node) this._previousNode = node; } - /// - /// Array of reducible nodes. - /// - private OctreeNode[] _reducibleNodes; - - /// - /// Maximum number of significant bits in the image. - /// - private int _maxColorBits; - - /// - /// Store the last node quantized. - /// - private OctreeNode _previousNode; - - /// - /// Cache the previous color quantized. - /// - private int _previousColor; - /// /// Class which encapsulates each node in the tree. /// protected class OctreeNode - { + { /// /// Flag indicating that this is a leaf node. /// @@ -291,8 +291,33 @@ protected class OctreeNode /// Red component. /// private int _red; - - /// + + /// + /// Green Component. + /// + private int _green; + + /// + /// Blue component. + /// + private int _blue; + + /// + /// Pointers to any child nodes. + /// + private OctreeNode[] _children; + + /// + /// Pointer to next reducible node. + /// + private OctreeNode _nextReducible; + + /// + /// The index of this node in the palette. + /// + private int _paletteIndex; + + /// /// Initializes a new instance of the class. /// Construct the node. /// @@ -324,20 +349,20 @@ public OctreeNode(int level, int colorBits, Octree octree) } /// - /// Gets or sets get/Set the next reducible node. + /// Gets return the child nodes. /// - public OctreeNode NextReducible + public OctreeNode[] Children { - get { return this._nextReducible; } - set { this._nextReducible = value; } + get { return this._children; } } /// - /// Gets return the child nodes. + /// Gets or sets get/Set the next reducible node. /// - public OctreeNode[] Children + public OctreeNode NextReducible { - get { return this._children; } + get { return this._nextReducible; } + set { this._nextReducible = value; } } /// @@ -353,7 +378,7 @@ public void AddColor(Color32 pixel, int colorBits, int level, Octree octree) if (this._leaf) { this.Increment(pixel); - + // Setup the previous node octree.TrackPrevious(this); } @@ -429,10 +454,10 @@ public void ConstructPalette(ArrayList palette, ref int paletteIndex) // Loop through children looking for leaves for (int index = 0; index < 8; index++) { - if (this._children[index] != null) - { - this._children[index].ConstructPalette(palette, ref paletteIndex); - } + if (this._children[index] != null) + { + this._children[index].ConstructPalette(palette, ref paletteIndex); + } } } } @@ -451,14 +476,14 @@ public int GetPaletteIndex(Color32 pixel, int level) ((pixel.Green & mask[level]) >> (shift - 1)) | ((pixel.Blue & mask[level]) >> shift); - if (this._children[index] != null) - { - paletteIndex = this._children[index].GetPaletteIndex(pixel, level + 1); - } - else - { - throw new Exception("Didn't expect this!"); - } + if (this._children[index] != null) + { + paletteIndex = this._children[index].GetPaletteIndex(pixel, level + 1); + } + else + { + throw new Exception("Didn't expect this!"); + } } return paletteIndex; @@ -474,31 +499,6 @@ public void Increment(Color32 pixel) this._green += pixel.Green; this._blue += pixel.Blue; } - - /// - /// Green Component. - /// - private int _green; - - /// - /// Blue component. - /// - private int _blue; - - /// - /// Pointers to any child nodes. - /// - private OctreeNode[] _children; - - /// - /// Pointer to next reducible node. - /// - private OctreeNode _nextReducible; - - /// - /// The index of this node in the palette. - /// - private int _paletteIndex; } } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs index d409710242a..ccfd9440a1f 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/PaletteQuantizer.cs @@ -14,18 +14,18 @@ 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. /// @@ -33,7 +33,7 @@ public class PaletteQuantizer : Quantizer /// /// Palette quantization only requires a single quantization step. /// - public PaletteQuantizer(ArrayList palette) + public PaletteQuantizer(ArrayList palette) : base(true) { this._colorMap = new Hashtable(); @@ -53,10 +53,10 @@ protected override byte QuantizePixel(Color32 pixel) int colorHash = pixel.ARGB; // Check if the color is in the lookup table - if (this._colorMap.ContainsKey(colorHash)) - { - colorIndex = (byte)this._colorMap[colorHash]; - } + if (this._colorMap.ContainsKey(colorHash)) + { + colorIndex = (byte)this._colorMap[colorHash]; + } else { // Not found - loop through the palette and find the nearest match. @@ -100,10 +100,10 @@ protected override byte QuantizePixel(Color32 pixel) leastDistance = distance; // And if it's an exact match, exit the loop - if (distance == 0) - { - break; - } + if (distance == 0) + { + break; + } } } } @@ -122,11 +122,11 @@ protected override byte QuantizePixel(Color32 pixel) /// The new color palette. protected override ColorPalette GetPalette(ColorPalette palette) { - for (int index = 0; index < this._colors.Length; index++) - { - palette.Entries[index] = this._colors[index]; - } - + for (int index = 0; index < this._colors.Length; index++) + { + palette.Entries[index] = this._colors[index]; + } + return palette; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs index 1ba2d5f5408..f960879cb4b 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageQuantization/Quantizer.cs @@ -13,14 +13,15 @@ namespace DotNetNuke.Services.GeneratedImage.ImageQuantization /// Abstarct class for Quantizers. /// 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. /// @@ -73,19 +74,19 @@ public Bitmap Quantize(Image source) { // Get the source image bits and lock into memory sourceData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - + // Call the FirstPass function if not a single pass algorithm. // For something like an octree quantizer, this will run through // all image pixels, build a data structure, and create a palette. - if (!this._singlePass) - { - this.FirstPass(sourceData, width, height); - } - - // Then set the color palette on the output bitmap. I'm passing in the current palette - // as there's no way to construct a new, empty palette. + if (!this._singlePass) + { + this.FirstPass(sourceData, width, height); + } + + // Then set the color palette on the output bitmap. I'm passing in the current palette + // as there's no way to construct a new, empty palette. output.Palette = this.GetPalette(output.Palette); - + // Then call the second pass which actually does the conversion this.SecondPass(sourceData, output, width, height, bounds); } @@ -248,24 +249,19 @@ public struct Color32 /// [FieldOffset(0)] public byte Blue; - + /// /// Holds the green component of the colour. /// [FieldOffset(1)] public byte Green; - + /// /// Holds the red component of the colour. /// [FieldOffset(2)] public byte Red; - - public Color32(IntPtr pSourcePixel) - { - this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); - } - + /// /// Holds the alpha component of the colour. /// @@ -278,6 +274,11 @@ public Color32(IntPtr pSourcePixel) [FieldOffset(0)] public int ARGB; + public Color32(IntPtr pSourcePixel) + { + this = (Color32)Marshal.PtrToStructure(pSourcePixel, typeof(Color32)); + } + /// /// Gets return the color for this Color32 object. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs index 79b2f42684e..bec0a690353 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ImageTransform.cs @@ -14,6 +14,13 @@ namespace DotNetNuke.Services.GeneratedImage /// public abstract class ImageTransform { + // REVIEW: should this property be abstract? + + /// + /// Gets provides an Unique String for the image transformation. + /// + public virtual string UniqueString => this.GetType().FullName; + /// /// Gets or sets the interpolation mode used for resizing images. The default is HighQualityBicubic. /// @@ -34,13 +41,6 @@ public abstract class ImageTransform /// public CompositingQuality CompositingQuality { get; set; } - // REVIEW: should this property be abstract? - - /// - /// Gets provides an Unique String for the image transformation. - /// - public virtual string UniqueString => this.GetType().FullName; - /// /// Process an input image applying the image transformation. /// @@ -66,7 +66,7 @@ public virtual Bitmap CopyImage(Stream imgStream) graph.SmoothingMode = this.SmoothingMode; graph.DrawImage(srcImage, new Rectangle(0, 0, srcImage.Width, srcImage.Height)); } - + return destImage; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs index e5d3b2c2f84..365296241d0 100644 --- a/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs +++ b/DNN Platform/Library/Services/GeneratedImage/ProfileEventHandler.cs @@ -26,12 +26,12 @@ public class ProfileEventHandler : IProfileEventHandlers /// public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) { - if (profileArgs?.User == null || profileArgs.OldProfile == null) - { - return; - } - - // extract old and new user profile from args and clear both client and server caching + if (profileArgs?.User == null || profileArgs.OldProfile == null) + { + return; + } + + // extract old and new user profile from args and clear both client and server caching var user = profileArgs.User; var newProfile = user.Profile; var oldProfile = profileArgs.OldProfile; @@ -41,17 +41,17 @@ public void ProfileUpdated(object sender, ProfileEventArgs profileArgs) { var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, user.PortalID); Dictionary userIds; - if ((userIds = DataCache.GetCache>(cacheKey)) == null) - { - userIds = new Dictionary(); - } - - // Add the userid to the clear cache list, if not already in the list. - if (userIds.ContainsKey(user.UserID)) - { - userIds.Remove(user.UserID); - } - + if ((userIds = DataCache.GetCache>(cacheKey)) == null) + { + userIds = new Dictionary(); + } + + // Add the userid to the clear cache list, if not already in the list. + if (userIds.ContainsKey(user.UserID)) + { + userIds.Remove(user.UserID); + } + userIds.Add(user.UserID, DateTime.UtcNow); DataCache.SetCache(cacheKey, userIds); } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs index 15124734152..3568e0c9135 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/ImageFileTransform.cs @@ -22,7 +22,12 @@ public ImageFileTransform() this.PixelOffsetMode = PixelOffsetMode.HighQuality; this.CompositingQuality = CompositingQuality.HighQuality; } - + + /// + /// Gets provides an Unique String for the image transformation. + /// + public override string UniqueString => base.UniqueString + "-" + this.ImageFilePath + this.ImageUrl; + /// /// Gets or sets file path of the image. /// @@ -38,11 +43,6 @@ public ImageFileTransform() /// public Image EmptyImage { get; set; } - /// - /// Gets provides an Unique String for the image transformation. - /// - public override string UniqueString => base.UniqueString + "-" + this.ImageFilePath + this.ImageUrl; - /// /// 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 7646776f675..f48c1c02c9d 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/PlaceHolderTransform.cs @@ -25,7 +25,12 @@ public PlaceholderTransform() this.Height = 0; this.Text = string.Empty; } - + + /// + /// Gets provides an Unique String for the image transformation. + /// + public override string UniqueString => base.UniqueString + this.Width + "-" + this.Height + "-" + this.Color + "-" + this.BackColor + "-" + this.Text; + /// /// Gets or sets the width of the placeholder image. /// @@ -51,11 +56,6 @@ public PlaceholderTransform() /// public string Text { get; set; } - /// - /// Gets provides an Unique String for the image transformation. - /// - public override string UniqueString => base.UniqueString + this.Width + "-" + this.Height + "-" + this.Color + "-" + this.BackColor + "-" + this.Text; - /// /// Processes an input image returning a placeholder image. /// @@ -64,16 +64,16 @@ public PlaceholderTransform() public override Image ProcessImage(Image image) { // Check dimensions - if (this.Width == 0 && this.Height > 0) - { - this.Width = this.Height; - } - - if (this.Width > 0 && this.Height == 0) - { - this.Height = this.Width; - } - + if (this.Width == 0 && this.Height > 0) + { + this.Width = this.Height; + } + + if (this.Width > 0 && this.Height == 0) + { + this.Height = this.Width; + } + var bitmap = new Bitmap(this.Width, this.Height); Brush backColorBrush = new SolidBrush(this.BackColor); Brush colorBrush = new SolidBrush(this.Color); @@ -95,29 +95,29 @@ public override Image ProcessImage(Image image) // Determine fontsize var fontSize = 13; - if (this.Width < 101) - { - fontSize = 8; - } - else if (this.Width < 151) - { - fontSize = 10; - } - else if (this.Width < 201) - { - fontSize = 12; - } - else if (this.Width < 301) - { - fontSize = 14; - } - else - { - fontSize = 24; - } - - // Draw text on image - // Use rectangle for text and align text to center of rectangle + if (this.Width < 101) + { + fontSize = 8; + } + else if (this.Width < 151) + { + fontSize = 10; + } + else if (this.Width < 201) + { + fontSize = 12; + } + else if (this.Width < 301) + { + fontSize = 14; + } + else + { + fontSize = 24; + } + + // Draw text on image + // Use rectangle for text and align text to center of rectangle var font = new Font("Arial", fontSize, FontStyle.Bold); var stringFormat = new StringFormat { @@ -131,7 +131,7 @@ public override Image ProcessImage(Image image) // Save indicator to file objGraphics.Flush(); } - + return bitmap; } } diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs index cb98960fb1e..bab3b0cfc7a 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/SecureFileTransform.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// Secure File ImageTransform class. /// public class SecureFileTransform : ImageTransform - { + { public SecureFileTransform() { this.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -26,7 +26,12 @@ public SecureFileTransform() this.PixelOffsetMode = PixelOffsetMode.HighQuality; this.CompositingQuality = CompositingQuality.HighQuality; } - + + /// + /// Gets provides an Unique String for the image transformation. + /// + public override string UniqueString => base.UniqueString + this.SecureFile.FileId; + /// /// Gets or sets set IFileInfo object of given FileId. /// @@ -37,11 +42,6 @@ public SecureFileTransform() /// public Image EmptyImage { get; set; } - /// - /// Gets provides an Unique String for the image transformation. - /// - public override string UniqueString => base.UniqueString + this.SecureFile.FileId; - /// /// Processes an input image returing a secure file image. /// diff --git a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs index 12d8237a7d0..cd3c226af39 100644 --- a/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs +++ b/DNN Platform/Library/Services/GeneratedImage/StartTransform/UserProfilePicTransform.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Services.GeneratedImage.StartTransform /// User Profile Picture ImageTransform class. /// public class UserProfilePicTransform : ImageTransform - { + { public UserProfilePicTransform() { this.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -27,11 +27,6 @@ public UserProfilePicTransform() this.PixelOffsetMode = PixelOffsetMode.HighQuality; this.CompositingQuality = CompositingQuality.HighQuality; } - - /// - /// Gets or sets the UserID of the profile pic. - /// - public int UserID { get; set; } /// /// Gets provides an Unique String for the image transformation. @@ -41,7 +36,12 @@ public UserProfilePicTransform() /// /// Gets a value indicating whether is reusable. /// - public bool IsReusable => false; + public bool IsReusable => false; + + /// + /// Gets or sets the UserID of the profile pic. + /// + public int UserID { get; set; } /// /// Processes an input image returning the user profile picture. @@ -64,7 +64,7 @@ public override Image ProcessImage(Image image) return this.CopyImage(content); } } - + return this.GetNoAvatarImage(); } diff --git a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs index 6fa2ed401a5..256ec995211 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/BeaconService.cs @@ -41,7 +41,7 @@ public string GetBeaconEndpoint() : ep; #endif } - + return this._beaconEndpoint; } @@ -63,11 +63,6 @@ public bool IsBeaconEnabledForControlBar(UserInfo user) return enabled; } - protected override Func GetFactory() - { - return () => new BeaconService(); - } - public bool IsBeaconEnabledForPersonaBar() { return Host.ParticipateInImprovementProg && !IsAlphaMode; @@ -78,30 +73,30 @@ public string GetBeaconQuery(UserInfo user, string filePath = null) var roles = 0; if (user.UserID >= 0) { - if (user.IsSuperUser) - { - roles |= (int)RolesEnum.Host; - } - - if (user.IsInRole("Administrators")) - { - roles |= (int)RolesEnum.Admin; - } - - if (user.IsInRole("Content Managers")) - { - roles |= (int)RolesEnum.ContentManager; - } - - if (user.IsInRole("Content Editors")) - { - roles |= (int)RolesEnum.ContentEditor; - } - - if (user.IsInRole("Community Manager")) - { - roles |= (int)RolesEnum.CommunityManager; - } + if (user.IsSuperUser) + { + roles |= (int)RolesEnum.Host; + } + + if (user.IsInRole("Administrators")) + { + roles |= (int)RolesEnum.Admin; + } + + if (user.IsInRole("Content Managers")) + { + roles |= (int)RolesEnum.ContentManager; + } + + if (user.IsInRole("Content Editors")) + { + roles |= (int)RolesEnum.ContentEditor; + } + + if (user.IsInRole("Community Manager")) + { + roles |= (int)RolesEnum.CommunityManager; + } } // h: Host GUID - hashed @@ -124,24 +119,24 @@ public string GetBeaconQuery(UserInfo user, string filePath = null) { "r", roles.ToString("D") }, }; - if (!string.IsNullOrEmpty(filePath)) - { - qparams["f"] = HttpUtility.UrlEncode(filePath); - } - - // add package and version to context of request + if (!string.IsNullOrEmpty(filePath)) + { + qparams["f"] = HttpUtility.UrlEncode(filePath); + } + + // add package and version to context of request string packageName = DotNetNukeContext.Current.Application.Name; string installVersion = Common.Globals.FormatVersion(DotNetNukeContext.Current.Application.Version, "00", 3, string.Empty); - if (!string.IsNullOrEmpty(packageName)) - { - qparams["n"] = HttpUtility.UrlEncode(this.GetHash(packageName)); - } - - if (!string.IsNullOrEmpty(installVersion)) - { - qparams["v"] = HttpUtility.UrlEncode(this.GetHash(installVersion)); - } - + if (!string.IsNullOrEmpty(packageName)) + { + qparams["n"] = HttpUtility.UrlEncode(this.GetHash(packageName)); + } + + if (!string.IsNullOrEmpty(installVersion)) + { + qparams["v"] = HttpUtility.UrlEncode(this.GetHash(installVersion)); + } + return "?" + string.Join("&", qparams.Select(kpv => kpv.Key + "=" + kpv.Value)); } @@ -150,37 +145,42 @@ public string GetBeaconUrl(UserInfo user, string filePath = null) return this.GetBeaconEndpoint() + this.GetBeaconQuery(user, filePath); } + protected override Func GetFactory() + { + return () => new BeaconService(); + } + private static RolesEnum GetUserRolesBitValues(UserInfo user) { var roles = RolesEnum.None; if (user.UserID >= 0) { - if (user.IsSuperUser) - { - roles |= RolesEnum.Host; - } - - if (user.IsInRole("Administrators")) - { - roles |= RolesEnum.Admin; - } - - if (user.IsInRole("Content Managers")) - { - roles |= RolesEnum.ContentManager; - } - - if (user.IsInRole("Content Editors")) - { - roles |= RolesEnum.ContentEditor; - } - - if (user.IsInRole("Community Manager")) - { - roles |= RolesEnum.CommunityManager; - } + if (user.IsSuperUser) + { + roles |= RolesEnum.Host; + } + + if (user.IsInRole("Administrators")) + { + roles |= RolesEnum.Admin; + } + + if (user.IsInRole("Content Managers")) + { + roles |= RolesEnum.ContentManager; + } + + if (user.IsInRole("Content Editors")) + { + roles |= RolesEnum.ContentEditor; + } + + if (user.IsInRole("Community Manager")) + { + roles |= RolesEnum.CommunityManager; + } } - + return roles; } diff --git a/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs b/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs index b811084252a..eb57a469d51 100644 --- a/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs +++ b/DNN Platform/Library/Services/ImprovementsProgram/IBeaconService.cs @@ -9,13 +9,13 @@ namespace DotNetNuke.Services.ImprovementsProgram public interface IBeaconService { string GetBeaconEndpoint(); - + string GetBeaconQuery(UserInfo user, string filePath = null); - + string GetBeaconUrl(UserInfo user, string filePath = null); - + bool IsBeaconEnabledForControlBar(UserInfo user); - + bool IsBeaconEnabledForPersonaBar(); } } diff --git a/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs b/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs index 6929f0dd092..ce00c6f2039 100644 --- a/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs +++ b/DNN Platform/Library/Services/Installer/Blocker/IInstallBlocker.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.Services.Installer.Blocker public interface IInstallBlocker { void RegisterInstallBegining(); - + void RegisterInstallEnd(); - + bool IsInstallInProgress(); } } diff --git a/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs b/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs index e11e9e34d25..510eda5d971 100644 --- a/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs +++ b/DNN Platform/Library/Services/Installer/Blocker/InstallBlocker.cs @@ -15,17 +15,17 @@ namespace DotNetNuke.Services.Installer.Blocker /// This class ... /// public class InstallBlocker : ServiceLocator, IInstallBlocker - { - private const string installBlockerFile = "\\installBlocker.lock"; - private bool fileCreated = false; - + { + private const string installBlockerFile = "\\installBlocker.lock"; + private bool fileCreated = false; + public void RegisterInstallBegining() { - if (!this.fileCreated) - { - File.Create(Globals.ApplicationMapPath + installBlockerFile); - } - + if (!this.fileCreated) + { + File.Create(Globals.ApplicationMapPath + installBlockerFile); + } + this.fileCreated = true; } @@ -36,7 +36,7 @@ public bool IsInstallInProgress() public void RegisterInstallEnd() { - var retryable = new RetryableAction( + var retryable = new RetryableAction( () => { if (this.IsInstallInProgress() && this.fileCreated) @@ -47,11 +47,11 @@ public void RegisterInstallEnd() retryable.TryIt(); this.fileCreated = false; - } - + } + protected override Func GetFactory() { return () => new InstallBlocker(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs index 046eacdcb7e..a86d7a8b2a6 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/CoreVersionDependency.cs @@ -37,7 +37,7 @@ public override bool IsValid { _IsValid = false; } - + return _IsValid; } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs b/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs index dc4fa35d467..863c4b2501c 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/DependencyBase.cs @@ -15,7 +15,7 @@ namespace DotNetNuke.Services.Installer.Dependencies /// /// ----------------------------------------------------------------------------- public abstract class DependencyBase : IDependency - { + { public virtual string ErrorMessage { get @@ -34,6 +34,6 @@ public virtual bool IsValid public virtual void ReadManifest(XPathNavigator dependencyNav) { - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs b/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs index 5bb995718f5..d8f301230f9 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/DependencyFactory.cs @@ -17,12 +17,12 @@ namespace DotNetNuke.Services.Installer.Dependencies /// /// ----------------------------------------------------------------------------- public class DependencyFactory - { + { /// ----------------------------------------------------------------------------- /// /// The GetDependency method instantiates (and returns) the relevant Dependency. /// - /// The manifest (XPathNavigator) for the dependency. + /// The manifest (XPathNavigator) for the dependency. /// /// ----------------------------------------------------------------------------- public static IDependency GetDependency(XPathNavigator dependencyNav) @@ -55,20 +55,20 @@ public static IDependency GetDependency(XPathNavigator dependencyNav) // The class for the Installer is specified in the Text property dependency = (DependencyBase)Reflection.CreateObject(entry.Text, "Dependency_" + entry.Value); } - + break; } - + if (dependency == null) { // Could not create dependency, show generic error message dependency = new InvalidDependency(Util.INSTALL_Dependencies); } - + // Read Manifest dependency.ReadManifest(dependencyNav); return dependency; - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs index 31aaa8a2700..75a4a576022 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/IDependency.cs @@ -15,7 +15,7 @@ namespace DotNetNuke.Services.Installer.Dependencies public interface IDependency { string ErrorMessage { get; } - + bool IsValid { get; } void ReadManifest(XPathNavigator dependencyNav); diff --git a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs index 76af91f2840..d2d9141805a 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/ManagedPackageDependency.cs @@ -27,7 +27,7 @@ public override bool IsValid bool _IsValid = true; // Get Package from DataStore - PackageInfo package = PackageController.Instance.GetExtensionPackage( + PackageInfo package = PackageController.Instance.GetExtensionPackage( Null.NullInteger, (p) => p.Name.Equals(this.PackageDependency.PackageName, StringComparison.OrdinalIgnoreCase) && p.Version >= this.PackageDependency.Version); @@ -35,12 +35,12 @@ public override bool IsValid { _IsValid = false; } - + return _IsValid; } } - - public PackageDependencyInfo PackageDependency { get; set; } + + public PackageDependencyInfo PackageDependency { get; set; } public override void ReadManifest(XPathNavigator dependencyNav) { @@ -49,6 +49,6 @@ public override void ReadManifest(XPathNavigator dependencyNav) PackageName = dependencyNav.Value, Version = new Version(Util.ReadAttribute(dependencyNav, "version")), }; - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs index a27c71ac6ef..46a58c1dfab 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/PackageDependency.cs @@ -40,7 +40,7 @@ public override bool IsValid { _IsValid = false; } - + return _IsValid; } } diff --git a/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs b/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs index 5ef3360e38d..d6c31273e10 100644 --- a/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs +++ b/DNN Platform/Library/Services/Installer/Dependencies/TypeDependency.cs @@ -48,7 +48,7 @@ public override bool IsValid } } } - + return isValid; } } diff --git a/DNN Platform/Library/Services/Installer/InstallFile.cs b/DNN Platform/Library/Services/Installer/InstallFile.cs index 59fb30975bd..86a00f7a5f3 100644 --- a/DNN Platform/Library/Services/Installer/InstallFile.cs +++ b/DNN Platform/Library/Services/Installer/InstallFile.cs @@ -20,10 +20,10 @@ namespace DotNetNuke.Services.Installer [Serializable] public class InstallFile { - private static readonly Regex FileTypeMatchRegex = new Regex(Util.REGEX_Version + ".txt", RegexOptions.Compiled); - + private static readonly Regex FileTypeMatchRegex = new Regex(Util.REGEX_Version + ".txt", RegexOptions.Compiled); + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallFile instance from a ZipInputStream and a ZipEntry. /// @@ -38,10 +38,10 @@ public InstallFile(ZipInputStream zip, ZipEntry entry, InstallerInfo info) this.Encoding = TextEncoding.UTF8; this.InstallerInfo = info; this.ReadZip(zip, entry); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallFile instance. /// @@ -51,10 +51,10 @@ public InstallFile(string fileName) { this.Encoding = TextEncoding.UTF8; this.ParseFileName(fileName); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallFile instance. /// @@ -66,10 +66,10 @@ public InstallFile(string fileName, InstallerInfo info) this.Encoding = TextEncoding.UTF8; this.ParseFileName(fileName); this.InstallerInfo = info; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallFile instance. /// @@ -83,10 +83,10 @@ public InstallFile(string fileName, string sourceFileName, InstallerInfo info) this.ParseFileName(fileName); this.SourceFileName = sourceFileName; this.InstallerInfo = info; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallFile instance. /// @@ -98,15 +98,7 @@ public InstallFile(string fileName, string filePath) this.Encoding = TextEncoding.UTF8; this.Name = fileName; this.Path = filePath; - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Action for this file. - /// - /// A string. - /// ----------------------------------------------------------------------------- - public string Action { get; set; } + } /// ----------------------------------------------------------------------------- /// @@ -136,8 +128,6 @@ public virtual string BackupPath } } - public TextEncoding Encoding { get; private set; } - /// ----------------------------------------------------------------------------- /// /// Gets the File Extension of the file. @@ -153,7 +143,7 @@ public string Extension { return string.Empty; } - + return ext.Substring(1); } } @@ -172,6 +162,36 @@ public string FullName } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the location of the temporary file. + /// + /// A string. + /// ----------------------------------------------------------------------------- + public string TempFileName + { + get + { + string fileName = this.SourceFileName; + if (string.IsNullOrEmpty(fileName)) + { + fileName = this.FullName; + } + + return System.IO.Path.Combine(this.InstallerInfo.TempInstallFolder, fileName); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Action for this file. + /// + /// A string. + /// ----------------------------------------------------------------------------- + public string Action { get; set; } + + public TextEncoding Encoding { get; private set; } + /// ----------------------------------------------------------------------------- /// /// Gets the associated InstallerInfo. @@ -205,26 +225,6 @@ public string FullName /// ----------------------------------------------------------------------------- public string SourceFileName { get; private set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the location of the temporary file. - /// - /// A string. - /// ----------------------------------------------------------------------------- - public string TempFileName - { - get - { - string fileName = this.SourceFileName; - if (string.IsNullOrEmpty(fileName)) - { - fileName = this.FullName; - } - - return System.IO.Path.Combine(this.InstallerInfo.TempInstallFolder, fileName); - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Type of the file. @@ -239,8 +239,8 @@ public string TempFileName /// /// A System.Version. /// ----------------------------------------------------------------------------- - public Version Version { get; private set; } - + public Version Version { get; private set; } + /// ----------------------------------------------------------------------------- /// /// The SetVersion method sets the version of the file. @@ -250,8 +250,8 @@ public string TempFileName public void SetVersion(Version version) { this.Version = version; - } - + } + /// ----------------------------------------------------------------------------- /// /// The ParseFileName parses the ZipEntry metadata. @@ -271,13 +271,13 @@ private void ParseFileName(string fileName) this.Name = fileName.Substring(i + 1, fileName.Length - (i + 1)); this.Path = fileName.Substring(0, i); } - + if (string.IsNullOrEmpty(this.Path) && fileName.StartsWith("[app_code]")) { this.Name = fileName.Substring(10, fileName.Length - 10); this.Path = fileName.Substring(0, 10); } - + if (this.Name.Equals("manifest.xml", StringComparison.InvariantCultureIgnoreCase)) { this.Type = InstallFileType.Manifest; @@ -318,7 +318,7 @@ private void ParseFileName(string fileName) { this.Type = FileTypeMatchRegex.IsMatch(this.Name) ? InstallFileType.CleanUp : InstallFileType.Other; } - + break; } } @@ -345,6 +345,6 @@ private void ReadZip(ZipInputStream unzip, ZipEntry entry) this.ParseFileName(entry.Name); Util.WriteStream(unzip, this.TempFileName); File.SetLastWriteTime(this.TempFileName, entry.DateTime); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installer.cs b/DNN Platform/Library/Services/Installer/Installer.cs index 99c5e85030f..66d84922cca 100644 --- a/DNN Platform/Library/Services/Installer/Installer.cs +++ b/DNN Platform/Library/Services/Installer/Installer.cs @@ -30,11 +30,11 @@ namespace DotNetNuke.Services.Installer /// ----------------------------------------------------------------------------- public class Installer { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Installer)); - private Stream _inputStream; - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Installer)); + private Stream _inputStream; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a string representing /// the physical path to the temporary install folder and a string representing @@ -48,7 +48,7 @@ public class Installer public Installer(string tempFolder, string manifest, string physicalSitePath, bool loadManifest) { this.Packages = new SortedList(); - + // Called from Interactive installer - default IgnoreWhiteList to false this.InstallerInfo = new InstallerInfo(tempFolder, manifest, physicalSitePath) { IgnoreWhiteList = false }; @@ -56,10 +56,10 @@ public Installer(string tempFolder, string manifest, string physicalSitePath, bo { this.ReadManifest(true); } - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a Stream and a /// string representing the physical path to the root of the site. @@ -68,13 +68,13 @@ public Installer(string tempFolder, string manifest, string physicalSitePath, bo /// The physical path to the root of the site. /// Flag that determines whether the manifest will be loaded. /// ----------------------------------------------------------------------------- - public Installer(Stream inputStream, string physicalSitePath, bool loadManifest) + public Installer(Stream inputStream, string physicalSitePath, bool loadManifest) : this(inputStream, physicalSitePath, loadManifest, true) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a Stream and a /// string representing the physical path to the root of the site. @@ -90,7 +90,7 @@ public Installer(Stream inputStream, string physicalSitePath, bool loadManifest, this._inputStream = new MemoryStream(); inputStream.CopyTo(this._inputStream); - + // Called from Batch installer - default IgnoreWhiteList to true this.InstallerInfo = new InstallerInfo(inputStream, physicalSitePath) { IgnoreWhiteList = true }; @@ -98,10 +98,10 @@ public Installer(Stream inputStream, string physicalSitePath, bool loadManifest, { this.ReadManifest(deleteTemp); } - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new Installer instance from a PackageInfo object. /// @@ -124,15 +124,7 @@ public Installer(string manifest, string physicalSitePath, bool loadManifest) { this.ReadManifest(new FileStream(manifest, FileMode.Open, FileAccess.Read)); } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the associated InstallerInfo object. - /// - /// An InstallerInfo. - /// ----------------------------------------------------------------------------- - public InstallerInfo InstallerInfo { get; private set; } + } /// ----------------------------------------------------------------------------- /// @@ -148,14 +140,6 @@ public bool IsValid } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a SortedList of Packages that are included in the Package Zip. - /// - /// A SortedList(Of Integer, PackageInstaller). - /// ----------------------------------------------------------------------------- - public SortedList Packages { get; private set; } - /// ----------------------------------------------------------------------------- /// /// Gets. @@ -168,7 +152,23 @@ public string TempInstallFolder { return this.InstallerInfo.TempInstallFolder; } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the associated InstallerInfo object. + /// + /// An InstallerInfo. + /// ----------------------------------------------------------------------------- + public InstallerInfo InstallerInfo { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a SortedList of Packages that are included in the Package Zip. + /// + /// A SortedList(Of Integer, PackageInstaller). + /// ----------------------------------------------------------------------------- + public SortedList Packages { get; private set; } public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, InstallerInfo info) { @@ -227,7 +227,7 @@ public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, Inst // Parse the package nodes nav = legacyDoc.CreateNavigator().SelectSingleNode("dotnetnuke"); } - + break; case "skinobject": // Legacy Skin Object @@ -242,7 +242,7 @@ public static XPathNavigator ConvertLegacyNavigator(XPathNavigator rootNav, Inst return nav; } - + public void DeleteTempFolder() { try @@ -262,7 +262,7 @@ public void DeleteTempFolder() /// ----------------------------------------------------------------------------- /// /// The Install method installs the feature. - /// + /// /// /// ----------------------------------------------------------------------------- public bool Install() @@ -291,10 +291,10 @@ public bool Install() { Globals.DeleteFolderRecursive(this.TempInstallFolder); } - + this.InstallerInfo.Log.AddInfo(Util.FOLDER_DeletedBackup); } - + if (this.InstallerInfo.Log.Valid) { this.InstallerInfo.Log.EndJob(Util.INSTALL_Success); @@ -328,7 +328,66 @@ public bool Install() return bStatus; } - + + /// ----------------------------------------------------------------------------- + /// + /// The ReadManifest method reads the manifest file and parses it into packages. + /// + /// ----------------------------------------------------------------------------- + public void ReadManifest(bool deleteTemp) + { + this.InstallerInfo.Log.StartJob(Util.DNN_Reading); + if (this.InstallerInfo.ManifestFile != null) + { + this.ReadManifest(new FileStream(this.InstallerInfo.ManifestFile.TempFileName, FileMode.Open, FileAccess.Read)); + } + + if (this.InstallerInfo.Log.Valid) + { + this.InstallerInfo.Log.EndJob(Util.DNN_Success); + } + else if (deleteTemp) + { + // Delete Temp Folder + this.DeleteTempFolder(); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the feature. + /// + /// A flag that indicates whether the files should be + /// deleted. + /// + /// ----------------------------------------------------------------------------- + public bool UnInstall(bool deleteFiles) + { + this.InstallerInfo.Log.StartJob(Util.UNINSTALL_Start); + try + { + this.UnInstallPackages(deleteFiles); + } + catch (Exception ex) + { + this.InstallerInfo.Log.AddFailure(ex); + return false; + } + + if (this.InstallerInfo.Log.HasWarnings) + { + this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Warnings); + } + else + { + this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Success); + } + + // log installation event + this.LogInstallEvent("Package", "UnInstall"); + return true; + } + /// ----------------------------------------------------------------------------- /// /// The InstallPackages method installs the packages. @@ -340,7 +399,7 @@ private void InstallPackages(ref bool clearClientCache) for (int index = 0; index <= this.Packages.Count - 1; index++) { PackageInstaller installer = this.Packages.Values[index]; - + // Check if package is valid if (installer.Package.IsValid) { @@ -389,7 +448,7 @@ private void LogInstallEvent(string package, string eventType) { log.LogProperties.Add(new LogDetailInfo("Info:", objLogEntry.Description)); } - + LogController.Instance.AddLog(log); } catch (Exception exc) @@ -415,7 +474,7 @@ private void ProcessPackages(XPathNavigator rootNav) { order = int.Parse(installOrder); } - + this.Packages.Add(order, new PackageInstaller(nav.OuterXml, this.InstallerInfo)); } } @@ -441,12 +500,12 @@ private void ReadManifest(Stream stream) { this.InstallerInfo.Log.AddFailure(Util.PACKAGE_UnRecognizable); } - + switch (packageType.ToLowerInvariant()) { case "package": this.InstallerInfo.IsLegacyMode = false; - + // Parse the package nodes this.ProcessPackages(rootNav); break; @@ -496,7 +555,7 @@ private void BackupStreamIntoFile(Stream stream, PackageInfo package) { stream.Seek(0, SeekOrigin.Begin); } - + stream.CopyTo(fileStream); } } @@ -504,65 +563,6 @@ private void BackupStreamIntoFile(Stream stream, PackageInfo package) { Logger.Error(ex); } - } - - /// ----------------------------------------------------------------------------- - /// - /// The ReadManifest method reads the manifest file and parses it into packages. - /// - /// ----------------------------------------------------------------------------- - public void ReadManifest(bool deleteTemp) - { - this.InstallerInfo.Log.StartJob(Util.DNN_Reading); - if (this.InstallerInfo.ManifestFile != null) - { - this.ReadManifest(new FileStream(this.InstallerInfo.ManifestFile.TempFileName, FileMode.Open, FileAccess.Read)); - } - - if (this.InstallerInfo.Log.Valid) - { - this.InstallerInfo.Log.EndJob(Util.DNN_Success); - } - else if (deleteTemp) - { - // Delete Temp Folder - this.DeleteTempFolder(); - } } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstall method uninstalls the feature. - /// - /// A flag that indicates whether the files should be - /// deleted. - /// - /// ----------------------------------------------------------------------------- - public bool UnInstall(bool deleteFiles) - { - this.InstallerInfo.Log.StartJob(Util.UNINSTALL_Start); - try - { - this.UnInstallPackages(deleteFiles); - } - catch (Exception ex) - { - this.InstallerInfo.Log.AddFailure(ex); - return false; - } - - if (this.InstallerInfo.Log.HasWarnings) - { - this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Warnings); - } - else - { - this.InstallerInfo.Log.EndJob(Util.UNINSTALL_Success); - } - - // log installation event - this.LogInstallEvent("Package", "UnInstall"); - return true; - } } } diff --git a/DNN Platform/Library/Services/Installer/InstallerInfo.cs b/DNN Platform/Library/Services/Installer/InstallerInfo.cs index b4b27d97bbc..f9006d80eb9 100644 --- a/DNN Platform/Library/Services/Installer/InstallerInfo.cs +++ b/DNN Platform/Library/Services/Installer/InstallerInfo.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.Services.Installer /// ----------------------------------------------------------------------------- [Serializable] public class InstallerInfo - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance. /// @@ -36,10 +36,10 @@ public InstallerInfo() { this.PhysicalSitePath = Null.NullString; this.Initialize(); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a /// string representing the physical path to the root of the site. @@ -53,10 +53,10 @@ public InstallerInfo(string sitePath, InstallMode mode) this.TempInstallFolder = Globals.InstallMapPath + "Temp\\" + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); this.PhysicalSitePath = sitePath; this.InstallMode = mode; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a Stream and a /// string representing the physical path to the root of the site. @@ -72,10 +72,10 @@ public InstallerInfo(Stream inputStream, string sitePath) // Read the Zip file into its component entries this.ReadZipStream(inputStream, false); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a string representing /// the physical path to the temporary install folder and a string representing @@ -94,10 +94,10 @@ public InstallerInfo(string tempFolder, string manifest, string sitePath) { this.ManifestFile = new InstallFile(manifest, this); } - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallerInfo instance from a PackageInfo object. /// @@ -112,23 +112,7 @@ public InstallerInfo(PackageInfo package, string sitePath) this.InstallMode = InstallMode.UnInstall; this.ManifestFile = new InstallFile(Path.Combine(this.TempInstallFolder, package.Name + ".dnn")); package.AttachInstallerInfo(this); - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets a list of allowable file extensions (in addition to the Host's List). - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string AllowableFiles { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a Dictionary of Files that are included in the Package. - /// - /// A Dictionary(Of String, InstallFile). - /// ----------------------------------------------------------------------------- - public Dictionary Files { get; private set; } + } /// ----------------------------------------------------------------------------- /// @@ -145,35 +129,11 @@ public bool HasValidFiles { _HasValidFiles = Null.NullBoolean; } - + return _HasValidFiles; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets and sets whether the File Extension WhiteList is ignored. - /// - /// A Boolean value. - /// ----------------------------------------------------------------------------- - public bool IgnoreWhiteList { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets whether the Package is already installed with the same version. - /// - /// A Boolean value. - /// ----------------------------------------------------------------------------- - public bool Installed { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the InstallMode. - /// - /// A InstallMode value. - /// ----------------------------------------------------------------------------- - public InstallMode InstallMode { get; private set; } - /// ----------------------------------------------------------------------------- /// /// Gets the Invalid File Extensions. @@ -190,18 +150,11 @@ public string InvalidFileExtensions { _InvalidFileExtensions = _InvalidFileExtensions.Substring(2); } - + return _InvalidFileExtensions; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets whether the Installer is in legacy mode. - /// - /// ----------------------------------------------------------------------------- - public bool IsLegacyMode { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the InstallerInfo instance is Valid. @@ -216,6 +169,53 @@ public bool IsValid } } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets a list of allowable file extensions (in addition to the Host's List). + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string AllowableFiles { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a Dictionary of Files that are included in the Package. + /// + /// A Dictionary(Of String, InstallFile). + /// ----------------------------------------------------------------------------- + public Dictionary Files { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets and sets whether the File Extension WhiteList is ignored. + /// + /// A Boolean value. + /// ----------------------------------------------------------------------------- + public bool IgnoreWhiteList { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets whether the Package is already installed with the same version. + /// + /// A Boolean value. + /// ----------------------------------------------------------------------------- + public bool Installed { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the InstallMode. + /// + /// A InstallMode value. + /// ----------------------------------------------------------------------------- + public InstallMode InstallMode { get; private set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets whether the Installer is in legacy mode. + /// + /// ----------------------------------------------------------------------------- + public bool IsLegacyMode { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the associated Logger. @@ -287,8 +287,8 @@ public bool IsValid /// /// A String. /// ----------------------------------------------------------------------------- - public string TempInstallFolder { get; private set; } - + public string TempInstallFolder { get; private set; } + private void Initialize() { this.TempInstallFolder = Null.NullString; @@ -359,7 +359,7 @@ 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; } else if (file.Extension == "dnn5" && this.ManifestFile.Extension == "dnn") @@ -373,18 +373,18 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) } } } - + this.Log.AddInfo(string.Format(Util.FILE_ReadSuccess, file.FullName)); } - + entry = unzip.GetNextEntry(); } - + if (this.ManifestFile == null) { this.Log.AddFailure(Util.EXCEPTION_MissingDnn); } - + if (this.Log.Valid) { this.Log.EndJob(Util.FILES_ReadingEnd); @@ -397,6 +397,6 @@ private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) // Close the Zip Input Stream as we have finished with it inputStream.Close(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs index bb0c97b0368..77353bd8a96 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AssemblyInstaller.cs @@ -213,51 +213,6 @@ private static string ReadPublicKey(AssemblyName assemblyName) 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) - { - if (this.ApplyXmlMerge(file, "BindingRedirect.config")) - { - this.Log.AddInfo(Util.ASSEMBLY_AddedBindingRedirect + " - " + file.FullName); - } - } - - /// Removes the binding redirect for the assembly file, if the assembly is strong-named. - /// The assembly file. - private void RemoveBindingRedirect(InstallFile file) - { - if (this.ApplyXmlMerge(file, "RemoveBindingRedirect.config")) - { - this.Log.AddInfo(Util.ASSEMBLY_RemovedBindingRedirect + " - " + file.FullName); - } - } - - /// If the is a strong-named assembly, applies the XML merge. - /// The assembly file. - /// The XML merge file name. - /// true if the XML Merge was applied successfully, false if the file was not a strong-named assembly or could not be read. - private bool ApplyXmlMerge(InstallFile file, string xmlMergeFile) - { - var assemblyName = ReadAssemblyName(Path.Combine(this.PhysicalBasePath, file.FullName)); - var publicKeyToken = ReadPublicKey(assemblyName); - if (string.IsNullOrEmpty(publicKeyToken)) - { - return false; - } - - var name = assemblyName.Name; - var assemblyVersion = assemblyName.Version; - var newVersion = assemblyVersion.ToString(); - - var xmlMergePath = Path.Combine(Globals.InstallMapPath, "Config", xmlMergeFile); - var xmlMergeDoc = GetXmlMergeDoc(xmlMergePath, name, publicKeyToken, OldVersion, newVersion); - var xmlMerge = new XmlMerge(xmlMergeDoc, file.Version.ToString(), this.Package.Name); - xmlMerge.UpdateConfigs(); - - return true; - } - /// Gets the XML merge document to create the binding redirect. /// The path to the template binding redirect XML Merge document. /// The assembly name. @@ -308,5 +263,50 @@ private static void ReplaceInAttributeValue(XmlNode parentNode, XmlNamespaceMana var attribute = parentNode.SelectSingleNode(xpath, namespaceManager); attribute.Value = attribute.Value.Replace(oldValue, newValue); } + + /// 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) + { + if (this.ApplyXmlMerge(file, "BindingRedirect.config")) + { + this.Log.AddInfo(Util.ASSEMBLY_AddedBindingRedirect + " - " + file.FullName); + } + } + + /// Removes the binding redirect for the assembly file, if the assembly is strong-named. + /// The assembly file. + private void RemoveBindingRedirect(InstallFile file) + { + if (this.ApplyXmlMerge(file, "RemoveBindingRedirect.config")) + { + this.Log.AddInfo(Util.ASSEMBLY_RemovedBindingRedirect + " - " + file.FullName); + } + } + + /// If the is a strong-named assembly, applies the XML merge. + /// The assembly file. + /// The XML merge file name. + /// true if the XML Merge was applied successfully, false if the file was not a strong-named assembly or could not be read. + private bool ApplyXmlMerge(InstallFile file, string xmlMergeFile) + { + var assemblyName = ReadAssemblyName(Path.Combine(this.PhysicalBasePath, file.FullName)); + var publicKeyToken = ReadPublicKey(assemblyName); + if (string.IsNullOrEmpty(publicKeyToken)) + { + return false; + } + + var name = assemblyName.Name; + var assemblyVersion = assemblyName.Version; + var newVersion = assemblyVersion.ToString(); + + var xmlMergePath = Path.Combine(Globals.InstallMapPath, "Config", xmlMergeFile); + var xmlMergeDoc = GetXmlMergeDoc(xmlMergePath, name, publicKeyToken, OldVersion, newVersion); + var xmlMerge = new XmlMerge(xmlMergeDoc, file.Version.ToString(), this.Package.Name); + xmlMerge.UpdateConfigs(); + + return true; + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs index 708c70f2c72..75b5bacf1f7 100644 --- a/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/AuthenticationInstaller.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class AuthenticationInstaller : ComponentInstallerBase - { + { private AuthenticationInfo AuthSystem; - private AuthenticationInfo TempAuthSystem; - + private AuthenticationInfo TempAuthSystem; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -33,8 +33,8 @@ public override string AllowableFiles { return "ashx, aspx, ascx, vb, cs, resx, css, js, resources, config, vbproj, csproj, sln, htm, html"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -69,7 +69,7 @@ public override void Install() this.AuthSystem.AuthenticationID = this.TempAuthSystem.AuthenticationID; this.AuthSystem.IsEnabled = this.TempAuthSystem.IsEnabled; } - + this.AuthSystem.PackageID = this.Package.PackageID; if (bAdd) { @@ -81,7 +81,7 @@ public override void Install() // Update service AuthenticationController.UpdateAuthentication(this.AuthSystem); } - + this.Completed = true; this.Log.AddInfo(string.Format(Util.AUTHENTICATION_Registered, this.AuthSystem.AuthenticationType)); } @@ -90,30 +90,6 @@ 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); - } - } /// ----------------------------------------------------------------------------- /// @@ -171,6 +147,30 @@ public override void Rollback() public override void UnInstall() { this.DeleteAuthentiation(); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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 43ee5431468..90b4d69f07c 100644 --- a/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/CleanupInstaller.cs @@ -23,18 +23,18 @@ namespace DotNetNuke.Services.Installer.Installers /// ----------------------------------------------------------------------------- public class CleanupInstaller : FileInstaller { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CleanupInstaller)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CleanupInstaller)); private string _fileName; - private string _glob; - + private string _glob; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). /// /// A String. /// ----------------------------------------------------------------------------- - public override string AllowableFiles => "*"; - + public override string AllowableFiles => "*"; + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -76,7 +76,7 @@ public override void Install() { bSuccess = this.ProcessGlob(); } - + this.Completed = bSuccess; } catch (Exception ex) @@ -84,12 +84,29 @@ public override void Install() this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } - + + public override void ReadManifest(XPathNavigator manifestNav) + { + this._fileName = Util.ReadAttribute(manifestNav, "fileName"); + this._glob = Util.ReadAttribute(manifestNav, "glob"); + base.ReadManifest(manifestNav); + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the file component. + /// + /// There is no uninstall for this component. + /// ----------------------------------------------------------------------------- + public override void UnInstall() + { + } + /// ----------------------------------------------------------------------------- /// /// The CleanupFile method cleansup a single file. /// - /// The InstallFile to clean up. + /// The InstallFile to clean up. /// /// ----------------------------------------------------------------------------- protected bool CleanupFile(InstallFile insFile) @@ -128,7 +145,26 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) this.Files.Add(file); } } - + + protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) + { + return base.ReadManifestItem(nav, false); + } + + /// ----------------------------------------------------------------------------- + /// + /// The RollbackFile method rolls back the cleanup of a single file. + /// + /// The InstallFile to commit. + /// ----------------------------------------------------------------------------- + protected override void RollbackFile(InstallFile installFile) + { + if (File.Exists(installFile.BackupFileName)) + { + Util.RestoreFile(installFile, this.PhysicalBasePath, this.Log); + } + } + private bool ProcessCleanupFile() { this.Log.AddInfo(string.Format(Util.CLEANUP_Processing, this.Version.ToString(3))); @@ -143,11 +179,11 @@ private bool ProcessCleanupFile() 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; } @@ -173,45 +209,9 @@ private bool ProcessGlob() { 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) - { - return base.ReadManifestItem(nav, false); - } - - /// ----------------------------------------------------------------------------- - /// - /// The RollbackFile method rolls back the cleanup of a single file. - /// - /// The InstallFile to commit. - /// ----------------------------------------------------------------------------- - protected override void RollbackFile(InstallFile installFile) - { - if (File.Exists(installFile.BackupFileName)) - { - Util.RestoreFile(installFile, this.PhysicalBasePath, this.Log); - } - } - - public override void ReadManifest(XPathNavigator manifestNav) - { - this._fileName = Util.ReadAttribute(manifestNav, "fileName"); - this._glob = Util.ReadAttribute(manifestNav, "glob"); - base.ReadManifest(manifestNav); } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstall method uninstalls the file component. - /// - /// There is no uninstall for this component. - /// ----------------------------------------------------------------------------- - public override void UnInstall() - { - } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs index 1ef0fe3746e..5426355d814 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ComponentInstallerBase.cs @@ -41,14 +41,6 @@ public virtual string AllowableFiles } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether gets the Completed flag. - /// - /// A Boolean value. - /// ----------------------------------------------------------------------------- - public bool Completed { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets the InstallMode. @@ -77,14 +69,6 @@ public Logger Log } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the associated Package. - /// - /// An PackageInfo object. - /// ----------------------------------------------------------------------------- - public PackageInfo Package { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of Files that are included in the Package. @@ -113,8 +97,6 @@ public string PhysicalSitePath } } - public bool Skipped { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. @@ -129,6 +111,24 @@ public virtual bool SupportsManifestOnlyInstall } } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets a value indicating whether gets the Completed flag. + /// + /// A Boolean value. + /// ----------------------------------------------------------------------------- + public bool Completed { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated Package. + /// + /// An PackageInfo object. + /// ----------------------------------------------------------------------------- + public PackageInfo Package { get; set; } + + public bool Skipped { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Type of the component. @@ -137,6 +137,14 @@ public virtual bool SupportsManifestOnlyInstall /// ----------------------------------------------------------------------------- public string Type { get; set; } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Version of the Component. + /// + /// A System.Version. + /// ----------------------------------------------------------------------------- + public Version Version { get; set; } + public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) { EventMessage eventMessage = null; @@ -144,14 +152,14 @@ 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/*")) { @@ -172,14 +180,14 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) { attribValue += version + ","; } - + break; case "upgrade": if (this.Package.InstalledVersion > new Version(0, 0, 0)) { attribValue += version + ","; } - + break; default: Version upgradeVersion = null; @@ -200,30 +208,22 @@ public EventMessage ReadEventMessageNode(XPathNavigator manifestNav) { attribValue += version + ","; } - + break; } } - + attribValue = attribValue.TrimEnd(','); } } - + eventMessage.Attributes.Add(attribName, attribValue); } } - + return eventMessage; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the Version of the Component. - /// - /// A System.Version. - /// ----------------------------------------------------------------------------- - public Version Version { get; set; } - public abstract void Commit(); public abstract void Install(); diff --git a/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs index 12ab9759276..c2e48de54a7 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ConfigInstaller.cs @@ -18,15 +18,15 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class ConfigInstaller : ComponentInstallerBase - { + { private string _FileName = Null.NullString; private string _InstallConfig = Null.NullString; private XmlDocument _TargetConfig; private InstallFile _TargetFile; private string _UnInstallConfig = Null.NullString; private string _UninstallFileName = Null.NullString; - private XmlMerge _xmlMerge; - + private XmlMerge _xmlMerge; + /// ----------------------------------------------------------------------------- /// /// Gets the Install config changes. @@ -81,8 +81,8 @@ public string UnInstallConfig { return this._UnInstallConfig; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -186,7 +186,7 @@ public override void ReadManifest(XPathNavigator manifestNav) { this._TargetFile = new InstallFile(targetFileName, string.Empty, this.Package.InstallerInfo); } - + // Get the Install config changes nodeNav = nav.SelectSingleNode("install"); this._InstallConfig = nodeNav.InnerXml; @@ -248,6 +248,6 @@ public override void UnInstall() stream.Close(); } } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs index ea9479d9512..dabc1f809cd 100644 --- a/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/FileInstaller.cs @@ -18,52 +18,43 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class FileInstaller : ComponentInstallerBase - { + { private readonly List _Files = new List(); - private bool _DeleteFiles = Null.NullBoolean; - + 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. + /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. /// - /// A Boolean value. + /// A Boolean. /// ----------------------------------------------------------------------------- - public bool DeleteFiles + public override bool SupportsManifestOnlyInstall { get { - return this._DeleteFiles; - } - - set - { - this._DeleteFiles = value; + return Null.NullBoolean; } } /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether gets whether the Installer supports Manifest only installs. + /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the + /// package. /// - /// A Boolean. + /// A Boolean value. /// ----------------------------------------------------------------------------- - public override bool SupportsManifestOnlyInstall + public bool DeleteFiles { get { - return Null.NullBoolean; + return this._DeleteFiles; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the BasePath for the files. - /// - /// The Base Path is relative to the WebRoot. - /// A String. - /// ----------------------------------------------------------------------------- - protected string BasePath { get; set; } + + set + { + this._DeleteFiles = value; + } + } /// ----------------------------------------------------------------------------- /// @@ -136,11 +127,20 @@ protected virtual string PhysicalBasePath { _PhysicalBasePath += "\\"; } - + return _PhysicalBasePath.Replace("/", "\\"); } - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the BasePath for the files. + /// + /// The Base Path is relative to the WebRoot. + /// A String. + /// ----------------------------------------------------------------------------- + protected string BasePath { get; set; } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -155,7 +155,7 @@ public override void Commit() { this.CommitFile(file); } - + this.Completed = true; } catch (Exception ex) @@ -182,7 +182,7 @@ public override void Install() break; } } - + this.Completed = bSuccess; } catch (Exception ex) @@ -190,7 +190,76 @@ public override void Install() this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); } } - + + /// ----------------------------------------------------------------------------- + /// + /// The ReadManifest method reads the manifest file for the file compoent. + /// + /// ----------------------------------------------------------------------------- + public override void ReadManifest(XPathNavigator manifestNav) + { + XPathNavigator rootNav = manifestNav.SelectSingleNode(this.CollectionNodeName); + if (rootNav != null) + { + XPathNavigator baseNav = rootNav.SelectSingleNode("basePath"); + if (baseNav != null) + { + this.BasePath = baseNav.Value; + } + + this.ReadCustomManifest(rootNav); + foreach (XPathNavigator nav in rootNav.Select(this.ItemNodeName)) + { + this.ProcessFile(this.ReadManifestItem(nav, true), nav); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The Rollback method undoes the installation of the file component in the event + /// that one of the other components fails. + /// + /// ----------------------------------------------------------------------------- + public override void Rollback() + { + try + { + foreach (InstallFile file in this.Files) + { + this.RollbackFile(file); + } + + this.Completed = true; + } + catch (Exception ex) + { + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the file component. + /// + /// ----------------------------------------------------------------------------- + public override void UnInstall() + { + try + { + foreach (InstallFile file in this.Files) + { + this.UnInstallFile(file); + } + + this.Completed = true; + } + catch (Exception ex) + { + this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); + } + } + /// ----------------------------------------------------------------------------- /// /// The CommitFile method commits a single file. @@ -219,7 +288,7 @@ protected virtual void DeleteFile(InstallFile insFile) /// /// The InstallFile method installs a single file. /// - /// The InstallFile to install. + /// The InstallFile to install. /// /// ----------------------------------------------------------------------------- protected virtual bool InstallFile(InstallFile insFile) @@ -256,7 +325,7 @@ protected virtual bool InstallFile(InstallFile insFile) /// /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed. + /// The type of file being processed. /// /// ----------------------------------------------------------------------------- protected virtual bool IsCorrectType(InstallFileType type) @@ -298,7 +367,7 @@ protected virtual void ReadCustomManifest(XPathNavigator nav) /// The ReadManifestItem method reads a single node. /// /// The XPathNavigator representing the node. - /// Flag that determines whether a check should be made. + /// Flag that determines whether a check should be made. /// /// ----------------------------------------------------------------------------- protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) @@ -330,7 +399,7 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil { file.Type = InstallFileType.AppCode; } - + if (file != null) { // Set the Version @@ -350,7 +419,7 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil { file.Action = strAction; } - + if (this.InstallMode == InstallMode.Install && checkFileExists && file.Action != "UnRegister") { if (File.Exists(file.TempFileName)) @@ -363,7 +432,7 @@ protected virtual InstallFile ReadManifestItem(XPathNavigator nav, bool checkFil } } } - + return file; } @@ -396,75 +465,6 @@ protected virtual void RollbackFile(InstallFile installFile) protected virtual void UnInstallFile(InstallFile unInstallFile) { this.DeleteFile(unInstallFile); - } - - /// ----------------------------------------------------------------------------- - /// - /// The ReadManifest method reads the manifest file for the file compoent. - /// - /// ----------------------------------------------------------------------------- - public override void ReadManifest(XPathNavigator manifestNav) - { - XPathNavigator rootNav = manifestNav.SelectSingleNode(this.CollectionNodeName); - if (rootNav != null) - { - XPathNavigator baseNav = rootNav.SelectSingleNode("basePath"); - if (baseNav != null) - { - this.BasePath = baseNav.Value; - } - - this.ReadCustomManifest(rootNav); - foreach (XPathNavigator nav in rootNav.Select(this.ItemNodeName)) - { - this.ProcessFile(this.ReadManifestItem(nav, true), nav); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Rollback method undoes the installation of the file component in the event - /// that one of the other components fails. - /// - /// ----------------------------------------------------------------------------- - public override void Rollback() - { - try - { - foreach (InstallFile file in this.Files) - { - this.RollbackFile(file); - } - - this.Completed = true; - } - catch (Exception ex) - { - this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstall method uninstalls the file component. - /// - /// ----------------------------------------------------------------------------- - public override void UnInstall() - { - try - { - foreach (InstallFile file in this.Files) - { - this.UnInstallFile(file); - } - - this.Completed = true; - } - catch (Exception ex) - { - this.Log.AddFailure(Util.EXCEPTION + " - " + ex.Message); - } - } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs b/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs index 86d7e6dc823..877ebd6245c 100644 --- a/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs +++ b/DNN Platform/Library/Services/Installer/Installers/InstallerFactory.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class InstallerFactory - { + { /// ----------------------------------------------------------------------------- /// /// The GetInstaller method instantiates the relevant Component Installer. /// - /// The type of Installer. + /// The type of Installer. /// /// ----------------------------------------------------------------------------- public static ComponentInstallerBase GetInstaller(string installerType) @@ -98,10 +98,10 @@ public static ComponentInstallerBase GetInstaller(string installerType) // The class for the Installer is specified in the Text property installer = (ComponentInstallerBase)Reflection.CreateObject(entry.Text, "Installer_" + entry.Value); } - + break; } - + return installer; } @@ -110,7 +110,7 @@ public static ComponentInstallerBase GetInstaller(string installerType) /// The GetInstaller method instantiates the relevant Component Installer. /// /// The manifest (XPathNavigator) for the component. - /// The associated PackageInfo instance. + /// The associated PackageInfo instance. /// /// ----------------------------------------------------------------------------- public static ComponentInstallerBase GetInstaller(XPathNavigator manifestNav, PackageInfo package) @@ -142,8 +142,8 @@ public static ComponentInstallerBase GetInstaller(XPathNavigator manifestNav, Pa installer.ReadManifest(manifestNav); } } - + return installer; - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs index acade88447f..5017fb985f2 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptFileInstaller.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Services.Installer.Installers using DotNetNuke.Common; public class JavaScriptFileInstaller : FileInstaller - { + { /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -23,8 +23,8 @@ public override string AllowableFiles { return "js"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("jsfiles"). @@ -51,8 +51,8 @@ protected override string ItemNodeName { return "jsfile"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The ReadCustomManifest method reads the custom manifest items (that subclasses @@ -67,6 +67,6 @@ protected override void ReadCustomManifest(XPathNavigator nav) { this.BasePath = string.Format("Resources\\Libraries\\{0}\\{1}", libraryNav.Value, Globals.FormatVersion(this.Package.Version, "00", 3, "_")); } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs index 25682665a45..59ce0b58ffc 100644 --- a/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/JavaScriptLibraryInstaller.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.Installer.Installers public class JavaScriptLibraryInstaller : ComponentInstallerBase { private JavaScriptLibrary _library; - private JavaScriptLibrary _installedLibrary; + private JavaScriptLibrary _installedLibrary; public override void Commit() { @@ -31,7 +31,7 @@ public override void Install() { this._library.JavaScriptLibraryID = this._installedLibrary.JavaScriptLibraryID; } - + // Save JavaScript Library to database this._library.PackageID = this.Package.PackageID; JavaScriptLibraryController.Instance.SaveLibrary(this._library); @@ -44,26 +44,6 @@ 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) { @@ -95,6 +75,26 @@ public override void Rollback() public override void UnInstall() { this.DeleteLibrary(); - } + } + + private void DeleteLibrary() + { + try + { + // Attempt to get the Library + var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.PackageID == this.Package.PackageID); + + if (library != null) + { + JavaScriptLibraryController.Instance.DeleteLibrary(library); + + this.Log.AddInfo(string.Format(Util.LIBRARY_UnRegistered, library.LibraryName)); + } + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs index e54515a707e..0b829ce8c9b 100644 --- a/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/LanguageInstaller.cs @@ -19,17 +19,17 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class LanguageInstaller : FileInstaller - { + { private readonly LanguagePackType LanguagePackType; private LanguagePackInfo InstalledLanguagePack; private Locale Language; private LanguagePackInfo LanguagePack; - private Locale TempLanguage; - + private Locale TempLanguage; + public LanguageInstaller(LanguagePackType type) { this.LanguagePackType = type; - } + } /// ----------------------------------------------------------------------------- /// @@ -40,8 +40,8 @@ public LanguageInstaller(LanguagePackType type) public override string AllowableFiles { get { return "resx, xml, tdf,template"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("languageFiles"). @@ -69,7 +69,7 @@ protected override string ItemNodeName return "languageFile"; } } - + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -79,7 +79,7 @@ protected override string ItemNodeName public override void Commit() { if (this.LanguagePackType == LanguagePackType.Core || this.LanguagePack.DependentPackageID > 0) - { + { base.Commit(); } else @@ -113,7 +113,7 @@ public override void Install() { this.Language.LanguageId = this.TempLanguage.LanguageId; } - + if (this.LanguagePack.PackageType == LanguagePackType.Core) { // Update language @@ -143,7 +143,44 @@ public override void Install() this.Skipped = true; } } - + + /// ----------------------------------------------------------------------------- + /// + /// The Rollback method undoes the installation of the component in the event + /// that one of the other components fails. + /// + /// ----------------------------------------------------------------------------- + public override void Rollback() + { + // If Temp Language exists then we need to update the DataStore with this + if (this.TempLanguage == null) + { + // No Temp Language - Delete newly added Language + this.DeleteLanguage(); + } + else + { + // Temp Language - Rollback to Temp + Localization.SaveLanguage(this.TempLanguage); + } + + // Call base class to prcoess files + base.Rollback(); + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the language component. + /// + /// ----------------------------------------------------------------------------- + public override void UnInstall() + { + this.DeleteLanguage(); + + // Call base class to process files + base.UnInstall(); + } + /// ----------------------------------------------------------------------------- /// /// The ReadCustomManifest method reads the custom manifest items. @@ -176,8 +213,8 @@ protected override void ReadCustomManifest(XPathNavigator nav) // Call base class base.ReadCustomManifest(nav); - } - + } + /// ----------------------------------------------------------------------------- /// /// The DeleteLanguage method deletes the Language @@ -210,43 +247,6 @@ private void DeleteLanguage() { this.Log.AddFailure(ex); } - } - - /// ----------------------------------------------------------------------------- - /// - /// The Rollback method undoes the installation of the component in the event - /// that one of the other components fails. - /// - /// ----------------------------------------------------------------------------- - public override void Rollback() - { - // If Temp Language exists then we need to update the DataStore with this - if (this.TempLanguage == null) - { - // No Temp Language - Delete newly added Language - this.DeleteLanguage(); - } - else - { - // Temp Language - Rollback to Temp - Localization.SaveLanguage(this.TempLanguage); - } - - // Call base class to prcoess files - base.Rollback(); } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstall method uninstalls the language component. - /// - /// ----------------------------------------------------------------------------- - public override void UnInstall() - { - this.DeleteLanguage(); - - // Call base class to prcoess files - base.UnInstall(); - } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs index 553d9fdde63..8f5e5ce438b 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ModuleInstaller.cs @@ -25,11 +25,11 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class ModuleInstaller : ComponentInstallerBase - { + { private DesktopModuleInfo _desktopModule; private EventMessage _eventMessage; - private DesktopModuleInfo _installedDesktopModule; - + private DesktopModuleInfo _installedDesktopModule; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -42,8 +42,8 @@ public override string AllowableFiles { return "cshtml, vbhtml, ashx, aspx, ascx, vb, cs, resx, css, js, resources, config, vbproj, csproj, sln, htm, html, xml, psd, svc, asmx, xsl, xslt"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -57,18 +57,18 @@ public override void Commit() { Config.AddCodeSubDirectory(this._desktopModule.CodeSubDirectory); } - + 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 @@ -148,7 +148,7 @@ public override void Install() if (this._installedDesktopModule != null) { this._desktopModule.DesktopModuleID = this._installedDesktopModule.DesktopModuleID; - + // save the module's category this._desktopModule.Category = this._installedDesktopModule.Category; } @@ -169,91 +169,6 @@ 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); - } - } /// ----------------------------------------------------------------------------- /// @@ -295,7 +210,7 @@ public override void ReadManifest(XPathNavigator manifestNav) } } } - + if (this.Log.Valid) { this.Log.AddInfo(Util.MODULE_ReadSuccess); @@ -331,6 +246,91 @@ public override void Rollback() public override void UnInstall() { this.DeleteModule(); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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 0a38230cec1..b4de14c9466 100644 --- a/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/PackageInstaller.cs @@ -20,13 +20,13 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class PackageInstaller : ComponentInstallerBase - { + { private readonly SortedList _componentInstallers = new SortedList(); private PackageInfo _installedPackage; - private EventMessage _eventMessage; - + private EventMessage _eventMessage; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new PackageInstaller instance. /// @@ -57,10 +57,10 @@ public PackageInstaller(PackageInfo package) this._componentInstallers.Add(0, installer); } } - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new PackageInstaller instance. /// @@ -81,8 +81,8 @@ public PackageInstaller(string packageManifest, InstallerInfo info) XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("package"); this.ReadManifest(nav); } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and sets whether the Packages files are deleted when uninstalling the @@ -98,8 +98,8 @@ public PackageInstaller(string packageManifest, InstallerInfo info) /// /// A Boolean value. /// ----------------------------------------------------------------------------- - public bool IsValid { get; private set; } - + public bool IsValid { get; private set; } + /// ----------------------------------------------------------------------------- /// /// The Commit method commits the package installation. @@ -131,7 +131,7 @@ public override void Commit() { this.Log.AddFailure(Util.INSTALL_Aborted); } - + this.Package.InstallerInfo.PackageID = this.Package.PackageID; } @@ -186,7 +186,7 @@ public override void Install() { this.Log.AddFailure(Util.INSTALL_Aborted + " - " + this.Package.Name + ":" + ex.Message); } - + if (isCompleted) { // All components successfully installed so Commit any pending changes @@ -198,92 +198,6 @@ 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; - } /// ----------------------------------------------------------------------------- /// @@ -303,7 +217,7 @@ public override void ReadManifest(XPathNavigator manifestNav) { this.Package.PortalID = this.Package.InstallerInfo.PortalID; } - + this.CheckSecurity(); if (!this.IsValid) { @@ -319,7 +233,7 @@ public override void ReadManifest(XPathNavigator manifestNav) { this.IsValid = false; } - + if (this.IsValid) { this.Package.Version = new Version(strVersion); @@ -373,44 +287,44 @@ public override void ReadManifest(XPathNavigator manifestNav) // In Dynamics moduels, a component:type=File can have a basePath pointing to the App_Conde folder. This is not a correct FolderName // To ensure that FolderName is DesktopModules... var folderNameValue = PackageController.GetSpecificFolderName(manifestNav, "components/component/files|components/component/resourceFiles", "basePath", "DesktopModules"); - if (!string.IsNullOrEmpty(folderNameValue)) - { - this.Package.FolderName = folderNameValue.Replace('\\', '/'); - } - + if (!string.IsNullOrEmpty(folderNameValue)) + { + this.Package.FolderName = folderNameValue.Replace('\\', '/'); + } + break; case "Auth_System": foldernameNav = manifestNav.SelectSingleNode("components/component/files"); - if (foldernameNav != null) - { - this.Package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); - } - + if (foldernameNav != null) + { + this.Package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); + } + break; case "Container": foldernameNav = manifestNav.SelectSingleNode("components/component/containerFiles"); - if (foldernameNav != null) - { - this.Package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); - } - + if (foldernameNav != null) + { + this.Package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); + } + break; case "Skin": foldernameNav = manifestNav.SelectSingleNode("components/component/skinFiles"); - if (foldernameNav != null) - { - this.Package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); - } - + if (foldernameNav != null) + { + this.Package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); + } + break; default: // copied from "Module" without the extra OR condition folderNameValue = PackageController.GetSpecificFolderName(manifestNav, "components/component/resourceFiles", "basePath", "DesktopModules"); - if (!string.IsNullOrEmpty(folderNameValue)) - { - this.Package.FolderName = folderNameValue.Replace('\\', '/'); - } - + if (!string.IsNullOrEmpty(folderNameValue)) + { + this.Package.FolderName = folderNameValue.Replace('\\', '/'); + } + break; } @@ -437,7 +351,7 @@ public override void ReadManifest(XPathNavigator manifestNav) } } } - + // Get Author XPathNavigator authorNav = manifestNav.SelectSingleNode("owner"); if (authorNav != null) @@ -463,7 +377,7 @@ public override void ReadManifest(XPathNavigator manifestNav) this.Package.License = this.ReadTextFromFile(licenseSrc); } } - + if (string.IsNullOrEmpty(this.Package.License)) { // Legacy Packages have no license @@ -485,7 +399,7 @@ public override void ReadManifest(XPathNavigator manifestNav) this.Package.ReleaseNotes = this.ReadTextFromFile(relNotesSrc); } } - + if (string.IsNullOrEmpty(this.Package.ReleaseNotes)) { // Legacy Packages have no Release Notes @@ -562,7 +476,7 @@ public override void UnInstall() { fileInstaller.DeleteFiles = this.DeleteFiles; } - + this.Log.ResetFlags(); this.Log.AddInfo(Util.UNINSTALL_StartComp + " - " + compInstaller.Type); compInstaller.UnInstall(); @@ -579,6 +493,92 @@ public override void UnInstall() // Remove the Package information from the Data Store PackageController.Instance.DeleteExtensionPackage(this.Package); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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 106cd2e94b1..57ea9e08a97 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ResourceFileInstaller.cs @@ -22,9 +22,9 @@ namespace DotNetNuke.Services.Installer.Installers public class ResourceFileInstaller : FileInstaller { public const string DEFAULT_MANIFESTEXT = ".manifest"; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ResourceFileInstaller)); - private string _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). @@ -37,8 +37,8 @@ public override string AllowableFiles { return "resources, zip"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("resourceFiles"). @@ -74,8 +74,8 @@ protected string Manifest { return this._Manifest; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The CommitFile method commits a single file. @@ -100,7 +100,7 @@ protected override void DeleteFile(InstallFile file) /// /// The InstallFile method installs a single assembly. /// - /// The InstallFile to install. + /// The InstallFile to install. /// protected override bool InstallFile(InstallFile insFile) { @@ -108,14 +108,14 @@ protected override bool InstallFile(InstallFile insFile) try { this.Log.AddInfo(Util.FILES_Expanding); - + // Create the folder for destination this._Manifest = insFile.Name + ".manifest"; if (!Directory.Exists(this.PhysicalBasePath)) { Directory.CreateDirectory(this.PhysicalBasePath); } - + using (var unzip = new ZipInputStream(new FileStream(insFile.TempFileName, FileMode.Open))) using (var manifestStream = new FileStream(Path.Combine(this.PhysicalBasePath, this.Manifest), FileMode.Create, FileAccess.Write)) { @@ -146,7 +146,7 @@ protected override bool InstallFile(InstallFile insFile) writer.WriteStartElement("file"); // Write path - writer.WriteElementString( + writer.WriteElementString( "path", entry.Name.Substring(0, entry.Name.IndexOf(fileName))); @@ -156,7 +156,7 @@ protected override bool InstallFile(InstallFile insFile) var physicalPath = Path.Combine(this.PhysicalBasePath, entry.Name); if (File.Exists(physicalPath)) { - Util.BackupFile( + Util.BackupFile( new InstallFile(entry.Name, this.Package.InstallerInfo), this.PhysicalBasePath, this.Log); @@ -186,7 +186,7 @@ protected override bool InstallFile(InstallFile insFile) retValue = false; } - + return retValue; } @@ -194,7 +194,7 @@ protected override bool InstallFile(InstallFile insFile) /// /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed. + /// The type of file being processed. /// /// ----------------------------------------------------------------------------- protected override bool IsCorrectType(InstallFileType type) @@ -207,7 +207,7 @@ protected override bool IsCorrectType(InstallFileType type) /// The ReadManifestItem method reads a single node. /// /// The XPathNavigator representing the node. - /// Flag that determines whether a check should be made. + /// Flag that determines whether a check should be made. /// /// ----------------------------------------------------------------------------- protected override InstallFile ReadManifestItem(XPathNavigator nav, bool checkFileExists) @@ -255,7 +255,7 @@ protected override void RollbackFile(InstallFile insFile) Util.DeleteFile(entry.Name, this.PhysicalBasePath, this.Log); } } - + entry = unzip.GetNextEntry(); } } @@ -283,11 +283,11 @@ protected override void UnInstallFile(InstallFile unInstallFile) this.Log.AddFailure(ex); } } - + if (this.DeleteFiles) { Util.DeleteFile(this.Manifest, this.PhysicalBasePath, this.Log); } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs index 4bc8102d0ea..2023b9eb31e 100644 --- a/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/ScriptInstaller.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class ScriptInstaller : FileInstaller - { + { private readonly SortedList _installScripts = new SortedList(); private readonly SortedList _unInstallScripts = new SortedList(); private InstallFile _installScript; - private InstallFile _upgradeScript; - + private InstallFile _upgradeScript; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -38,8 +38,8 @@ public override string AllowableFiles { return "*dataprovider, sql"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the base Install Script (if present). @@ -130,8 +130,8 @@ protected InstallFile UpgradeScript { return this._upgradeScript; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -201,22 +201,48 @@ public override void Install() } } } - + this.Completed = bSuccess; } catch (Exception ex) { this.Log.AddFailure(ex); } - + this.Log.AddInfo(Util.SQL_End); } + /// ----------------------------------------------------------------------------- + /// + /// The Rollback method undoes the installation of the script component in the event + /// that one of the other components fails. + /// + /// ----------------------------------------------------------------------------- + public override void Rollback() + { + base.Rollback(); + } + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the script component. + /// + /// ----------------------------------------------------------------------------- + public override void UnInstall() + { + this.Log.AddInfo(Util.SQL_BeginUnInstall); + + // Call the base method + base.UnInstall(); + + this.Log.AddInfo(Util.SQL_EndUnInstall); + } + /// ----------------------------------------------------------------------------- /// /// Gets a flag that determines what type of file this installer supports. /// - /// The type of file being processed. + /// The type of file being processed. /// /// ----------------------------------------------------------------------------- protected override bool IsCorrectType(InstallFileType type) @@ -260,7 +286,26 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) // Call base method to set up for file processing base.ProcessFile(file, nav); } - + + protected override void UnInstallFile(InstallFile scriptFile) + { + // Process the file if it is an UnInstall Script + var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); + if (extension != null && this.UnInstallScripts.ContainsValue(scriptFile)) + { + string fileExtension = extension.Substring(1); + if (scriptFile.Name.StartsWith("uninstall.", StringComparison.InvariantCultureIgnoreCase) && this.IsValidScript(fileExtension)) + { + // Install Script + this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); + this.ExecuteSql(scriptFile); + } + } + + // Call base method to delete file + base.UnInstallFile(scriptFile); + } + private bool ExecuteSql(InstallFile scriptFile) { bool bSuccess = true; @@ -276,7 +321,7 @@ private bool ExecuteSql(InstallFile scriptFile) { strScript = strScript.Substring(1); } - + string strSQLExceptions = DataProvider.Instance().ExecuteScript(strScript); if (!string.IsNullOrEmpty(strSQLExceptions)) { @@ -290,7 +335,7 @@ private bool ExecuteSql(InstallFile scriptFile) bSuccess = false; } } - + this.Log.AddInfo(string.Format(Util.SQL_EndFile, scriptFile.Name)); return bSuccess; } @@ -298,8 +343,8 @@ private bool ExecuteSql(InstallFile scriptFile) 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 @@ -316,53 +361,8 @@ private bool InstallScriptFile(InstallFile scriptFile) bSuccess = this.ExecuteSql(scriptFile); } } - - return bSuccess; - } - - protected override void UnInstallFile(InstallFile scriptFile) - { - // Process the file if it is an UnInstall Script - var extension = Path.GetExtension(scriptFile.Name.ToLowerInvariant()); - if (extension != null && this.UnInstallScripts.ContainsValue(scriptFile)) - { - string fileExtension = extension.Substring(1); - if (scriptFile.Name.StartsWith("uninstall.", StringComparison.InvariantCultureIgnoreCase) && this.IsValidScript(fileExtension)) - { - // Install Script - this.Log.AddInfo(Util.SQL_Executing + scriptFile.Name); - this.ExecuteSql(scriptFile); - } - } - // Call base method to delete file - base.UnInstallFile(scriptFile); - } - - /// ----------------------------------------------------------------------------- - /// - /// The Rollback method undoes the installation of the script component in the event - /// that one of the other components fails. - /// - /// ----------------------------------------------------------------------------- - public override void Rollback() - { - base.Rollback(); + return bSuccess; } - - /// ----------------------------------------------------------------------------- - /// - /// The UnInstall method uninstalls the script component. - /// - /// ----------------------------------------------------------------------------- - public override void UnInstall() - { - this.Log.AddInfo(Util.SQL_BeginUnInstall); - - // Call the base method - base.UnInstall(); - - this.Log.AddInfo(Util.SQL_EndUnInstall); - } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs index 06e42d33362..7ccfb17cb84 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinControlInstaller.cs @@ -18,10 +18,10 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class SkinControlInstaller : ComponentInstallerBase - { + { private SkinControlInfo InstalledSkinControl; - private SkinControlInfo SkinControl; - + private SkinControlInfo SkinControl; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -34,8 +34,8 @@ public override string AllowableFiles { return "ascx, vb, cs, js, resx, xml, vbproj, csproj, sln"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Commit method finalises the Install and commits any pending changes. @@ -75,30 +75,6 @@ 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); - } - } /// ----------------------------------------------------------------------------- /// @@ -145,6 +121,30 @@ public override void Rollback() public override void UnInstall() { this.DeleteSkinControl(); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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 a0fd91b89ab..eb51db2ab76 100644 --- a/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/SkinInstaller.cs @@ -21,13 +21,13 @@ namespace DotNetNuke.Services.Installer.Installers /// /// ----------------------------------------------------------------------------- public class SkinInstaller : FileInstaller - { + { private readonly ArrayList _SkinFiles = new ArrayList(); private SkinPackageInfo SkinPackage; private SkinPackageInfo TempSkinPackage; - private string _SkinName = Null.NullString; - + private string _SkinName = Null.NullString; + /// ----------------------------------------------------------------------------- /// /// Gets a list of allowable file extensions (in addition to the Host's List). @@ -40,8 +40,8 @@ public override string AllowableFiles { return "ascx, html, htm, css, xml, js, resx, jpg, jpeg, gif, png"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("skinFiles"). @@ -85,7 +85,7 @@ protected override string PhysicalBasePath { _PhysicalBasePath += "\\"; } - + return _PhysicalBasePath.Replace("/", "\\"); } } @@ -109,7 +109,7 @@ protected string RootPath { _RootPath = PortalController.Instance.GetCurrentPortalSettings().HomeSystemDirectoryMapPath; } - + return _RootPath; } } @@ -168,8 +168,8 @@ protected virtual string SkinType { return "Skin"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The Install method installs the skin component. @@ -200,7 +200,7 @@ public override void Install() this.SkinPackage.PackageID = this.TempSkinPackage.PackageID; } } - + this.SkinPackage.SkinType = this.SkinType; if (bAdd) { @@ -212,7 +212,7 @@ public override void Install() // Update skin package SkinController.UpdateSkinPackage(this.SkinPackage); } - + this.Log.AddInfo(string.Format(Util.SKIN_Registered, this.SkinPackage.SkinName)); // install (copy the files) by calling the base class @@ -241,16 +241,16 @@ public override void Install() break; } } - + Array arrMessage = strMessage.Split(new[] { "
    " }, StringSplitOptions.None); foreach (string strRow in arrMessage) { this.Log.AddInfo(HtmlUtils.StripTags(strRow, true)); } - + this.Log.EndJob(Util.SKIN_EndProcessing); } - + this.Completed = true; } catch (Exception ex) @@ -282,7 +282,20 @@ public override void Rollback() // Call base class to prcoess files base.Rollback(); } - + + /// ----------------------------------------------------------------------------- + /// + /// The UnInstall method uninstalls the skin component. + /// + /// ----------------------------------------------------------------------------- + public override void UnInstall() + { + this.DeleteSkinPackage(); + + // Call base class to prcoess files + base.UnInstall(); + } + /// ----------------------------------------------------------------------------- /// /// The ProcessFile method determines what to do with parsed "file" node. @@ -302,7 +315,7 @@ protected override void ProcessFile(InstallFile file, XPathNavigator nav) { this.SkinFiles.Add(this.PhysicalBasePath + file.FullName); } - + break; } @@ -327,31 +340,6 @@ protected override void ReadCustomManifest(XPathNavigator nav) // 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); - } - } /// ----------------------------------------------------------------------------- /// @@ -371,19 +359,31 @@ protected override void UnInstallFile(InstallFile unInstallFile) fileName = fileName.Replace(Path.GetExtension(fileName), ".ascx"); Util.DeleteFile(fileName, this.PhysicalBasePath, this.Log); } - } + } /// ----------------------------------------------------------------------------- /// - /// The UnInstall method uninstalls the skin component. + /// The DeleteSkinPackage method deletes the Skin Package + /// from the data Store. /// /// ----------------------------------------------------------------------------- - public override void UnInstall() + private void DeleteSkinPackage() { - this.DeleteSkinPackage(); + try + { + // Attempt to get the Authentication Service + SkinPackageInfo skinPackage = SkinController.GetSkinByPackageID(this.Package.PackageID); + if (skinPackage != null) + { + SkinController.DeleteSkinPackage(skinPackage); + } - // Call base class to prcoess files - base.UnInstall(); - } + this.Log.AddInfo(string.Format(Util.SKIN_UnRegistered, skinPackage.SkinName)); + } + catch (Exception ex) + { + this.Log.AddFailure(ex); + } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs index 835ca0d4442..751050237d2 100644 --- a/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/UrlProviderInstaller.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 DotNetNuke.Services.Installer.Installers { using System; @@ -78,24 +77,6 @@ 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. @@ -151,5 +132,23 @@ public override void UnInstall() { this.DeleteProvider(); } + + 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); + } + } } } diff --git a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs index de509d94889..5bf84d245c3 100644 --- a/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs +++ b/DNN Platform/Library/Services/Installer/Installers/WidgetInstaller.cs @@ -29,7 +29,7 @@ public override string AllowableFiles return "js"; } } - + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("widgetFiles"). diff --git a/DNN Platform/Library/Services/Installer/LegacyUtil.cs b/DNN Platform/Library/Services/Installer/LegacyUtil.cs index 02e5d346115..6c486920bee 100644 --- a/DNN Platform/Library/Services/Installer/LegacyUtil.cs +++ b/DNN Platform/Library/Services/Installer/LegacyUtil.cs @@ -31,6 +31,7 @@ namespace DotNetNuke.Services.Installer public class LegacyUtil { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LegacyUtil)); + private static string AdminModules = "Adsense, MarketShare, Authentication, Banners, FeedExplorer, FileManager, HostSettings, Lists, LogViewer, Newsletters, PortalAliases, Portals, RecycleBin, Scheduler, SearchAdmin, SearchInput, SearchResults, Security, SiteLog, SiteWizard, SQL, Tabs, Vendors,"; @@ -68,7 +69,7 @@ public static string CreateSkinManifest(string skinFolder, string skinType, stri // Add Skin Package Fragment CreateSkinManifest(writer, skinFolder, "Skin", tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), "Skins"); } - + if (Directory.Exists(Path.Combine(tempInstallFolder, "Containers"))) { // Add Container PAckage Fragment @@ -80,7 +81,7 @@ public static string CreateSkinManifest(string skinFolder, string skinType, stri // Add Package Fragment CreateSkinManifest(writer, skinFolder, skinType, tempInstallFolder.Replace(Globals.ApplicationMapPath + "\\", string.Empty), string.Empty); } - + PackageWriterBase.WriteManifestEndElement(writer); // Close XmlWriter @@ -98,12 +99,12 @@ public static void ParsePackageName(PackageInfo package) { ParsePackageName(package, "\\"); } - + if (string.IsNullOrEmpty(package.Owner)) { ParsePackageName(package, "_"); } - + if ((package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && AdminModules.Contains(package.Name + ",")) || (package.PackageType.Equals("Module", StringComparison.OrdinalIgnoreCase) && CoreModules.Contains(package.Name + ",")) || ((package.PackageType.Equals("Container", StringComparison.OrdinalIgnoreCase) || package.PackageType.Equals("Skin", StringComparison.OrdinalIgnoreCase)) && KnownSkins.Contains(package.Name + ",")) || (package.PackageType.Equals("SkinObject", StringComparison.OrdinalIgnoreCase) && KnownSkinObjects.Contains(package.Name + ","))) { if (string.IsNullOrEmpty(package.Owner)) @@ -127,7 +128,7 @@ public static void ParsePackageName(PackageInfo package) } } } - + if (package.Owner == "DotNetNuke" || package.Owner == "DNN") { package.License = Localization.GetString("License", Localization.GlobalResourceFile); @@ -142,99 +143,6 @@ 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). /// @@ -251,7 +159,7 @@ public static void ProcessLegacyLanguages() { HostController.Instance.Update("EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); } - + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("root/languageInUrl"); if (urlNav != null) { @@ -267,20 +175,20 @@ public static void ProcessLegacyLanguages() language.Text = Util.ReadAttribute(nav, "name"); language.Code = Util.ReadAttribute(nav, "key"); language.Fallback = Util.ReadAttribute(nav, "fallback"); - + // Save Language Localization.SaveLanguage(language); 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 @@ -292,11 +200,11 @@ 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); } @@ -320,13 +228,13 @@ public static void ProcessLegacyLanguages() { PortalController.UpdatePortalSetting(portalID, "EnableBrowserLanguage", Util.ReadAttribute(browserNav, "enabled", false, null, Null.NullString, "true")); } - + XPathNavigator urlNav = doc.CreateNavigator().SelectSingleNode("locales/languageInUrl"); if (urlNav != null) { PortalController.UpdatePortalSetting(portalID, "EnableUrlLanguage", Util.ReadAttribute(urlNav, "enabled", false, null, Null.NullString, "true")); } - + foreach (Locale installedLanguage in LocaleController.Instance.GetLocales(Null.NullInteger).Values) { string code = installedLanguage.Code; @@ -341,7 +249,7 @@ public static void ProcessLegacyLanguages() break; } } - + if (!bFound) { // Language is enabled - add to portal @@ -393,7 +301,7 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) { package.Version = new Version(desktopModule.Version); } - + if (hostModules.Contains(desktopModule.ModuleName)) { // Host Module so make this a system package @@ -404,7 +312,7 @@ public static void ProcessLegacyModule(DesktopModuleInfo desktopModule) { desktopModule.IsAdmin = false; } - + package.PackageType = "Module"; // See if the Module is using a "Namespace" for its name @@ -505,5 +413,98 @@ public static void ProcessLegacySkins() ProcessLegacySkin(skinFolder, "Container"); } } + + 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); + } + } } } diff --git a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs index 856cfbfc060..8c82e8c6183 100644 --- a/DNN Platform/Library/Services/Installer/Log/LogEntry.cs +++ b/DNN Platform/Library/Services/Installer/Log/LogEntry.cs @@ -15,10 +15,10 @@ namespace DotNetNuke.Services.Installer.Log [Serializable] public class LogEntry { - private readonly string _description; - + private readonly string _description; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor builds a LogEntry from its type and description. /// @@ -33,14 +33,6 @@ public LogEntry(LogType type, string description) this._description = description; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the type of LogEntry. - /// - /// A LogType. - /// ----------------------------------------------------------------------------- - public LogType Type { get; private set; } - /// ----------------------------------------------------------------------------- /// /// Gets the description of LogEntry. @@ -60,6 +52,14 @@ public string Description } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the type of LogEntry. + /// + /// A LogType. + /// ----------------------------------------------------------------------------- + public LogType Type { get; private set; } + public override string ToString() { return string.Format("{0}: {1}", this.Type, this.Description); diff --git a/DNN Platform/Library/Services/Installer/Log/Logger.cs b/DNN Platform/Library/Services/Installer/Log/Logger.cs index bce0591997c..ec1c9aaaeac 100644 --- a/DNN Platform/Library/Services/Installer/Log/Logger.cs +++ b/DNN Platform/Library/Services/Installer/Log/Logger.cs @@ -35,6 +35,42 @@ public Logger() this._hasWarnings = Null.NullBoolean; } + public bool HasWarnings + { + get + { + return this._hasWarnings; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a List of Log Entries. + /// + /// A List of LogEntrys. + /// ----------------------------------------------------------------------------- + public IList Logs + { + get + { + return this._logs; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets a Flag that indicates whether the Installation was Valid. + /// + /// A List of LogEntrys. + /// ----------------------------------------------------------------------------- + public bool Valid + { + get + { + return this._valid; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Css Class used for Error Log Entries. @@ -49,24 +85,16 @@ public string ErrorClass { this._errorClass = "NormalRed"; } - + return this._errorClass; } - + set { this._errorClass = value; } } - public bool HasWarnings - { - get - { - return this._hasWarnings; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Css Class used for Log Entries that should be highlighted. @@ -81,30 +109,16 @@ public string HighlightClass { this._highlightClass = "NormalBold"; } - + return this._highlightClass; } - + set { this._highlightClass = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a List of Log Entries. - /// - /// A List of LogEntrys. - /// ----------------------------------------------------------------------------- - public IList Logs - { - get - { - return this._logs; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Css Class used for normal Log Entries. @@ -119,30 +133,16 @@ public string NormalClass { this._normalClass = "Normal"; } - + return this._normalClass; } - + set { this._normalClass = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets a Flag that indicates whether the Installation was Valid. - /// - /// A List of LogEntrys. - /// ----------------------------------------------------------------------------- - public bool Valid - { - get - { - return this._valid; - } - } - /// ----------------------------------------------------------------------------- /// /// The AddFailure method adds a new LogEntry of type Failure to the Logs collection. @@ -203,7 +203,7 @@ public void EndJob(string job) /// ----------------------------------------------------------------------------- /// /// GetLogsTable formats log entries in an HtmlTable. - /// + /// /// /// ----------------------------------------------------------------------------- public HtmlTable GetLogsTable() @@ -235,7 +235,7 @@ public HtmlTable GetLogsTable() tdDescription.Attributes.Add("class", this.NormalClass); break; } - + arrayTable.Rows.Add(tr); if (entry.Type == LogType.EndJob) { @@ -244,7 +244,7 @@ public HtmlTable GetLogsTable() arrayTable.Rows.Add(spaceTR); } } - + return arrayTable; } diff --git a/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs b/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs index a2de0f78afd..06613517993 100644 --- a/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs +++ b/DNN Platform/Library/Services/Installer/Packages/IPackageEditor.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Services.Installer.Packages public interface IPackageEditor { int PackageID { get; set; } - + bool IsWizard { get; set; } void Initialize(); diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs index 3382c575aff..1c77810e473 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageController.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageController.cs @@ -30,9 +30,9 @@ namespace DotNetNuke.Services.Installer.Packages /// /// ----------------------------------------------------------------------------- public class PackageController : ServiceLocator, IPackageController - { - private static readonly DataProvider provider = DataProvider.Instance(); - + { + private static readonly DataProvider provider = DataProvider.Instance(); + public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSettings) { bool bCanDelete = true; @@ -46,7 +46,7 @@ public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSe var dep = dependency; // Check if there is an alternative package - var packages = Instance.GetExtensionPackages( + var packages = Instance.GetExtensionPackages( package.PortalID, p => p.Name.Equals(dep.PackageName, StringComparison.OrdinalIgnoreCase) && p.Version >= dep.Version @@ -76,7 +76,7 @@ public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSe 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 @@ -86,7 +86,7 @@ public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSe { providerName = providerName.Substring(providerName.IndexOf(".", StringComparison.Ordinal) + 1); } - + switch (providerName) { case "SchedulingProvider": @@ -99,7 +99,7 @@ public static bool CanDeletePackage(PackageInfo package, PortalSettings portalSe providerName = "SearchDataStoreProvider"; break; } - + XPathNavigator providerNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/dotnetnuke/*[@defaultProvider='" + providerName + "']"); bCanDelete = providerNavigator == null; break; @@ -113,235 +113,6 @@ public static IDictionary GetModulePackagesInUse(int portalID, { 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(); - } - - private static void AddLog(PackageInfo package, EventLogController.EventLogType logType) - { - EventLogController.Instance.AddLog( - package, - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - string.Empty, - logType); - } - - private static void AddPackageInternal(PackageInfo package) - { - package.PackageID = provider.AddPackage( - package.PortalID, - package.Name, - package.FriendlyName, - package.Description, - package.PackageType, - package.Version.ToString(3), - package.License, - package.Manifest, - package.Owner, - package.Organization, - package.Url, - package.Email, - package.ReleaseNotes, - package.IsSystemPackage, - UserController.Instance.GetCurrentUserInfo().UserID, - package.FolderName, - package.IconFile); - - foreach (var dependency in package.Dependencies) - { - dependency.PackageId = package.PackageID; - SavePackageDependency(dependency); - } - - AddLog(package, EventLogController.EventLogType.PACKAGE_CREATED); - - ClearCache(package.PortalID); - } - - private static void ClearCache(int portalId) - { - DataCache.ClearPackagesCache(portalId); - } - - private static void ClearDependenciesCache() - { - DataCache.RemoveCache(DataCache.PackageDependenciesCacheKey); - } - - private static void DeletePackageInternal(PackageInfo package) - { - provider.DeletePackage(package.PackageID); - AddLog(package, EventLogController.EventLogType.PACKAGE_DELETED); - - if (PortalSettings.Current != null) - { - ClearCache(PortalSettings.Current.PortalId); - } - - ClearCache(Null.NullInteger); - } - - private static IEnumerable GetPackageDependencies() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.PackageDependenciesCacheKey, - DataCache.PackagesCacheTimeout, - DataCache.PackagesCachePriority), - c => CBO.FillCollection(provider.GetPackageDependencies())); - } - - private static void UpdatePackageInternal(PackageInfo package) - { - provider.UpdatePackage( - package.PackageID, - package.PortalID, - package.FriendlyName, - package.Description, - package.PackageType, - package.Version.ToString(3), - package.License, - package.Manifest, - package.Owner, - package.Organization, - package.Url, - package.Email, - package.ReleaseNotes, - package.IsSystemPackage, - UserController.Instance.GetCurrentUserInfo().UserID, - package.FolderName, - package.IconFile); - - foreach (var dependency in package.Dependencies) - { - dependency.PackageId = package.PackageID; - SavePackageDependency(dependency); - } - - AddLog(package, EventLogController.EventLogType.PACKAGE_UPDATED); - - ClearCache(package.PortalID); - } - - private static void SavePackageDependency(PackageDependencyInfo dependency) - { - dependency.PackageDependencyId = provider.SavePackageDependency(dependency.PackageDependencyId, dependency.PackageId, dependency.PackageName, - dependency.Version.ToString()); - - ClearDependenciesCache(); - } - - public PackageInfo GetExtensionPackage(int portalId, Func predicate, bool useCopy) - { - var package = this.GetExtensionPackages(portalId).FirstOrDefault(predicate); - - if (package != null && useCopy) - { - return package.Clone(); - } - - return package; - } - - public IList GetExtensionPackages(int portalId) - { - var cacheKey = string.Format(DataCache.PackagesCacheKey, portalId); - var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.PackagesCacheTimeout, DataCache.PackagesCachePriority, portalId); - return CBO.GetCachedObject>( - cacheItemArgs, - c => CBO.FillCollection(provider.GetPackages(portalId))); - } - - public IList GetExtensionPackages(int portalId, Func predicate) - { - return this.GetExtensionPackages(portalId).Where(predicate).ToList(); - } - - /// - /// Save or update the package. - /// - /// - public void SaveExtensionPackage(PackageInfo package) - { - if (package.PackageID == Null.NullInteger) - { - AddPackageInternal(package); - } - else - { - UpdatePackageInternal(package); - } - } - - public PackageType GetExtensionPackageType(Func predicate) - { - return this.GetExtensionPackageTypes().SingleOrDefault(predicate); - } - - public IList GetExtensionPackageTypes() - { - return CBO.GetCachedObject>( - new CacheItemArgs( - DataCache.PackageTypesCacheKey, - DataCache.PackageTypesCacheTimeout, - DataCache.PackageTypesCachePriority), - c => CBO.FillCollection(provider.GetPackageTypes())); - } - - public IList GetPackageDependencies(Func predicate) - { - return GetPackageDependencies().Where(predicate).ToList(); - } public static void ParsePackage(string file, string installPath, Dictionary packages, List invalidPackages) { @@ -401,7 +172,7 @@ public static void ParsePackage(string file, string installPath, Dictionary predicate) + { + return this.GetExtensionPackage(portalId, predicate, false); + } + + public PackageInfo GetExtensionPackage(int portalId, Func predicate, bool useCopy) + { + var package = this.GetExtensionPackages(portalId).FirstOrDefault(predicate); + + if (package != null && useCopy) + { + return package.Clone(); + } + + return package; + } + + public IList GetExtensionPackages(int portalId) + { + var cacheKey = string.Format(DataCache.PackagesCacheKey, portalId); + var cacheItemArgs = new CacheItemArgs(cacheKey, DataCache.PackagesCacheTimeout, DataCache.PackagesCachePriority, portalId); + return CBO.GetCachedObject>( + cacheItemArgs, + c => CBO.FillCollection(provider.GetPackages(portalId))); + } + + public IList GetExtensionPackages(int portalId, Func predicate) + { + return this.GetExtensionPackages(portalId).Where(predicate).ToList(); + } + + /// + /// Save or update the package. + /// + /// + public void SaveExtensionPackage(PackageInfo package) + { + if (package.PackageID == Null.NullInteger) + { + AddPackageInternal(package); + } + else + { + UpdatePackageInternal(package); + } + } + + public PackageType GetExtensionPackageType(Func predicate) + { + return this.GetExtensionPackageTypes().SingleOrDefault(predicate); + } + + public IList GetExtensionPackageTypes() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PackageTypesCacheKey, + DataCache.PackageTypesCacheTimeout, + DataCache.PackageTypesCachePriority), + c => CBO.FillCollection(provider.GetPackageTypes())); + } + + public IList GetPackageDependencies(Func predicate) + { + return GetPackageDependencies().Where(predicate).ToList(); + } + + internal static string GetSpecificFolderName(XPathNavigator manifestNav, string xpath, string elementName, string startWith) + { + string result = string.Empty; + var foldernameNav = manifestNav.Select(xpath); + + if (foldernameNav != null) + { + while (foldernameNav.MoveNext()) + { + var elementValue = Util.ReadElement(foldernameNav.Current, elementName); + if (!string.IsNullOrEmpty(elementValue) && elementValue.StartsWith(startWith)) + { + result = elementValue; + break; + } + } + } + + return result; + } + + protected override Func GetFactory() + { + return () => new PackageController(); + } + + private static void AddLog(PackageInfo package, EventLogController.EventLogType logType) + { + EventLogController.Instance.AddLog( + package, + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + string.Empty, + logType); + } + + private static void AddPackageInternal(PackageInfo package) + { + package.PackageID = provider.AddPackage( + package.PortalID, + package.Name, + package.FriendlyName, + package.Description, + package.PackageType, + package.Version.ToString(3), + package.License, + package.Manifest, + package.Owner, + package.Organization, + package.Url, + package.Email, + package.ReleaseNotes, + package.IsSystemPackage, + UserController.Instance.GetCurrentUserInfo().UserID, + package.FolderName, + package.IconFile); + + foreach (var dependency in package.Dependencies) + { + dependency.PackageId = package.PackageID; + SavePackageDependency(dependency); + } + + AddLog(package, EventLogController.EventLogType.PACKAGE_CREATED); + + ClearCache(package.PortalID); + } + + private static void ClearCache(int portalId) + { + DataCache.ClearPackagesCache(portalId); + } + + private static void ClearDependenciesCache() + { + DataCache.RemoveCache(DataCache.PackageDependenciesCacheKey); + } + + private static void DeletePackageInternal(PackageInfo package) + { + provider.DeletePackage(package.PackageID); + AddLog(package, EventLogController.EventLogType.PACKAGE_DELETED); + + if (PortalSettings.Current != null) + { + ClearCache(PortalSettings.Current.PortalId); + } + + ClearCache(Null.NullInteger); + } + + private static IEnumerable GetPackageDependencies() + { + return CBO.GetCachedObject>( + new CacheItemArgs( + DataCache.PackageDependenciesCacheKey, + DataCache.PackagesCacheTimeout, + DataCache.PackagesCachePriority), + c => CBO.FillCollection(provider.GetPackageDependencies())); + } + + private static void UpdatePackageInternal(PackageInfo package) + { + provider.UpdatePackage( + package.PackageID, + package.PortalID, + package.FriendlyName, + package.Description, + package.PackageType, + package.Version.ToString(3), + package.License, + package.Manifest, + package.Owner, + package.Organization, + package.Url, + package.Email, + package.ReleaseNotes, + package.IsSystemPackage, + UserController.Instance.GetCurrentUserInfo().UserID, + package.FolderName, + package.IconFile); + + foreach (var dependency in package.Dependencies) + { + dependency.PackageId = package.PackageID; + SavePackageDependency(dependency); + } + + AddLog(package, EventLogController.EventLogType.PACKAGE_UPDATED); + + ClearCache(package.PortalID); + } + + private static void SavePackageDependency(PackageDependencyInfo dependency) + { + dependency.PackageDependencyId = provider.SavePackageDependency(dependency.PackageDependencyId, dependency.PackageId, dependency.PackageName, + dependency.Version.ToString()); + + ClearDependenciesCache(); + } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventArgs.cs b/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventArgs.cs index 93638f32359..47bc579524d 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventArgs.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageCreatedEventArgs.cs @@ -17,10 +17,10 @@ namespace DotNetNuke.Services.Installer.Packages /// ----------------------------------------------------------------------------- public class PackageCreatedEventArgs : EventArgs { - private readonly PackageInfo _Package; - + private readonly PackageInfo _Package; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Builds a new PackageCreatedEventArgs. /// diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs b/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs index 1c14dc9fe0d..e61942f949d 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageDependencyInfo.cs @@ -10,11 +10,11 @@ namespace DotNetNuke.Services.Installer.Packages public class PackageDependencyInfo { public int PackageDependencyId { get; set; } - + public int PackageId { get; set; } - + public string PackageName { get; set; } - + public Version Version { get; set; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs b/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs index ee5cbc9e5b6..50ed4af6d4b 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageEditorBase.cs @@ -18,7 +18,7 @@ public class PackageEditorBase : ModuleUserControlBase, IPackageEditor private bool _IsWizard = Null.NullBoolean; private PackageInfo _Package; private int _PackageID = Null.NullInteger; - + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Package ID. @@ -31,7 +31,7 @@ public int PackageID { return this._PackageID; } - + set { this._PackageID = value; @@ -50,7 +50,7 @@ public bool IsWizard { return this._IsWizard; } - + set { this._IsWizard = value; @@ -83,10 +83,10 @@ protected PackageInfo Package { this._Package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, (p) => p.PackageID == this.PackageID); } - + return this._Package; } - } + } /// ----------------------------------------------------------------------------- /// @@ -104,8 +104,8 @@ public virtual void Initialize() /// ----------------------------------------------------------------------------- public virtual void UpdatePackage() { - } - + } + protected override void OnInit(EventArgs e) { this.ID = this.EditorID; diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs index 039477efce7..822f1c0357e 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageInfo.cs @@ -23,22 +23,22 @@ namespace DotNetNuke.Services.Installer.Packages [Serializable] public class PackageInfo : BaseEntityInfo { - private IList _dependencies; - + private IList _dependencies; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallPackage instance as defined by the /// Parameters. /// /// ----------------------------------------------------------------------------- - public PackageInfo(InstallerInfo info) + public PackageInfo(InstallerInfo info) : this() { this.AttachInstallerInfo(info); - } - - /// + } + + /// /// Initializes a new instance of the class. /// This Constructor creates a new InstallPackage instance. /// @@ -64,6 +64,50 @@ public IList Dependencies } } + /// ----------------------------------------------------------------------------- + /// + /// Gets a Dictionary of Files that are included in the Package. + /// + /// A Dictionary(Of String, InstallFile). + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public Dictionary Files + { + get + { + return this.InstallerInfo.Files; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the InstallMode. + /// + /// An InstallMode value. + /// ----------------------------------------------------------------------------- + public InstallMode InstallMode + { + get + { + return this.InstallerInfo.InstallMode; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Logger. + /// + /// An Logger object. + /// ----------------------------------------------------------------------------- + [XmlIgnore] + public Logger Log + { + get + { + return this.InstallerInfo.Log; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Email for this package. @@ -88,21 +132,6 @@ public IList Dependencies /// ----------------------------------------------------------------------------- public string FileName { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets a Dictionary of Files that are included in the Package. - /// - /// A Dictionary(Of String, InstallFile). - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public Dictionary Files - { - get - { - return this.InstallerInfo.Files; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets the name (path) of the folder where the package is installed. @@ -144,20 +173,6 @@ public Dictionary Files [XmlIgnore] public InstallerInfo InstallerInfo { get; private set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the InstallMode. - /// - /// An InstallMode value. - /// ----------------------------------------------------------------------------- - public InstallMode InstallMode - { - get - { - return this.InstallerInfo.InstallMode; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and Sets whether this package is a "system" Package. @@ -183,21 +198,6 @@ public InstallMode InstallMode /// ----------------------------------------------------------------------------- public string License { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Logger. - /// - /// An Logger object. - /// ----------------------------------------------------------------------------- - [XmlIgnore] - public Logger Log - { - get - { - return this.InstallerInfo.Log; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets the Manifest of this package. @@ -295,29 +295,29 @@ 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/Packages/PackageType.cs b/DNN Platform/Library/Services/Installer/Packages/PackageType.cs index 6ecc854c221..0ef983d94f7 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageType.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageType.cs @@ -32,11 +32,11 @@ public PackageTypeMemberNameFixer() public class PackageType : PackageTypeMemberNameFixer { public string Description { get; set; } - + public string EditorControlSrc { get; set; } - + public SecurityAccessLevel SecurityAccessLevel { get; set; } - + public bool SupportsSideBySideInstallation { get; set; } } } diff --git a/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs b/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs index db7c2dfd0af..8df9f194ac8 100644 --- a/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs +++ b/DNN Platform/Library/Services/Installer/Packages/PackageTypeEditControl.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.Services.Installer.Packages.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:PackageTypeEditControl runat=server>")] public class PackageTypeEditControl : TextEditControl - { + { /// ----------------------------------------------------------------------------- /// /// RenderEditMode renders the Edit mode of the control. @@ -72,6 +72,6 @@ protected override void RenderEditMode(HtmlTextWriter writer) // Close Select Tag writer.RenderEndTag(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Util.cs b/DNN Platform/Library/Services/Installer/Util.cs index 94cae3642ae..33911d7a028 100644 --- a/DNN Platform/Library/Services/Installer/Util.cs +++ b/DNN Platform/Library/Services/Installer/Util.cs @@ -31,248 +31,6 @@ namespace DotNetNuke.Services.Installer /// 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"); - public static string ASSEMBLY_InUse = GetLocalizedString("ASSEMBLY_InUse"); - public static string ASSEMBLY_Registered = GetLocalizedString("ASSEMBLY_Registered"); - public static string ASSEMBLY_UnRegistered = GetLocalizedString("ASSEMBLY_UnRegistered"); - public static string ASSEMBLY_Updated = GetLocalizedString("ASSEMBLY_Updated"); - public static string AUTHENTICATION_ReadSuccess = GetLocalizedString("AUTHENTICATION_ReadSuccess"); - public static string AUTHENTICATION_LoginSrcMissing = GetLocalizedString("AUTHENTICATION_LoginSrcMissing"); - public static string AUTHENTICATION_Registered = GetLocalizedString("AUTHENTICATION_Registered"); - public static string AUTHENTICATION_SettingsSrcMissing = GetLocalizedString("AUTHENTICATION_SettingsSrcMissing"); - public static string AUTHENTICATION_TypeMissing = GetLocalizedString("AUTHENTICATION_TypeMissing"); - public static string AUTHENTICATION_UnRegistered = GetLocalizedString("AUTHENTICATION_UnRegistered"); - public static string CLEANUP_Processing = GetLocalizedString("CLEANUP_Processing"); - public static string CLEANUP_ProcessComplete = GetLocalizedString("CLEANUP_ProcessComplete"); - public static string CLEANUP_ProcessError = GetLocalizedString("CLEANUP_ProcessError"); - public static string COMPONENT_Installed = GetLocalizedString("COMPONENT_Installed"); - public static string COMPONENT_Skipped = GetLocalizedString("COMPONENT_Skipped"); - public static string COMPONENT_RolledBack = GetLocalizedString("COMPONENT_RolledBack"); - public static string COMPONENT_RollingBack = GetLocalizedString("COMPONENT_RollingBack"); - public static string COMPONENT_UnInstalled = GetLocalizedString("COMPONENT_UnInstalled"); - public static string CONFIG_Committed = GetLocalizedString("CONFIG_Committed"); - public static string CONFIG_RolledBack = GetLocalizedString("CONFIG_RolledBack"); - public static string CONFIG_Updated = GetLocalizedString("CONFIG_Updated"); - public static string DASHBOARD_ReadSuccess = GetLocalizedString("DASHBOARD_ReadSuccess"); - public static string DASHBOARD_SrcMissing = GetLocalizedString("DASHBOARD_SrcMissing"); - public static string DASHBOARD_Registered = GetLocalizedString("DASHBOARD_Registered"); - public static string DASHBOARD_KeyMissing = GetLocalizedString("DASHBOARD_KeyMissing"); - public static string DASHBOARD_LocalResourcesMissing = GetLocalizedString("DASHBOARD_LocalResourcesMissing"); - public static string DASHBOARD_UnRegistered = GetLocalizedString("DASHBOARD_UnRegistered"); - public static string DNN_Reading = GetLocalizedString("DNN_Reading"); - public static string DNN_ReadingComponent = GetLocalizedString("DNN_ReadingComponent"); - public static string DNN_ReadingPackage = GetLocalizedString("DNN_ReadingPackage"); - public static string DNN_Success = GetLocalizedString("DNN_Success"); - public static string EVENTMESSAGE_CommandMissing = GetLocalizedString("EVENTMESSAGE_CommandMissing"); - public static string EVENTMESSAGE_TypeMissing = GetLocalizedString("EVENTMESSAGE_TypeMissing"); - public static string EXCEPTION = GetLocalizedString("EXCEPTION"); - public static string EXCEPTION_FileLoad = GetLocalizedString("EXCEPTION_FileLoad"); - public static string EXCEPTION_FileRead = GetLocalizedString("EXCEPTION_FileRead"); - public static string EXCEPTION_GlobDotDotNotSupportedInCleanup = GetLocalizedString("EXCEPTION_GlobDotDotNotSupportedInCleanup"); - public static string EXCEPTION_InstallerCreate = GetLocalizedString("EXCEPTION_InstallerCreate"); - public static string EXCEPTION_MissingDnn = GetLocalizedString("EXCEPTION_MissingDnn"); - public static string EXCEPTION_MultipleDnn = GetLocalizedString("EXCEPTION_MultipleDnn"); - public static string EXCEPTION_NameMissing = GetLocalizedString("EXCEPTION_NameMissing"); - public static string EXCEPTION_Type = GetLocalizedString("EXCEPTION_Type"); - public static string EXCEPTION_TypeMissing = GetLocalizedString("EXCEPTION_TypeMissing"); - public static string EXCEPTION_VersionMissing = GetLocalizedString("EXCEPTION_VersionMissing"); - public static string FILE_CreateBackup = GetLocalizedString("FILE_CreateBackup"); - public static string FILE_Created = GetLocalizedString("FILE_Created"); - public static string FILE_Deleted = GetLocalizedString("FILE_Deleted"); - public static string FILE_Found = GetLocalizedString("FILE_Found"); - public static string FILE_Loading = GetLocalizedString("FILE_Loading"); - public static string FILE_NotAllowed = GetLocalizedString("FILE_NotAllowed"); - public static string FILE_NotFound = GetLocalizedString("FILE_NotFound"); - public static string FILE_ReadSuccess = GetLocalizedString("FILE_ReadSuccess"); - public static string FILE_RestoreBackup = GetLocalizedString("FILE_RestoreBackup"); - public static string FILES_CreatedResources = GetLocalizedString("FILES_CreatedResources"); - public static string FILES_Expanding = GetLocalizedString("FILES_Expanding"); - public static string FILES_Loading = GetLocalizedString("FILES_Loading"); - public static string FILES_Reading = GetLocalizedString("FILES_Reading"); - public static string FILES_ReadingEnd = GetLocalizedString("FILES_ReadingEnd"); - public static string FOLDER_Created = GetLocalizedString("FOLDER_Created"); - public static string FOLDER_Deleted = GetLocalizedString("FOLDER_Deleted"); - public static string FOLDER_DeletedBackup = GetLocalizedString("FOLDER_DeletedBackup"); - public static string INSTALL_Compatibility = GetLocalizedString("INSTALL_Compatibility"); - public static string INSTALL_Dependencies = GetLocalizedString("INSTALL_Dependencies"); - public static string INSTALL_Aborted = GetLocalizedString("INSTALL_Aborted"); - public static string INSTALL_Failed = GetLocalizedString("INSTALL_Failed"); - public static string INSTALL_Committed = GetLocalizedString("INSTALL_Committed"); - public static string INSTALL_Namespace = GetLocalizedString("INSTALL_Namespace"); - public static string INSTALL_Package = GetLocalizedString("INSTALL_Package"); - public static string INSTALL_Permissions = GetLocalizedString("INSTALL_Permissions"); - public static string INSTALL_Start = GetLocalizedString("INSTALL_Start"); - public static string INSTALL_Success = GetLocalizedString("INSTALL_Success"); - public static string INSTALL_Version = GetLocalizedString("INSTALL_Version"); - public static string LANGUAGE_PortalsEnabled = GetLocalizedString("LANGUAGE_PortalsEnabled"); - public static string LANGUAGE_Registered = GetLocalizedString("LANGUAGE_Registered"); - public static string LANGUAGE_UnRegistered = GetLocalizedString("LANGUAGE_UnRegistered"); - public static string LIBRARY_ReadSuccess = GetLocalizedString("LIBRARY_ReadSuccess"); - public static string LIBRARY_Registered = GetLocalizedString("LIBRARY_Registered"); - public static string LIBRARY_UnRegistered = GetLocalizedString("LIBRARY_UnRegistered"); - public static string MODULE_ControlKeyMissing = GetLocalizedString("MODULE_ControlKeyMissing"); - public static string MODULE_ControlTypeMissing = GetLocalizedString("MODULE_ControlTypeMissing"); - public static string MODULE_FriendlyNameMissing = GetLocalizedString("MODULE_FriendlyNameMissing"); - public static string MODULE_InvalidVersion = GetLocalizedString("MODULE_InvalidVersion"); - public static string MODULE_ReadSuccess = GetLocalizedString("MODULE_ReadSuccess"); - public static string MODULE_Registered = GetLocalizedString("MODULE_Registered"); - public static string MODULE_UnRegistered = GetLocalizedString("MODULE_UnRegistered"); - public static string MODULE_AdminPageAdded = GetLocalizedString("MODULE_AdminPageAdded"); - public static string MODULE_AdminPagemoduleAdded = GetLocalizedString("MODULE_AdminPagemoduleAdded"); - public static string MODULE_AdminPageRemoved = GetLocalizedString("MODULE_AdminPageRemoved"); - public static string MODULE_AdminPagemoduleRemoved = GetLocalizedString("MODULE_AdminPagemoduleRemoved"); - public static string MODULE_HostPageAdded = GetLocalizedString("MODULE_HostPageAdded"); - public static string MODULE_HostPagemoduleAdded = GetLocalizedString("MODULE_HostPagemoduleAdded"); - public static string MODULE_HostPageRemoved = GetLocalizedString("MODULE_HostPageRemoved"); - public static string MODULE_HostPagemoduleRemoved = GetLocalizedString("MODULE_HostPagemoduleRemoved"); - public static string PACKAGE_NoLicense = GetLocalizedString("PACKAGE_NoLicense"); - public static string PACKAGE_NoReleaseNotes = GetLocalizedString("PACKAGE_NoReleaseNotes"); - public static string PACKAGE_UnRecognizable = GetLocalizedString("PACKAGE_UnRecognizable"); - public static string SECURITY_Installer = GetLocalizedString("SECURITY_Installer"); - public static string SECURITY_NotRegistered = GetLocalizedString("SECURITY_NotRegistered"); - public static string SKIN_BeginProcessing = GetLocalizedString("SKIN_BeginProcessing"); - public static string SKIN_Installed = GetLocalizedString("SKIN_Installed"); - public static string SKIN_EndProcessing = GetLocalizedString("SKIN_EndProcessing"); - public static string SKIN_Registered = GetLocalizedString("SKIN_Registered"); - public static string SKIN_UnRegistered = GetLocalizedString("SKIN_UnRegistered"); - public static string SQL_Begin = GetLocalizedString("SQL_Begin"); - public static string SQL_BeginFile = GetLocalizedString("SQL_BeginFile"); - public static string SQL_BeginUnInstall = GetLocalizedString("SQL_BeginUnInstall"); - public static string SQL_Committed = GetLocalizedString("SQL_Committed"); - public static string SQL_End = GetLocalizedString("SQL_End"); - public static string SQL_EndFile = GetLocalizedString("SQL_EndFile"); - public static string SQL_EndUnInstall = GetLocalizedString("SQL_EndUnInstall"); - public static string SQL_Exceptions = GetLocalizedString("SQL_Exceptions"); - public static string SQL_Executing = GetLocalizedString("SQL_Executing"); - public static string SQL_RolledBack = GetLocalizedString("SQL_RolledBack"); - public static string UNINSTALL_Start = GetLocalizedString("UNINSTALL_Start"); - public static string UNINSTALL_StartComp = GetLocalizedString("UNINSTALL_StartComp"); - public static string UNINSTALL_Failure = GetLocalizedString("UNINSTALL_Failure"); - public static string UNINSTALL_Success = GetLocalizedString("UNINSTALL_Success"); - public static string UNINSTALL_SuccessComp = GetLocalizedString("UNINSTALL_SuccessComp"); - public static string UNINSTALL_Warnings = GetLocalizedString("UNINSTALL_Warnings"); - public static string UNINSTALL_WarningsComp = GetLocalizedString("UNINSTALL_WarningsComp"); - public static string URLPROVIDER_NameMissing = GetLocalizedString("URLPROVIDER_NameMissing"); - public static string URLPROVIDER_ReadSuccess = GetLocalizedString("URLPROVIDER_ReadSuccess"); - public static string URLPROVIDER_Registered = GetLocalizedString("URLPROVIDER_Registered"); - public static string URLPROVIDER_TypeMissing = GetLocalizedString("URLPROVIDER_TypeMissing"); - public static string URLPROVIDER_UnRegistered = GetLocalizedString("URLPROVIDER_UnRegistered"); - public static string WRITER_AddFileToManifest = GetLocalizedString("WRITER_AddFileToManifest"); - public static string WRITER_CreateArchive = GetLocalizedString("WRITER_CreateArchive"); - public static string WRITER_CreatedManifest = GetLocalizedString("WRITER_CreatedManifest"); - public static string WRITER_CreatedPackage = GetLocalizedString("WRITER_CreatedPackage"); - public static string WRITER_CreatingManifest = GetLocalizedString("WRITER_CreatingManifest"); - public static string WRITER_CreatingPackage = GetLocalizedString("WRITER_CreatingPackage"); - 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}"; - - /// ----------------------------------------------------------------------------- - /// - /// 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 - - /// ----------------------------------------------------------------------------- - /// - /// The StreamToStream method reads a source stream and wrtites it to a destination stream. - /// - /// The Source Stream. - /// The Destination Stream. - private static void StreamToStream(Stream sourceStream, Stream destStream) - { - var buf = new byte[1024]; - int count; - do - { - // Read the chunk from the source - count = sourceStream.Read(buf, 0, 1024); - - // Write the chunk to the destination - destStream.Write(buf, 0, count); - } - while (count > 0); - destStream.Flush(); - } - - private static void TryDeleteFolder(DirectoryInfo folder, Logger log) - { - if (folder.GetFiles().Length == 0 && folder.GetDirectories().Length == 0) - { - folder.Delete(); - log.AddInfo(string.Format(FOLDER_Deleted, folder.Name)); - TryDeleteFolder(folder.Parent, log); - } - } - - private static string ValidateNode(string propValue, bool isRequired, Logger log, string logmessage, string defaultValue) - { - if (string.IsNullOrEmpty(propValue)) - { - if (isRequired) - { - // Log Error - log.AddFailure(logmessage); - } - else - { - // Use Default - propValue = defaultValue; - } - } - - return propValue; - } - /// ----------------------------------------------------------------------------- /// /// The DeleteFile method deletes a file. @@ -779,5 +537,247 @@ public static void DeployExtension(WebResponse wr, string myfile, string install } } } + + /// ----------------------------------------------------------------------------- + /// + /// The StreamToStream method reads a source stream and wrtites it to a destination stream. + /// + /// The Source Stream. + /// The Destination Stream. + private static void StreamToStream(Stream sourceStream, Stream destStream) + { + var buf = new byte[1024]; + int count; + do + { + // Read the chunk from the source + count = sourceStream.Read(buf, 0, 1024); + + // Write the chunk to the destination + destStream.Write(buf, 0, count); + } + while (count > 0); + destStream.Flush(); + } + + private static void TryDeleteFolder(DirectoryInfo folder, Logger log) + { + if (folder.GetFiles().Length == 0 && folder.GetDirectories().Length == 0) + { + folder.Delete(); + log.AddInfo(string.Format(FOLDER_Deleted, folder.Name)); + TryDeleteFolder(folder.Parent, log); + } + } + + private static string ValidateNode(string propValue, bool isRequired, Logger log, string logmessage, string defaultValue) + { + if (string.IsNullOrEmpty(propValue)) + { + if (isRequired) + { + // Log Error + log.AddFailure(logmessage); + } + else + { + // Use Default + propValue = defaultValue; + } + } + + return propValue; + } + + // 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"); + public static string ASSEMBLY_InUse = GetLocalizedString("ASSEMBLY_InUse"); + public static string ASSEMBLY_Registered = GetLocalizedString("ASSEMBLY_Registered"); + public static string ASSEMBLY_UnRegistered = GetLocalizedString("ASSEMBLY_UnRegistered"); + public static string ASSEMBLY_Updated = GetLocalizedString("ASSEMBLY_Updated"); + public static string AUTHENTICATION_ReadSuccess = GetLocalizedString("AUTHENTICATION_ReadSuccess"); + public static string AUTHENTICATION_LoginSrcMissing = GetLocalizedString("AUTHENTICATION_LoginSrcMissing"); + public static string AUTHENTICATION_Registered = GetLocalizedString("AUTHENTICATION_Registered"); + public static string AUTHENTICATION_SettingsSrcMissing = GetLocalizedString("AUTHENTICATION_SettingsSrcMissing"); + public static string AUTHENTICATION_TypeMissing = GetLocalizedString("AUTHENTICATION_TypeMissing"); + public static string AUTHENTICATION_UnRegistered = GetLocalizedString("AUTHENTICATION_UnRegistered"); + public static string CLEANUP_Processing = GetLocalizedString("CLEANUP_Processing"); + public static string CLEANUP_ProcessComplete = GetLocalizedString("CLEANUP_ProcessComplete"); + public static string CLEANUP_ProcessError = GetLocalizedString("CLEANUP_ProcessError"); + public static string COMPONENT_Installed = GetLocalizedString("COMPONENT_Installed"); + public static string COMPONENT_Skipped = GetLocalizedString("COMPONENT_Skipped"); + public static string COMPONENT_RolledBack = GetLocalizedString("COMPONENT_RolledBack"); + public static string COMPONENT_RollingBack = GetLocalizedString("COMPONENT_RollingBack"); + public static string COMPONENT_UnInstalled = GetLocalizedString("COMPONENT_UnInstalled"); + public static string CONFIG_Committed = GetLocalizedString("CONFIG_Committed"); + public static string CONFIG_RolledBack = GetLocalizedString("CONFIG_RolledBack"); + public static string CONFIG_Updated = GetLocalizedString("CONFIG_Updated"); + public static string DASHBOARD_ReadSuccess = GetLocalizedString("DASHBOARD_ReadSuccess"); + public static string DASHBOARD_SrcMissing = GetLocalizedString("DASHBOARD_SrcMissing"); + public static string DASHBOARD_Registered = GetLocalizedString("DASHBOARD_Registered"); + public static string DASHBOARD_KeyMissing = GetLocalizedString("DASHBOARD_KeyMissing"); + public static string DASHBOARD_LocalResourcesMissing = GetLocalizedString("DASHBOARD_LocalResourcesMissing"); + public static string DASHBOARD_UnRegistered = GetLocalizedString("DASHBOARD_UnRegistered"); + public static string DNN_Reading = GetLocalizedString("DNN_Reading"); + public static string DNN_ReadingComponent = GetLocalizedString("DNN_ReadingComponent"); + public static string DNN_ReadingPackage = GetLocalizedString("DNN_ReadingPackage"); + public static string DNN_Success = GetLocalizedString("DNN_Success"); + public static string EVENTMESSAGE_CommandMissing = GetLocalizedString("EVENTMESSAGE_CommandMissing"); + public static string EVENTMESSAGE_TypeMissing = GetLocalizedString("EVENTMESSAGE_TypeMissing"); + public static string EXCEPTION = GetLocalizedString("EXCEPTION"); + public static string EXCEPTION_FileLoad = GetLocalizedString("EXCEPTION_FileLoad"); + public static string EXCEPTION_FileRead = GetLocalizedString("EXCEPTION_FileRead"); + public static string EXCEPTION_GlobDotDotNotSupportedInCleanup = GetLocalizedString("EXCEPTION_GlobDotDotNotSupportedInCleanup"); + public static string EXCEPTION_InstallerCreate = GetLocalizedString("EXCEPTION_InstallerCreate"); + public static string EXCEPTION_MissingDnn = GetLocalizedString("EXCEPTION_MissingDnn"); + public static string EXCEPTION_MultipleDnn = GetLocalizedString("EXCEPTION_MultipleDnn"); + public static string EXCEPTION_NameMissing = GetLocalizedString("EXCEPTION_NameMissing"); + public static string EXCEPTION_Type = GetLocalizedString("EXCEPTION_Type"); + public static string EXCEPTION_TypeMissing = GetLocalizedString("EXCEPTION_TypeMissing"); + public static string EXCEPTION_VersionMissing = GetLocalizedString("EXCEPTION_VersionMissing"); + public static string FILE_CreateBackup = GetLocalizedString("FILE_CreateBackup"); + public static string FILE_Created = GetLocalizedString("FILE_Created"); + public static string FILE_Deleted = GetLocalizedString("FILE_Deleted"); + public static string FILE_Found = GetLocalizedString("FILE_Found"); + public static string FILE_Loading = GetLocalizedString("FILE_Loading"); + public static string FILE_NotAllowed = GetLocalizedString("FILE_NotAllowed"); + public static string FILE_NotFound = GetLocalizedString("FILE_NotFound"); + public static string FILE_ReadSuccess = GetLocalizedString("FILE_ReadSuccess"); + public static string FILE_RestoreBackup = GetLocalizedString("FILE_RestoreBackup"); + public static string FILES_CreatedResources = GetLocalizedString("FILES_CreatedResources"); + public static string FILES_Expanding = GetLocalizedString("FILES_Expanding"); + public static string FILES_Loading = GetLocalizedString("FILES_Loading"); + public static string FILES_Reading = GetLocalizedString("FILES_Reading"); + public static string FILES_ReadingEnd = GetLocalizedString("FILES_ReadingEnd"); + public static string FOLDER_Created = GetLocalizedString("FOLDER_Created"); + public static string FOLDER_Deleted = GetLocalizedString("FOLDER_Deleted"); + public static string FOLDER_DeletedBackup = GetLocalizedString("FOLDER_DeletedBackup"); + public static string INSTALL_Compatibility = GetLocalizedString("INSTALL_Compatibility"); + public static string INSTALL_Dependencies = GetLocalizedString("INSTALL_Dependencies"); + public static string INSTALL_Aborted = GetLocalizedString("INSTALL_Aborted"); + public static string INSTALL_Failed = GetLocalizedString("INSTALL_Failed"); + public static string INSTALL_Committed = GetLocalizedString("INSTALL_Committed"); + public static string INSTALL_Namespace = GetLocalizedString("INSTALL_Namespace"); + public static string INSTALL_Package = GetLocalizedString("INSTALL_Package"); + public static string INSTALL_Permissions = GetLocalizedString("INSTALL_Permissions"); + public static string INSTALL_Start = GetLocalizedString("INSTALL_Start"); + public static string INSTALL_Success = GetLocalizedString("INSTALL_Success"); + public static string INSTALL_Version = GetLocalizedString("INSTALL_Version"); + public static string LANGUAGE_PortalsEnabled = GetLocalizedString("LANGUAGE_PortalsEnabled"); + public static string LANGUAGE_Registered = GetLocalizedString("LANGUAGE_Registered"); + public static string LANGUAGE_UnRegistered = GetLocalizedString("LANGUAGE_UnRegistered"); + public static string LIBRARY_ReadSuccess = GetLocalizedString("LIBRARY_ReadSuccess"); + public static string LIBRARY_Registered = GetLocalizedString("LIBRARY_Registered"); + public static string LIBRARY_UnRegistered = GetLocalizedString("LIBRARY_UnRegistered"); + public static string MODULE_ControlKeyMissing = GetLocalizedString("MODULE_ControlKeyMissing"); + public static string MODULE_ControlTypeMissing = GetLocalizedString("MODULE_ControlTypeMissing"); + public static string MODULE_FriendlyNameMissing = GetLocalizedString("MODULE_FriendlyNameMissing"); + public static string MODULE_InvalidVersion = GetLocalizedString("MODULE_InvalidVersion"); + public static string MODULE_ReadSuccess = GetLocalizedString("MODULE_ReadSuccess"); + public static string MODULE_Registered = GetLocalizedString("MODULE_Registered"); + public static string MODULE_UnRegistered = GetLocalizedString("MODULE_UnRegistered"); + public static string MODULE_AdminPageAdded = GetLocalizedString("MODULE_AdminPageAdded"); + public static string MODULE_AdminPagemoduleAdded = GetLocalizedString("MODULE_AdminPagemoduleAdded"); + public static string MODULE_AdminPageRemoved = GetLocalizedString("MODULE_AdminPageRemoved"); + public static string MODULE_AdminPagemoduleRemoved = GetLocalizedString("MODULE_AdminPagemoduleRemoved"); + public static string MODULE_HostPageAdded = GetLocalizedString("MODULE_HostPageAdded"); + public static string MODULE_HostPagemoduleAdded = GetLocalizedString("MODULE_HostPagemoduleAdded"); + public static string MODULE_HostPageRemoved = GetLocalizedString("MODULE_HostPageRemoved"); + public static string MODULE_HostPagemoduleRemoved = GetLocalizedString("MODULE_HostPagemoduleRemoved"); + public static string PACKAGE_NoLicense = GetLocalizedString("PACKAGE_NoLicense"); + public static string PACKAGE_NoReleaseNotes = GetLocalizedString("PACKAGE_NoReleaseNotes"); + public static string PACKAGE_UnRecognizable = GetLocalizedString("PACKAGE_UnRecognizable"); + public static string SECURITY_Installer = GetLocalizedString("SECURITY_Installer"); + public static string SECURITY_NotRegistered = GetLocalizedString("SECURITY_NotRegistered"); + public static string SKIN_BeginProcessing = GetLocalizedString("SKIN_BeginProcessing"); + public static string SKIN_Installed = GetLocalizedString("SKIN_Installed"); + public static string SKIN_EndProcessing = GetLocalizedString("SKIN_EndProcessing"); + public static string SKIN_Registered = GetLocalizedString("SKIN_Registered"); + public static string SKIN_UnRegistered = GetLocalizedString("SKIN_UnRegistered"); + public static string SQL_Begin = GetLocalizedString("SQL_Begin"); + public static string SQL_BeginFile = GetLocalizedString("SQL_BeginFile"); + public static string SQL_BeginUnInstall = GetLocalizedString("SQL_BeginUnInstall"); + public static string SQL_Committed = GetLocalizedString("SQL_Committed"); + public static string SQL_End = GetLocalizedString("SQL_End"); + public static string SQL_EndFile = GetLocalizedString("SQL_EndFile"); + public static string SQL_EndUnInstall = GetLocalizedString("SQL_EndUnInstall"); + public static string SQL_Exceptions = GetLocalizedString("SQL_Exceptions"); + public static string SQL_Executing = GetLocalizedString("SQL_Executing"); + public static string SQL_RolledBack = GetLocalizedString("SQL_RolledBack"); + public static string UNINSTALL_Start = GetLocalizedString("UNINSTALL_Start"); + public static string UNINSTALL_StartComp = GetLocalizedString("UNINSTALL_StartComp"); + public static string UNINSTALL_Failure = GetLocalizedString("UNINSTALL_Failure"); + public static string UNINSTALL_Success = GetLocalizedString("UNINSTALL_Success"); + public static string UNINSTALL_SuccessComp = GetLocalizedString("UNINSTALL_SuccessComp"); + public static string UNINSTALL_Warnings = GetLocalizedString("UNINSTALL_Warnings"); + public static string UNINSTALL_WarningsComp = GetLocalizedString("UNINSTALL_WarningsComp"); + public static string URLPROVIDER_NameMissing = GetLocalizedString("URLPROVIDER_NameMissing"); + public static string URLPROVIDER_ReadSuccess = GetLocalizedString("URLPROVIDER_ReadSuccess"); + public static string URLPROVIDER_Registered = GetLocalizedString("URLPROVIDER_Registered"); + public static string URLPROVIDER_TypeMissing = GetLocalizedString("URLPROVIDER_TypeMissing"); + public static string URLPROVIDER_UnRegistered = GetLocalizedString("URLPROVIDER_UnRegistered"); + public static string WRITER_AddFileToManifest = GetLocalizedString("WRITER_AddFileToManifest"); + public static string WRITER_CreateArchive = GetLocalizedString("WRITER_CreateArchive"); + public static string WRITER_CreatedManifest = GetLocalizedString("WRITER_CreatedManifest"); + public static string WRITER_CreatedPackage = GetLocalizedString("WRITER_CreatedPackage"); + public static string WRITER_CreatingManifest = GetLocalizedString("WRITER_CreatingManifest"); + public static string WRITER_CreatingPackage = GetLocalizedString("WRITER_CreatingPackage"); + 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}"; + + /// ----------------------------------------------------------------------------- + /// + /// 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 } } diff --git a/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs index 6972685b0f0..28277c89ef5 100644 --- a/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/AssemblyComponentWriter.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class AssemblyComponentWriter : FileComponentWriter { - public AssemblyComponentWriter(string basePath, Dictionary assemblies, PackageInfo package) + public AssemblyComponentWriter(string basePath, Dictionary assemblies, PackageInfo package) : base(basePath, assemblies, package) { } diff --git a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs index 19de549d86d..86e2d7e34c6 100644 --- a/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/AuthenticationPackageWriter.cs @@ -17,35 +17,35 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class AuthenticationPackageWriter : PackageWriterBase - { - public AuthenticationPackageWriter(PackageInfo package) + { + public AuthenticationPackageWriter(PackageInfo package) : base(package) { this.AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); this.Initialize(); } - public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) + public AuthenticationPackageWriter(AuthenticationInfo authSystem, PackageInfo package) : base(package) { this.AuthSystem = authSystem; this.Initialize(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the associated Authentication System. /// /// An AuthenticationInfo object. /// ----------------------------------------------------------------------------- - public AuthenticationInfo AuthSystem { get; set; } - + 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); @@ -72,6 +72,6 @@ private void WriteAuthenticationComponent(XmlWriter writer) // End component Element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs index bd1f3fd0418..22cc69b6302 100644 --- a/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/CleanupComponentWriter.cs @@ -16,12 +16,12 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class CleanupComponentWriter - { + { private readonly SortedList _Files; - private string _BasePath; - + private string _BasePath; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the ContainerComponentWriter. /// @@ -32,8 +32,8 @@ public CleanupComponentWriter(string basePath, SortedList f { this._Files = files; this._BasePath = basePath; - } - + } + public virtual void WriteManifest(XmlWriter writer) { foreach (KeyValuePair kvp in this._Files) @@ -47,6 +47,6 @@ public virtual void WriteManifest(XmlWriter writer) // End component Element writer.WriteEndElement(); } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs index 6426401cde2..96ed190d133 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ContainerComponentWriter.cs @@ -16,9 +16,9 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class ContainerComponentWriter : SkinComponentWriter - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the ContainerComponentWriter. /// @@ -27,7 +27,7 @@ public class ContainerComponentWriter : SkinComponentWriter /// A Dictionary of files. /// /// ----------------------------------------------------------------------------- - public ContainerComponentWriter(string containerName, string basePath, Dictionary files, PackageInfo package) + public ContainerComponentWriter(string containerName, string basePath, Dictionary files, PackageInfo package) : base(containerName, basePath, files, package) { } diff --git a/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs index 65e323df8fd..942664edcd0 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ContainerPackageWriter.cs @@ -17,13 +17,13 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class ContainerPackageWriter : SkinPackageWriter { - public ContainerPackageWriter(PackageInfo package) + public ContainerPackageWriter(PackageInfo package) : base(package) { this.BasePath = "Portals\\_default\\Containers\\" + this.SkinPackage.SkinName; } - public ContainerPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) + public ContainerPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) : base(skinPackage, package) { this.BasePath = "Portals\\_default\\Containers\\" + skinPackage.SkinName; diff --git a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs index 8efe1c39906..1754c30e5f1 100644 --- a/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/FileComponentWriter.cs @@ -18,15 +18,15 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class FileComponentWriter - { + { private readonly string _BasePath; private readonly Dictionary _Files; private readonly PackageInfo _Package; private int _InstallOrder = Null.NullInteger; - private int _UnInstallOrder = Null.NullInteger; - + private int _UnInstallOrder = Null.NullInteger; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the FileComponentWriter. /// @@ -39,15 +39,15 @@ public FileComponentWriter(string basePath, Dictionary file this._Files = files; this._BasePath = basePath; this._Package = package; - } - + } + public int InstallOrder { get { return this._InstallOrder; } - + set { this._InstallOrder = value; @@ -60,13 +60,13 @@ public int UnInstallOrder { return this._UnInstallOrder; } - + set { this._UnInstallOrder = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("files"). @@ -135,8 +135,8 @@ protected virtual PackageInfo Package { return this._Package; } - } - + } + public virtual void WriteManifest(XmlWriter writer) { // Start component Element @@ -146,7 +146,7 @@ public virtual void WriteManifest(XmlWriter writer) { writer.WriteAttributeString("installOrder", this.InstallOrder.ToString()); } - + if (this.UnInstallOrder > Null.NullInteger) { writer.WriteAttributeString("unInstallOrder", this.UnInstallOrder.ToString()); @@ -163,7 +163,7 @@ public virtual void WriteManifest(XmlWriter writer) { writer.WriteElementString("basePath", this._BasePath); } - + foreach (InstallFile file in this._Files.Values) { this.WriteFileElement(writer, file); @@ -174,8 +174,8 @@ public virtual void WriteManifest(XmlWriter writer) // End component Element writer.WriteEndElement(); - } - + } + /// ----------------------------------------------------------------------------- /// /// The WriteCustomManifest method writes the custom manifest items (that subclasses @@ -205,7 +205,7 @@ protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) path = file.Path.ToLowerInvariant().Replace(this._BasePath.ToLowerInvariant() + "\\", string.Empty); } } - + writer.WriteElementString("path", path); } @@ -220,6 +220,6 @@ protected virtual void WriteFileElement(XmlWriter writer, InstallFile file) // Close file Element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs index 7db83412d1d..b2e49f8950c 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguageComponentWriter.cs @@ -19,13 +19,13 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class LanguageComponentWriter : FileComponentWriter - { + { private readonly int _DependentPackageID; private readonly Locale _Language; - private readonly LanguagePackType _PackageType; - + private readonly LanguagePackType _PackageType; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the LanguageComponentWriter. /// @@ -34,15 +34,15 @@ public class LanguageComponentWriter : FileComponentWriter /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public LanguageComponentWriter(Locale language, string basePath, Dictionary files, PackageInfo package) + public LanguageComponentWriter(Locale language, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) { this._Language = language; this._PackageType = LanguagePackType.Core; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the LanguageComponentWriter. /// @@ -51,14 +51,14 @@ public LanguageComponentWriter(Locale language, string basePath, DictionaryA Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public LanguageComponentWriter(LanguagePackInfo languagePack, string basePath, Dictionary files, PackageInfo package) + public LanguageComponentWriter(LanguagePackInfo languagePack, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) { this._Language = LocaleController.Instance.GetLocale(languagePack.LanguageID); this._PackageType = languagePack.PackageType; this._DependentPackageID = languagePack.DependentPackageID; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("languageFiles"). @@ -128,6 +128,6 @@ protected override void WriteCustomManifest(XmlWriter writer) PackageInfo package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == this._DependentPackageID); writer.WriteElementString("package", package.Name); } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs index db1aa2f09fa..f31ce312e06 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LanguagePackWriter.cs @@ -23,12 +23,12 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class LanguagePackWriter : PackageWriterBase - { + { private bool _IsCore = Null.NullBoolean; private Locale _Language; - private LanguagePackInfo _LanguagePack; - - public LanguagePackWriter(PackageInfo package) + private LanguagePackInfo _LanguagePack; + + public LanguagePackWriter(PackageInfo package) : base(package) { this._LanguagePack = LanguagePackController.GetLanguagePackByPackage(package.PackageID); @@ -79,17 +79,17 @@ public LanguagePackWriter(XPathNavigator manifestNav, InstallerInfo installer) { this.Package.PackageType = "ExtensionLanguagePack"; } - + this.BasePath = Null.NullString; } - public LanguagePackWriter(Locale language, PackageInfo package) + public LanguagePackWriter(Locale language, PackageInfo package) : base(package) { this._Language = language; this.BasePath = Null.NullString; - } - + } + public override bool IncludeAssemblies { get @@ -110,7 +110,7 @@ public Locale Language { return this._Language; } - + set { this._Language = value; @@ -129,13 +129,13 @@ public LanguagePackInfo LanguagePack { return this._LanguagePack; } - + set { this._LanguagePack = value; } } - + protected override void GetFiles(bool includeSource, bool includeAppCode) { // Language file starts at the root @@ -150,13 +150,13 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) { 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 @@ -168,7 +168,7 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) { 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)); @@ -177,6 +177,21 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) } } + protected override void WriteFilesToManifest(XmlWriter writer) + { + LanguageComponentWriter languageFileWriter; + if (this.LanguagePack == null) + { + languageFileWriter = new LanguageComponentWriter(this.Language, this.BasePath, this.Files, this.Package); + } + else + { + languageFileWriter = new LanguageComponentWriter(this.LanguagePack, this.BasePath, this.Files, this.Package); + } + + languageFileWriter.WriteManifest(writer); + } + private void ReadLegacyManifest(XPathNavigator manifestNav) { string fileName = Null.NullString; @@ -229,7 +244,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\HostSettings\\App_LocalResources"; break; } - + break; case "lists": filePath = "DesktopModules\\Admin\\Lists\\App_LocalResources"; @@ -253,7 +268,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = string.Empty; break; } - + break; case "logging": filePath = "DesktopModules\\Admin\\LogViewer\\App_LocalResources"; @@ -274,7 +289,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = string.Empty; break; } - + break; case "modules": filePath = "Admin\\Modules\\App_LocalResources"; @@ -319,7 +334,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Admin\\Portal\\App_LocalResources"; break; } - + break; case "scheduling": filePath = "DesktopModules\\Admin\\Scheduler\\App_LocalResources"; @@ -343,7 +358,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\SearchResults\\App_LocalResources"; break; } - + break; case "security": switch (fileName.Replace(extendedExtension, string.Empty)) @@ -376,7 +391,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = string.Empty; break; } - + break; case "skins": filePath = "Admin\\Skins\\App_LocalResources"; @@ -403,7 +418,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Tabs\\App_LocalResources"; break; } - + break; case "users": switch (fileName.Replace(extendedExtension, string.Empty)) @@ -446,7 +461,7 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Admin\\Users\\App_LocalResources"; break; } - + break; case "vendors": switch (fileName.Replace(extendedExtension, string.Empty)) @@ -482,14 +497,14 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "DesktopModules\\Admin\\Vendors\\App_LocalResources"; break; } - + break; } - + break; case "LocalResource": filePath = Path.Combine("DesktopModules", Path.Combine(moduleName, "App_LocalResources")); - + // Two assumptions are made here // 1. Core files appear in the package before extension files // 2. Module packages only include one module @@ -519,14 +534,14 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) break; } } - + if (this._LanguagePack == null) { this.LegacyError = "DependencyError"; } } } - + break; case "ProviderResource": filePath = Path.Combine("Providers", Path.Combine(moduleName, "App_LocalResources")); @@ -535,27 +550,12 @@ private void ReadLegacyManifest(XPathNavigator manifestNav) filePath = "Install\\App_LocalResources"; break; } - + if (!string.IsNullOrEmpty(filePath)) { this.AddFile(Path.Combine(filePath, fileName), sourceFileName); } } - } - - protected override void WriteFilesToManifest(XmlWriter writer) - { - LanguageComponentWriter languageFileWriter; - if (this.LanguagePack == null) - { - languageFileWriter = new LanguageComponentWriter(this.Language, this.BasePath, this.Files, this.Package); - } - else - { - languageFileWriter = new LanguageComponentWriter(this.LanguagePack, this.BasePath, this.Files, this.Package); - } - - languageFileWriter.WriteManifest(writer); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs index dbd6b295b88..fcacb9a8fbd 100644 --- a/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/LibraryPackageWriter.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class LibraryPackageWriter : PackageWriterBase { - public LibraryPackageWriter(PackageInfo package) + public LibraryPackageWriter(PackageInfo package) : base(package) { this.BasePath = "DesktopModules\\Libraries"; diff --git a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs index 0cc9226e9d3..42dcbebeccb 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ModulePackageWriter.cs @@ -27,8 +27,8 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class ModulePackageWriter : PackageWriterBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageWriter)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageWriter)); + public ModulePackageWriter(XPathNavigator manifestNav, InstallerInfo installer) { this.DesktopModule = new DesktopModuleInfo(); @@ -53,7 +53,7 @@ public ModulePackageWriter(XPathNavigator manifestNav, InstallerInfo installer) this.Initialize(this.DesktopModule.FolderName); } - public ModulePackageWriter(DesktopModuleInfo desktopModule, XPathNavigator manifestNav, PackageInfo package) + public ModulePackageWriter(DesktopModuleInfo desktopModule, XPathNavigator manifestNav, PackageInfo package) : base(package) { this.DesktopModule = desktopModule; @@ -63,33 +63,33 @@ public ModulePackageWriter(DesktopModuleInfo desktopModule, XPathNavigator manif { this.ReadLegacyManifest(manifestNav.SelectSingleNode("folders/folder"), false); } - + string physicalFolderPath = Path.Combine(Globals.ApplicationMapPath, this.BasePath); this.ProcessModuleFolders(physicalFolderPath, physicalFolderPath); } - public ModulePackageWriter(PackageInfo package) + public ModulePackageWriter(PackageInfo package) : base(package) { this.DesktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); this.Initialize(this.DesktopModule.FolderName); } - public ModulePackageWriter(DesktopModuleInfo desktopModule, PackageInfo package) + public ModulePackageWriter(DesktopModuleInfo desktopModule, PackageInfo package) : base(package) { this.DesktopModule = desktopModule; this.Initialize(desktopModule.FolderName); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the associated Desktop Module. /// /// A DesktopModuleInfo object. /// ----------------------------------------------------------------------------- - public DesktopModuleInfo DesktopModule { get; set; } - + public DesktopModuleInfo DesktopModule { get; set; } + protected override Dictionary Dependencies { get @@ -99,21 +99,21 @@ protected override Dictionary Dependencies { dependencies["type"] = this.DesktopModule.Dependencies; } - + if (!string.IsNullOrEmpty(this.DesktopModule.Permissions)) { dependencies["permission"] = this.DesktopModule.Permissions; } - + return dependencies; } - } - + } + protected override void WriteManifestComponent(XmlWriter writer) { // Write Module Component this.WriteModuleComponent(writer); - } + } private static void ProcessControls(XPathNavigator controlNav, string moduleFolder, ModuleDefinitionInfo definition) { @@ -130,7 +130,7 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold // or it allows the developer to use webcontrols rather than usercontrols controlSrc = Path.Combine("DesktopModules", Path.Combine(moduleFolder, controlSrc)); } - + controlSrc = controlSrc.Replace('\\', '/'); moduleControl.ControlSrc = controlSrc; @@ -150,20 +150,20 @@ private static void ProcessControls(XPathNavigator controlNav, string moduleFold throw new Exception(Util.EXCEPTION_Type); } } - + string viewOrder = Util.ReadElement(controlNav, "vieworder"); if (!string.IsNullOrEmpty(viewOrder)) { moduleControl.ViewOrder = int.Parse(viewOrder); } - + moduleControl.HelpURL = Util.ReadElement(controlNav, "helpurl"); string supportsPartialRendering = Util.ReadElement(controlNav, "supportspartialrendering"); if (!string.IsNullOrEmpty(supportsPartialRendering)) { moduleControl.SupportsPartialRendering = bool.Parse(supportsPartialRendering); } - + string supportsPopUps = Util.ReadElement(controlNav, "supportspopups"); if (!string.IsNullOrEmpty(supportsPopUps)) { @@ -172,7 +172,7 @@ 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("/", "\\"); @@ -218,7 +218,7 @@ private void ProcessModules(XPathNavigator moduleNav, string moduleFolder) { ProcessControls(controlNav, moduleFolder, definition); } - + this.DesktopModule.ModuleDefinitions[definition.FriendlyName] = definition; } @@ -236,43 +236,43 @@ private void ReadLegacyManifest(XPathNavigator folderNav, bool processModule) { this.DesktopModule.FolderName = folderName; } - + if (string.IsNullOrEmpty(this.DesktopModule.FolderName)) { this.DesktopModule.FolderName = "MyModule"; } - + string friendlyname = Util.ReadElement(folderNav, "friendlyname"); if (!string.IsNullOrEmpty(friendlyname)) { this.DesktopModule.FriendlyName = friendlyname; this.DesktopModule.ModuleName = friendlyname; } - + string iconFile = Util.ReadElement(folderNav, "iconfile"); if (!string.IsNullOrEmpty(iconFile)) { this.Package.IconFile = iconFile; } - + string modulename = Util.ReadElement(folderNav, "modulename"); if (!string.IsNullOrEmpty(modulename)) { this.DesktopModule.ModuleName = modulename; } - + string permissions = Util.ReadElement(folderNav, "permissions"); if (!string.IsNullOrEmpty(permissions)) { this.DesktopModule.Permissions = permissions; } - + string dependencies = Util.ReadElement(folderNav, "dependencies"); if (!string.IsNullOrEmpty(dependencies)) { this.DesktopModule.Dependencies = dependencies; } - + this.DesktopModule.Version = Util.ReadElement(folderNav, "version", "01.00.00"); this.DesktopModule.Description = Util.ReadElement(folderNav, "description"); this.DesktopModule.BusinessControllerClass = Util.ReadElement(folderNav, "businesscontrollerclass"); @@ -302,7 +302,7 @@ private void ReadLegacyManifest(XPathNavigator folderNav, bool processModule) { sourceFileName = Path.Combine(filePath, fileName); } - + string tempFolder = this.Package.InstallerInfo.TempInstallFolder; if (!File.Exists(Path.Combine(tempFolder, sourceFileName))) { @@ -354,12 +354,12 @@ private void WriteEventMessage(XmlWriter writer) { upgradeVersions += version + ","; } - + if (upgradeVersions.Length > 1) { upgradeVersions = upgradeVersions.Remove(upgradeVersions.Length - 1, 1); } - + writer.WriteElementString("upgradeVersionsList", upgradeVersions); // End end of Event Message Attribues @@ -380,7 +380,7 @@ private void WriteModuleComponent(XmlWriter writer) { this.DesktopModule.CodeSubDirectory = this.DesktopModule.FolderName; } - + CBO.SerializeObject(this.DesktopModule, writer); // Write EventMessage @@ -391,6 +391,6 @@ private void WriteModuleComponent(XmlWriter writer) // End component Element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs index ad70e28e35e..86a09c6f808 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterBase.cs @@ -25,9 +25,9 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class PackageWriterBase - { - private static readonly Regex FileVersionMatchRegex = new Regex(Util.REGEX_Version, RegexOptions.Compiled); - + { + 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(); @@ -42,12 +42,12 @@ public PackageWriterBase(PackageInfo package) { this._Package = package; this._Package.AttachInstallerInfo(new InstallerInfo()); - } - + } + protected PackageWriterBase() { } - + /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of AppCodeFiles that should be included in the Package. @@ -60,23 +60,7 @@ public Dictionary AppCodeFiles { return this._AppCodeFiles; } - } - - /// ----------------------------------------------------------------------------- - /// - /// 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,33 +74,6 @@ public Dictionary Assemblies { return this._Assemblies; } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Path for the Package's assemblies. - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string AssemblyPath { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Base Path for the Package. - /// - /// A String. - /// ----------------------------------------------------------------------------- - public string BasePath - { - get - { - return this._BasePath; - } - - set - { - this._BasePath = value; - } } /// ----------------------------------------------------------------------------- @@ -145,15 +102,7 @@ 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. - /// ----------------------------------------------------------------------------- - public bool HasProjectFile { get; set; } + } /// ----------------------------------------------------------------------------- /// @@ -167,17 +116,7 @@ public virtual bool IncludeAssemblies { return true; } - } - - /// - /// Gets or sets and sets whether there are any errors in parsing legacy packages. - /// - /// - /// And sets whether there are any errors in parsing legacy packages - /// - /// - /// - public string LegacyError { get; set; } + } /// ----------------------------------------------------------------------------- /// @@ -193,25 +132,6 @@ public Logger Log } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the associated Package. - /// - /// An PackageInfo object. - /// ----------------------------------------------------------------------------- - public PackageInfo Package - { - get - { - return this._Package; - } - - set - { - this._Package = value; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of Resources that should be included in the Package. @@ -252,7 +172,87 @@ public List Versions { return this._Versions; } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Path for the Package's app code files. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string AppCodePath { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Path for the Package's assemblies. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string AssemblyPath { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Base Path for the Package. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string BasePath + { + get + { + return this._BasePath; + } + + set + { + this._BasePath = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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; } + + /// + /// Gets or sets and sets whether there are any errors in parsing legacy packages. + /// + /// + /// And sets whether there are any errors in parsing legacy packages + /// + /// + /// + public string LegacyError { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the associated Package. + /// + /// An PackageInfo object. + /// ----------------------------------------------------------------------------- + public PackageInfo Package + { + get + { + return this._Package; + } + + set + { + this._Package = value; + } + } + + protected virtual Dictionary Dependencies + { + get + { + return new Dictionary(); + } + } public static void WriteManifestEndElement(XmlWriter writer) { @@ -272,8 +272,8 @@ public static void WriteManifestStartElement(XmlWriter writer) // Start packages Element writer.WriteStartElement("packages"); - } - + } + public virtual void AddFile(InstallFile file) { switch (file.Type) @@ -294,7 +294,7 @@ public virtual void AddFile(InstallFile file) 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); @@ -309,161 +309,159 @@ public void AddResourceFile(InstallFile file) { this._Resources[file.FullName.ToLowerInvariant()] = file; } - - protected virtual void AddFile(string fileName) + + public void CreatePackage(string archiveName, string manifestName, string manifest, bool createManifest) { - this.AddFile(new InstallFile(fileName, this.Package.InstallerInfo)); + if (createManifest) + { + this.WriteManifest(manifestName, manifest); + } + + this.AddFile(manifestName); + this.CreateZipFile(archiveName); } - protected virtual void AddFile(string fileName, string sourceFileName) + public void GetFiles(bool includeSource) { - this.AddFile(new InstallFile(fileName, sourceFileName, this.Package.InstallerInfo)); + // Call protected method that does the work + this.GetFiles(includeSource, true); } - - private void AddFilesToZip(ZipOutputStream stream, IDictionary files, string basePath) + + /// + /// WriteManifest writes an existing manifest. + /// + /// The name of the manifest file. + /// The manifest. + /// This overload takes a package manifest and writes it to a file. + public void WriteManifest(string manifestName, string manifest) { - foreach (InstallFile packageFile in files.Values) + using (XmlWriter writer = XmlWriter.Create(Path.Combine(Globals.ApplicationMapPath, Path.Combine(this.BasePath, manifestName)), XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { - string filepath; - if (string.IsNullOrEmpty(basePath)) - { - filepath = Path.Combine(Globals.ApplicationMapPath, packageFile.FullName); - } - else - { - filepath = Path.Combine(Path.Combine(Globals.ApplicationMapPath, basePath), packageFile.FullName.Replace(basePath + "\\", string.Empty)); - } - - if (File.Exists(filepath)) - { - string packageFilePath = packageFile.Path; - if (!string.IsNullOrEmpty(basePath)) - { - packageFilePath = packageFilePath.Replace(basePath + "\\", string.Empty); - } - - FileSystemUtils.AddToZip(ref stream, filepath, packageFile.Name, packageFilePath); - this.Log.AddInfo(string.Format(Util.WRITER_SavedFile, packageFile.FullName)); - } + this.Log.StartJob(Util.WRITER_CreatingManifest); + this.WriteManifest(writer, manifest); + this.Log.EndJob(Util.WRITER_CreatedManifest); } } - private void CreateZipFile(string zipFileName) + /// + /// WriteManifest writes a package manifest to an XmlWriter. + /// + /// The XmlWriter. + /// The manifest. + /// This overload takes a package manifest and writes it to a Writer. + public void WriteManifest(XmlWriter writer, string manifest) { - int CompressionLevel = 9; - var zipFile = new FileInfo(zipFileName); + WriteManifestStartElement(writer); + writer.WriteRaw(manifest); - string ZipFileShortName = zipFile.Name; + // Close Dotnetnuke Element + WriteManifestEndElement(writer); - FileStream strmZipFile = null; - this.Log.StartJob(Util.WRITER_CreatingPackage); - try - { - this.Log.AddInfo(string.Format(Util.WRITER_CreateArchive, ZipFileShortName)); - strmZipFile = File.Create(zipFileName); - ZipOutputStream strmZipStream = null; - try - { - strmZipStream = new ZipOutputStream(strmZipFile); - strmZipStream.SetLevel(CompressionLevel); + // Close Writer + writer.Close(); + } - // Add Files To zip - this.AddFilesToZip(strmZipStream, this._Assemblies, string.Empty); - this.AddFilesToZip(strmZipStream, this._AppCodeFiles, this.AppCodePath); - this.AddFilesToZip(strmZipStream, this._Files, this.BasePath); - this.AddFilesToZip(strmZipStream, this._CleanUpFiles, this.BasePath); - this.AddFilesToZip(strmZipStream, this._Resources, this.BasePath); - this.AddFilesToZip(strmZipStream, this._Scripts, this.BasePath); - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); - } - finally - { - if (strmZipStream != null) - { - strmZipStream.Finish(); - strmZipStream.Close(); - } - } - - this.Log.EndJob(Util.WRITER_CreatedPackage); - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); - } - finally + /// + /// WriteManifest writes the manifest assoicated with this PackageWriter to a string. + /// + /// A flag that indicates whether to return the package element + /// as a fragment (True) or whether to add the outer dotnetnuke and packages elements (False). + /// The manifest as a string. + /// + public string WriteManifest(bool packageFragment) + { + // Create a writer to create the processed manifest + var sb = new StringBuilder(); + using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) { - if (strmZipFile != null) - { - strmZipFile.Close(); - } + this.WriteManifest(writer, packageFragment); + + // Close XmlWriter + writer.Close(); + + // Return new manifest + return sb.ToString(); } } - private void WritePackageEndElement(XmlWriter writer) + public void WriteManifest(XmlWriter writer, bool packageFragment) { - // Close components Element - writer.WriteEndElement(); + this.Log.StartJob(Util.WRITER_CreatingManifest); - // Close package Element - writer.WriteEndElement(); - } + if (!packageFragment) + { + // Start dotnetnuke element + WriteManifestStartElement(writer); + } - private void WritePackageStartElement(XmlWriter writer) - { // Start package Element - writer.WriteStartElement("package"); - writer.WriteAttributeString("name", this.Package.Name); - writer.WriteAttributeString("type", this.Package.PackageType); - writer.WriteAttributeString("version", this.Package.Version.ToString(3)); + this.WritePackageStartElement(writer); - // Write FriendlyName - writer.WriteElementString("friendlyName", this.Package.FriendlyName); + // write Script Component + if (this.Scripts.Count > 0) + { + var scriptWriter = new ScriptComponentWriter(this.BasePath, this.Scripts, this.Package); + scriptWriter.WriteManifest(writer); + } - // Write Description - writer.WriteElementString("description", this.Package.Description); - writer.WriteElementString("iconFile", Util.ParsePackageIconFileName(this.Package)); + // write Clean Up Files Component + if (this.CleanUpFiles.Count > 0) + { + var cleanupFileWriter = new CleanupComponentWriter(this.BasePath, this.CleanUpFiles); + cleanupFileWriter.WriteManifest(writer); + } - // Write Author - writer.WriteStartElement("owner"); + // Write the Custom Component + this.WriteManifestComponent(writer); - writer.WriteElementString("name", this.Package.Owner); - writer.WriteElementString("organization", this.Package.Organization); - writer.WriteElementString("url", this.Package.Url); - writer.WriteElementString("email", this.Package.Email); + // Write Assemblies Component + if (this.Assemblies.Count > 0) + { + var assemblyWriter = new AssemblyComponentWriter(this.AssemblyPath, this.Assemblies, this.Package); + assemblyWriter.WriteManifest(writer); + } - // Write Author End - writer.WriteEndElement(); + // Write AppCode Files Component + if (this.AppCodeFiles.Count > 0) + { + var fileWriter = new FileComponentWriter(this.AppCodePath, this.AppCodeFiles, this.Package); + fileWriter.WriteManifest(writer); + } - // Write License - writer.WriteElementString("license", this.Package.License); + // write Files Component + if (this.Files.Count > 0) + { + this.WriteFilesToManifest(writer); + } - // Write Release Notes - writer.WriteElementString("releaseNotes", this.Package.ReleaseNotes); + // write ResourceFiles Component + if (this.Resources.Count > 0) + { + var fileWriter = new ResourceFileComponentWriter(this.BasePath, this.Resources, this.Package); + fileWriter.WriteManifest(writer); + } - // Write Dependencies - if (this.Dependencies.Count > 0) + // Close Package + this.WritePackageEndElement(writer); + + if (!packageFragment) { - writer.WriteStartElement("dependencies"); - foreach (KeyValuePair kvp in this.Dependencies) - { - writer.WriteStartElement("dependency"); - writer.WriteAttributeString("type", kvp.Key); - writer.WriteString(kvp.Value); - writer.WriteEndElement(); - } - - writer.WriteEndElement(); + // Close Dotnetnuke Element + WriteManifestEndElement(writer); } - // Write components Element - writer.WriteStartElement("components"); - } + this.Log.EndJob(Util.WRITER_CreatedManifest); + } + + 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) { @@ -516,12 +514,12 @@ protected virtual void ParseFiles(DirectoryInfo folder, string rootPath) { filePath = filePath.Substring(1); } - + if (folder.FullName.ToLowerInvariant().Contains("app_code")) { filePath = "[app_code]" + filePath; } - + if (!file.Extension.Equals(".dnn", StringComparison.InvariantCultureIgnoreCase) && (file.Attributes & FileAttributes.Hidden) == 0) { this.AddFile(Path.Combine(filePath, file.Name)); @@ -576,7 +574,7 @@ protected void ParseProjectFile(FileInfo projFile, bool includeSource) { fileName = fileName.Substring(0, fileName.IndexOf(",")); } - + if ( !(fileName.StartsWith("system", StringComparison.InvariantCultureIgnoreCase) || fileName.StartsWith("microsoft", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke.webutility", StringComparison.InvariantCultureIgnoreCase) || fileName.Equals("dotnetnuke.webcontrols", StringComparison.InvariantCultureIgnoreCase))) @@ -618,149 +616,151 @@ protected virtual void WriteFilesToManifest(XmlWriter writer) protected virtual void WriteManifestComponent(XmlWriter writer) { - } + } - public void CreatePackage(string archiveName, string manifestName, string manifest, bool createManifest) + private void AddFilesToZip(ZipOutputStream stream, IDictionary files, string basePath) { - if (createManifest) + foreach (InstallFile packageFile in files.Values) { - this.WriteManifest(manifestName, manifest); - } - - this.AddFile(manifestName); - this.CreateZipFile(archiveName); - } + string filepath; + if (string.IsNullOrEmpty(basePath)) + { + filepath = Path.Combine(Globals.ApplicationMapPath, packageFile.FullName); + } + else + { + filepath = Path.Combine(Path.Combine(Globals.ApplicationMapPath, basePath), packageFile.FullName.Replace(basePath + "\\", string.Empty)); + } - public void GetFiles(bool includeSource) - { - // Call protected method that does the work - this.GetFiles(includeSource, true); - } + if (File.Exists(filepath)) + { + string packageFilePath = packageFile.Path; + if (!string.IsNullOrEmpty(basePath)) + { + packageFilePath = packageFilePath.Replace(basePath + "\\", string.Empty); + } - /// - /// WriteManifest writes an existing manifest. - /// - /// The name of the manifest file. - /// The manifest. - /// This overload takes a package manifest and writes it to a file. - public void WriteManifest(string manifestName, string manifest) - { - using (XmlWriter writer = XmlWriter.Create(Path.Combine(Globals.ApplicationMapPath, Path.Combine(this.BasePath, manifestName)), XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) - { - this.Log.StartJob(Util.WRITER_CreatingManifest); - this.WriteManifest(writer, manifest); - this.Log.EndJob(Util.WRITER_CreatedManifest); + FileSystemUtils.AddToZip(ref stream, filepath, packageFile.Name, packageFilePath); + this.Log.AddInfo(string.Format(Util.WRITER_SavedFile, packageFile.FullName)); + } } } - /// - /// WriteManifest writes a package manifest to an XmlWriter. - /// - /// The XmlWriter. - /// The manifest. - /// This overload takes a package manifest and writes it to a Writer. - public void WriteManifest(XmlWriter writer, string manifest) + private void CreateZipFile(string zipFileName) { - WriteManifestStartElement(writer); - writer.WriteRaw(manifest); + int CompressionLevel = 9; + var zipFile = new FileInfo(zipFileName); - // Close Dotnetnuke Element - WriteManifestEndElement(writer); + string ZipFileShortName = zipFile.Name; - // Close Writer - writer.Close(); - } + FileStream strmZipFile = null; + this.Log.StartJob(Util.WRITER_CreatingPackage); + try + { + this.Log.AddInfo(string.Format(Util.WRITER_CreateArchive, ZipFileShortName)); + strmZipFile = File.Create(zipFileName); + ZipOutputStream strmZipStream = null; + try + { + strmZipStream = new ZipOutputStream(strmZipFile); + strmZipStream.SetLevel(CompressionLevel); - /// - /// WriteManifest writes the manifest assoicated with this PackageWriter to a string. - /// - /// A flag that indicates whether to return the package element - /// as a fragment (True) or whether to add the outer dotnetnuke and packages elements (False). - /// The manifest as a string. - /// - public string WriteManifest(bool packageFragment) - { - // Create a writer to create the processed manifest - var sb = new StringBuilder(); - using (XmlWriter writer = XmlWriter.Create(sb, XmlUtils.GetXmlWriterSettings(ConformanceLevel.Fragment))) + // Add Files To zip + this.AddFilesToZip(strmZipStream, this._Assemblies, string.Empty); + this.AddFilesToZip(strmZipStream, this._AppCodeFiles, this.AppCodePath); + this.AddFilesToZip(strmZipStream, this._Files, this.BasePath); + this.AddFilesToZip(strmZipStream, this._CleanUpFiles, this.BasePath); + this.AddFilesToZip(strmZipStream, this._Resources, this.BasePath); + this.AddFilesToZip(strmZipStream, this._Scripts, this.BasePath); + } + catch (Exception ex) + { + Exceptions.Exceptions.LogException(ex); + this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); + } + finally + { + if (strmZipStream != null) + { + strmZipStream.Finish(); + strmZipStream.Close(); + } + } + + this.Log.EndJob(Util.WRITER_CreatedPackage); + } + catch (Exception ex) { - this.WriteManifest(writer, packageFragment); - - // Close XmlWriter - writer.Close(); - - // Return new manifest - return sb.ToString(); + Exceptions.Exceptions.LogException(ex); + this.Log.AddFailure(string.Format(Util.WRITER_SaveFileError, ex)); + } + finally + { + if (strmZipFile != null) + { + strmZipFile.Close(); + } } } - public void WriteManifest(XmlWriter writer, bool packageFragment) + private void WritePackageEndElement(XmlWriter writer) { - this.Log.StartJob(Util.WRITER_CreatingManifest); + // Close components Element + writer.WriteEndElement(); - if (!packageFragment) - { - // Start dotnetnuke element - WriteManifestStartElement(writer); - } + // Close package Element + writer.WriteEndElement(); + } + private void WritePackageStartElement(XmlWriter writer) + { // Start package Element - this.WritePackageStartElement(writer); - - // write Script Component - if (this.Scripts.Count > 0) - { - var scriptWriter = new ScriptComponentWriter(this.BasePath, this.Scripts, this.Package); - scriptWriter.WriteManifest(writer); - } + writer.WriteStartElement("package"); + writer.WriteAttributeString("name", this.Package.Name); + writer.WriteAttributeString("type", this.Package.PackageType); + writer.WriteAttributeString("version", this.Package.Version.ToString(3)); - // write Clean Up Files Component - if (this.CleanUpFiles.Count > 0) - { - var cleanupFileWriter = new CleanupComponentWriter(this.BasePath, this.CleanUpFiles); - cleanupFileWriter.WriteManifest(writer); - } + // Write FriendlyName + writer.WriteElementString("friendlyName", this.Package.FriendlyName); - // Write the Custom Component - this.WriteManifestComponent(writer); + // Write Description + writer.WriteElementString("description", this.Package.Description); + writer.WriteElementString("iconFile", Util.ParsePackageIconFileName(this.Package)); - // Write Assemblies Component - if (this.Assemblies.Count > 0) - { - var assemblyWriter = new AssemblyComponentWriter(this.AssemblyPath, this.Assemblies, this.Package); - assemblyWriter.WriteManifest(writer); - } + // Write Author + writer.WriteStartElement("owner"); - // Write AppCode Files Component - if (this.AppCodeFiles.Count > 0) - { - var fileWriter = new FileComponentWriter(this.AppCodePath, this.AppCodeFiles, this.Package); - fileWriter.WriteManifest(writer); - } + writer.WriteElementString("name", this.Package.Owner); + writer.WriteElementString("organization", this.Package.Organization); + writer.WriteElementString("url", this.Package.Url); + writer.WriteElementString("email", this.Package.Email); - // write Files Component - if (this.Files.Count > 0) - { - this.WriteFilesToManifest(writer); - } + // Write Author End + writer.WriteEndElement(); - // write ResourceFiles Component - if (this.Resources.Count > 0) - { - var fileWriter = new ResourceFileComponentWriter(this.BasePath, this.Resources, this.Package); - fileWriter.WriteManifest(writer); - } + // Write License + writer.WriteElementString("license", this.Package.License); - // Close Package - this.WritePackageEndElement(writer); + // Write Release Notes + writer.WriteElementString("releaseNotes", this.Package.ReleaseNotes); - if (!packageFragment) + // Write Dependencies + if (this.Dependencies.Count > 0) { - // Close Dotnetnuke Element - WriteManifestEndElement(writer); + writer.WriteStartElement("dependencies"); + foreach (KeyValuePair kvp in this.Dependencies) + { + writer.WriteStartElement("dependency"); + writer.WriteAttributeString("type", kvp.Key); + writer.WriteString(kvp.Value); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); } - - this.Log.EndJob(Util.WRITER_CreatedManifest); + + // Write components Element + writer.WriteStartElement("components"); } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs b/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs index 41e1339fda3..a5a1550f6f1 100644 --- a/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs +++ b/DNN Platform/Library/Services/Installer/Writers/PackageWriterFactory.cs @@ -16,12 +16,12 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class PackageWriterFactory - { + { /// ----------------------------------------------------------------------------- /// /// The GetWriter method instantiates the relevant PackageWriter Installer. /// - /// The associated PackageInfo instance. + /// The associated PackageInfo instance. /// /// ----------------------------------------------------------------------------- public static PackageWriterBase GetWriter(PackageInfo package) @@ -67,11 +67,11 @@ public static PackageWriterBase GetWriter(PackageInfo package) // The class for the Installer is specified in the Text property writer = (PackageWriterBase)Reflection.CreateObject(entry.Text, "PackageWriter_" + entry.Value); } - + break; } - + return writer; - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs index 708d3809571..65776e859e8 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ProviderPackageWriter.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class ProviderPackageWriter : PackageWriterBase { - public ProviderPackageWriter(PackageInfo package) + public ProviderPackageWriter(PackageInfo package) : base(package) { XmlDocument configDoc = Config.Load(); @@ -28,7 +28,7 @@ public ProviderPackageWriter(PackageInfo package) { providerPath = Util.ReadAttribute(providerNavigator, "providerPath"); } - + if (!string.IsNullOrEmpty(providerPath)) { this.BasePath = providerPath.Replace("~/", string.Empty).Replace("/", "\\"); diff --git a/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs index 96c173670f3..4067e7a0a1e 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ResourceFileComponentWriter.cs @@ -16,9 +16,9 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class ResourceFileComponentWriter : FileComponentWriter - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the ResourceFileComponentWriter. /// @@ -26,7 +26,7 @@ public class ResourceFileComponentWriter : FileComponentWriter /// A Dictionary of files. /// /// ----------------------------------------------------------------------------- - public ResourceFileComponentWriter(string basePath, Dictionary files, PackageInfo package) + public ResourceFileComponentWriter(string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) { } diff --git a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs index 0153188e681..e638f95a69d 100644 --- a/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/ScriptComponentWriter.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class ScriptComponentWriter : FileComponentWriter - { - public ScriptComponentWriter(string basePath, Dictionary scripts, PackageInfo package) + { + public ScriptComponentWriter(string basePath, Dictionary scripts, PackageInfo package) : base(basePath, scripts, package) { - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("scripts"). @@ -119,6 +119,6 @@ protected override void WriteFileElement(XmlWriter writer, InstallFile file) // Close file Element writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs index c421bcdbda4..f14b34f1f23 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinComponentWriter.cs @@ -16,11 +16,11 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class SkinComponentWriter : FileComponentWriter - { - private readonly string _SkinName; - + { + private readonly string _SkinName; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the SkinComponentWriter. /// @@ -29,12 +29,12 @@ public class SkinComponentWriter : FileComponentWriter /// A Dictionary of files. /// Package Info. /// ----------------------------------------------------------------------------- - public SkinComponentWriter(string skinName, string basePath, Dictionary files, PackageInfo package) + public SkinComponentWriter(string skinName, string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) { this._SkinName = skinName; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the name of the Collection Node ("skinFiles"). @@ -89,8 +89,8 @@ protected virtual string SkinNameNodeName { return "skinName"; } - } - + } + /// ----------------------------------------------------------------------------- /// /// The WriteCustomManifest method writes the custom manifest items (that subclasses @@ -101,6 +101,6 @@ protected virtual string SkinNameNodeName protected override void WriteCustomManifest(XmlWriter writer) { writer.WriteElementString(this.SkinNameNodeName, this._SkinName); - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs index 5dc9ca51bea..b68664caa93 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinControlPackageWriter.cs @@ -20,8 +20,8 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class SkinControlPackageWriter : PackageWriterBase - { - public SkinControlPackageWriter(PackageInfo package) + { + public SkinControlPackageWriter(PackageInfo package) : base(package) { this.SkinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); @@ -29,7 +29,7 @@ public SkinControlPackageWriter(PackageInfo package) this.AppCodePath = Path.Combine("App_Code", package.Name.ToLowerInvariant()).Replace("/", "\\"); } - public SkinControlPackageWriter(SkinControlInfo skinControl, PackageInfo package) + public SkinControlPackageWriter(SkinControlInfo skinControl, PackageInfo package) : base(package) { this.SkinControl = skinControl; @@ -53,16 +53,16 @@ public SkinControlPackageWriter(XPathNavigator manifestNav, InstallerInfo instal this.BasePath = Path.Combine("DesktopModules", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); this.AppCodePath = Path.Combine("App_Code", this.Package.Name.ToLowerInvariant()).Replace("/", "\\"); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the associated SkinControl. /// /// A SkinControlInfo object. /// ----------------------------------------------------------------------------- - public SkinControlInfo SkinControl { get; set; } - + public SkinControlInfo SkinControl { get; set; } + protected override void WriteManifestComponent(XmlWriter writer) { // Start component Element @@ -74,8 +74,8 @@ protected override void WriteManifestComponent(XmlWriter writer) // End component Element writer.WriteEndElement(); - } - + } + private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModule) { XPathNavigator folderNav = legacyManifest.SelectSingleNode("folders/folder"); @@ -112,6 +112,6 @@ private void ReadLegacyManifest(XPathNavigator legacyManifest, bool processModul { this.AddFile(Util.ReadElement(folderNav, "resourcefile")); } - } + } } } diff --git a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs index 5b1bbd908d0..92786046c1d 100644 --- a/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/SkinPackageWriter.cs @@ -18,39 +18,39 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class SkinPackageWriter : PackageWriterBase - { + { private readonly SkinPackageInfo _SkinPackage; - private readonly string _SubFolder; - - public SkinPackageWriter(PackageInfo package) + private readonly string _SubFolder; + + public SkinPackageWriter(PackageInfo package) : base(package) { this._SkinPackage = SkinController.GetSkinByPackageID(package.PackageID); this.SetBasePath(); } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package) : base(package) { this._SkinPackage = skinPackage; this.SetBasePath(); } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath) : base(package) { this._SkinPackage = skinPackage; this.BasePath = basePath; } - public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath, string subFolder) + public SkinPackageWriter(SkinPackageInfo skinPackage, PackageInfo package, string basePath, string subFolder) : base(package) { this._SkinPackage = skinPackage; this._SubFolder = subFolder; this.BasePath = Path.Combine(basePath, subFolder); - } - + } + public override bool IncludeAssemblies { get @@ -65,8 +65,8 @@ protected SkinPackageInfo SkinPackage { return this._SkinPackage; } - } - + } + public void SetBasePath() { if (this._SkinPackage.SkinType == "Skin") @@ -96,7 +96,7 @@ protected override void ParseFiles(DirectoryInfo folder, string rootPath) { filePath = filePath.Substring(1); } - + if (!file.Extension.Equals(".dnn", StringComparison.InvariantCultureIgnoreCase)) { if (string.IsNullOrEmpty(this._SubFolder)) @@ -123,7 +123,7 @@ protected override void WriteFilesToManifest(XmlWriter writer) { skinFileWriter = new ContainerComponentWriter(this.SkinPackage.SkinName, this.BasePath, this.Files, this.Package); } - + skinFileWriter.WriteManifest(writer); } } diff --git a/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs b/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs index ff1c3f84dc1..9fd53603287 100644 --- a/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/WidgetComponentWriter.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Services.Installer.Writers /// ----------------------------------------------------------------------------- public class WidgetComponentWriter : FileComponentWriter { - public WidgetComponentWriter(string basePath, Dictionary files, PackageInfo package) + public WidgetComponentWriter(string basePath, Dictionary files, PackageInfo package) : base(basePath, files, package) { } diff --git a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs index 46479ad1d26..dd5bc632c19 100644 --- a/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs +++ b/DNN Platform/Library/Services/Installer/Writers/WidgetPackageWriter.cs @@ -16,8 +16,8 @@ namespace DotNetNuke.Services.Installer.Writers /// /// ----------------------------------------------------------------------------- public class WidgetPackageWriter : PackageWriterBase - { - public WidgetPackageWriter(PackageInfo package) + { + public WidgetPackageWriter(PackageInfo package) : base(package) { string company = package.Name; @@ -27,16 +27,16 @@ public WidgetPackageWriter(PackageInfo package) } this.BasePath = Path.Combine("Resources\\Widgets\\User", company); - } - + } + public override bool IncludeAssemblies { get { return false; } - } - + } + protected override void GetFiles(bool includeSource, bool includeAppCode) { // Call base class method with includeAppCode = false diff --git a/DNN Platform/Library/Services/Installer/XmlMerge.cs b/DNN Platform/Library/Services/Installer/XmlMerge.cs index d7f2c19d249..90ca84f9154 100644 --- a/DNN Platform/Library/Services/Installer/XmlMerge.cs +++ b/DNN Platform/Library/Services/Installer/XmlMerge.cs @@ -23,11 +23,11 @@ namespace DotNetNuke.Services.Installer /// /// ----------------------------------------------------------------------------- public class XmlMerge - { - private IDictionary _pendingDocuments; - + { + private IDictionary _pendingDocuments; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -40,10 +40,10 @@ public XmlMerge(string sourceFileName, string version, string sender) this.Sender = sender; this.SourceConfig = new XmlDocument { XmlResolver = null }; this.SourceConfig.Load(sourceFileName); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -56,10 +56,10 @@ public XmlMerge(Stream sourceStream, string version, string sender) this.Sender = sender; this.SourceConfig = new XmlDocument { XmlResolver = null }; this.SourceConfig.Load(sourceStream); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -72,10 +72,10 @@ public XmlMerge(TextReader sourceReader, string version, string sender) this.Sender = sender; this.SourceConfig = new XmlDocument { XmlResolver = null }; this.SourceConfig.Load(sourceReader); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// /// @@ -87,8 +87,21 @@ public XmlMerge(XmlDocument sourceDoc, string version, string sender) this.Version = version; this.Sender = sender; this.SourceConfig = sourceDoc; - } - + } + + public IDictionary PendingDocuments + { + get + { + if (this._pendingDocuments == null) + { + this._pendingDocuments = new Dictionary(); + } + + return this._pendingDocuments; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the Source for the Config file. @@ -137,19 +150,6 @@ public XmlMerge(XmlDocument sourceDoc, string version, string sender) /// ----------------------------------------------------------------------------- public bool ConfigUpdateChangedNodes { get; private set; } - public IDictionary PendingDocuments - { - get - { - if (this._pendingDocuments == null) - { - this._pendingDocuments = new Dictionary(); - } - - return this._pendingDocuments; - } - } - /// ----------------------------------------------------------------------------- /// /// The UpdateConfig method processes the source file and updates the Target @@ -189,7 +189,78 @@ public void UpdateConfig(XmlDocument target, string fileName) this.ConfigUpdateChangedNodes = changedAnyNodes; } - + + /// ----------------------------------------------------------------------------- + /// + /// The UpdateConfigs method processes the source file and updates the various config + /// files. + /// + /// ----------------------------------------------------------------------------- + public void UpdateConfigs() + { + this.UpdateConfigs(true); + } + + public void UpdateConfigs(bool autoSave) + { + var changedAnyNodes = false; + var nodes = this.SourceConfig.SelectNodes("/configuration/nodes"); + if (nodes != null) + { + foreach (XmlNode configNode in nodes) + { + Debug.Assert(configNode.Attributes != null, "configNode.Attributes != null"); + + // Attempt to load TargetFile property from configFile Atribute + this.TargetFileName = configNode.Attributes["configfile"].Value; + string targetProductName = string.Empty; + if (configNode.Attributes["productName"] != null) + { + targetProductName = configNode.Attributes["productName"].Value; + } + + bool isAppliedToProduct; + + if (!File.Exists(Globals.ApplicationMapPath + "\\" + this.TargetFileName)) + { + DnnInstallLogger.InstallLogInfo($"Target File {this.TargetFileName} doesn't exist, ignore the merge process"); + return; + } + + this.TargetConfig = Config.Load(this.TargetFileName); + if (string.IsNullOrEmpty(targetProductName) || targetProductName == "All") + { + isAppliedToProduct = true; + } + else + { + isAppliedToProduct = DotNetNukeContext.Current.Application.ApplyToProduct(targetProductName); + } + + // The nodes definition is not correct so skip changes + if (this.TargetConfig != null && isAppliedToProduct) + { + var changedNodes = this.ProcessNodes(configNode.SelectNodes("node"), autoSave); + changedAnyNodes = changedAnyNodes || changedNodes; + if (!autoSave && changedNodes) + { + this.PendingDocuments.Add(this.TargetFileName, this.TargetConfig); + } + } + } + } + + this.ConfigUpdateChangedNodes = changedAnyNodes; + } + + public void SavePendingConfigs() + { + foreach (var key in this.PendingDocuments.Keys) + { + Config.Save(this.PendingDocuments[key], key); + } + } + private bool AddNode(XmlNode rootNode, XmlNode actionNode) { var changedNode = false; @@ -416,7 +487,7 @@ private XmlNode FindMatchingNode(XmlNode rootNode, XmlNode mergeNode, string pat matchingNode = this.FindNode(rootNode, rootNodePath, nsmgr); } } - + return matchingNode; } @@ -519,7 +590,7 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) keyAttribute = actionNode.Attributes["key"].Value; DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateNode: keyAttribute=" + keyAttribute.ToString()); } - + foreach (XmlNode child in actionNode.ChildNodes) { Debug.Assert(child.Attributes != null, "child.Attributes != null"); @@ -539,7 +610,7 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) { targetNode = this.FindMatchingNode(rootNode, actionNode, "targetpath"); } - + if (targetNode == null) { // Since there is no collision we can just add the node @@ -559,7 +630,7 @@ private bool UpdateNode(XmlNode rootNode, XmlNode actionNode) changedNode = !string.Equals(oldContent, newContent, StringComparison.Ordinal); break; case "save": - string commentHeaderText = string.Format( + string commentHeaderText = string.Format( Localization.GetString("XMLMERGE_Upgrade", Localization.SharedResourceFile), Environment.NewLine, this.Sender, @@ -611,77 +682,6 @@ private void RemoveCommentNodes(XmlNode node) { commentNodes.ForEach(n => { node.RemoveChild(n); }); } - } - - /// ----------------------------------------------------------------------------- - /// - /// The UpdateConfigs method processes the source file and updates the various config - /// files. - /// - /// ----------------------------------------------------------------------------- - public void UpdateConfigs() - { - this.UpdateConfigs(true); } - - public void UpdateConfigs(bool autoSave) - { - var changedAnyNodes = false; - var nodes = this.SourceConfig.SelectNodes("/configuration/nodes"); - if (nodes != null) - { - foreach (XmlNode configNode in nodes) - { - Debug.Assert(configNode.Attributes != null, "configNode.Attributes != null"); - - // Attempt to load TargetFile property from configFile Atribute - this.TargetFileName = configNode.Attributes["configfile"].Value; - string targetProductName = string.Empty; - if (configNode.Attributes["productName"] != null) - { - targetProductName = configNode.Attributes["productName"].Value; - } - - bool isAppliedToProduct; - - if (!File.Exists(Globals.ApplicationMapPath + "\\" + this.TargetFileName)) - { - DnnInstallLogger.InstallLogInfo($"Target File {this.TargetFileName} doesn't exist, ignore the merge process"); - return; - } - - this.TargetConfig = Config.Load(this.TargetFileName); - if (string.IsNullOrEmpty(targetProductName) || targetProductName == "All") - { - isAppliedToProduct = true; - } - else - { - isAppliedToProduct = DotNetNukeContext.Current.Application.ApplyToProduct(targetProductName); - } - - // The nodes definition is not correct so skip changes - if (this.TargetConfig != null && isAppliedToProduct) - { - var changedNodes = this.ProcessNodes(configNode.SelectNodes("node"), autoSave); - changedAnyNodes = changedAnyNodes || changedNodes; - if (!autoSave && changedNodes) - { - this.PendingDocuments.Add(this.TargetFileName, this.TargetConfig); - } - } - } - } - - this.ConfigUpdateChangedNodes = changedAnyNodes; - } - - public void SavePendingConfigs() - { - foreach (var key in this.PendingDocuments.Keys) - { - Config.Save(this.PendingDocuments[key], key); - } - } } } diff --git a/DNN Platform/Library/Services/Journal/CommentInfo.cs b/DNN Platform/Library/Services/Journal/CommentInfo.cs index 97467a4660b..512365b3f40 100644 --- a/DNN Platform/Library/Services/Journal/CommentInfo.cs +++ b/DNN Platform/Library/Services/Journal/CommentInfo.cs @@ -16,61 +16,61 @@ namespace DotNetNuke.Services.Journal public class CommentInfo : IHydratable, IPropertyAccess { + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public int CommentId { get; set; } - + public int JournalId { get; set; } - + public string Comment { get; set; } - + public DateTime DateCreated { get; set; } - + public DateTime DateUpdated { get; set; } - + public XmlDocument CommentXML { get; set; } - + public int UserId { get; set; } - + public string DisplayName { get; set; } - - public int KeyID + + public int KeyID { - get + get { return this.CommentId; } - - set - { - this.CommentId = value; - } - } - public CacheLevel Cacheability - { - get + set { - return CacheLevel.fullyCacheable; + this.CommentId = value; } } - public void Fill(System.Data.IDataReader dr) + public void Fill(System.Data.IDataReader dr) { this.CommentId = Null.SetNullInteger(dr["CommentId"]); this.JournalId = Null.SetNullInteger(dr["JournalId"]); this.Comment = Null.SetNullString(dr["Comment"]); this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); - if (!string.IsNullOrEmpty(Null.SetNullString(dr["CommentXML"]))) + if (!string.IsNullOrEmpty(Null.SetNullString(dr["CommentXML"]))) { this.CommentXML = new XmlDocument { XmlResolver = null }; this.CommentXML.LoadXml(dr["CommentXML"].ToString()); } - + this.UserId = Null.SetNullInteger(dr["UserId"]); this.DisplayName = Null.SetNullString(dr["DisplayName"]); } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + 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 a01489a1900..cf8874f9c03 100644 --- a/DNN Platform/Library/Services/Journal/Content.cs +++ b/DNN Platform/Library/Services/Journal/Content.cs @@ -16,53 +16,53 @@ 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) + 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) + if (colContentTypes.Count() > 0) { var contentType = colContentTypes.Single(); contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } - else + } + else { contentTypeId = CreateContentType(ContentTypeName); } return contentTypeId; - } - + } + /// /// This should only run after the Post exists in the data store. /// /// The newly created ContentItemID from the data store. /// This is for the first question in the thread. Not for replies or items with ParentID > 0. - internal ContentItem CreateContentItem(JournalItem objJournalItem, int tabId, int moduleId) + internal ContentItem CreateContentItem(JournalItem objJournalItem, int tabId, int moduleId) { var typeController = new ContentTypeController(); string contentTypeName = "DNNCorp_JournalProfile"; - if (objJournalItem.SocialGroupId > 0) + if (objJournalItem.SocialGroupId > 0) { contentTypeName = "DNNCorp_JournalGroup"; } - + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t; int contentTypeID; - if (colContentTypes.Count() > 0) + if (colContentTypes.Count() > 0) { var contentType = colContentTypes.Single(); contentTypeID = contentType == null ? CreateContentType(contentTypeName) : contentType.ContentTypeId; - } - else + } + else { contentTypeID = CreateContentType(contentTypeName); } - var objContent = new ContentItem + var objContent = new ContentItem { Content = GetContentBody(objJournalItem), ContentTypeId = contentTypeID, @@ -83,16 +83,16 @@ internal ContentItem CreateContentItem(JournalItem objJournalItem, int tabId, in /// /// This is used to update the content in the ContentItems table. Should be called when a question is updated. /// - internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int moduleId) + internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int moduleId) { var objContent = Util.GetContentController().GetContentItem(objJournalItem.ContentItemId); - if (objContent == null) - { - return; - } - - // Only update content the contentitem if it was created by the journal + if (objContent == null) + { + return; + } + + // Only update content the contentitem if it was created by the journal if ((objContent.ContentTypeId == GetContentTypeID("DNNCorp_JournalProfile") && objJournalItem.ProfileId > 0) || (objContent.ContentTypeId == GetContentTypeID("DNNCorp_JournalGroup") && objJournalItem.SocialGroupId > 0)) { @@ -103,7 +103,7 @@ internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int modul Util.GetContentController().UpdateContentItem(objContent); } - + // Update Terms // var cntTerm = new Terms(); // cntTerm.ManageQuestionTerms(objPost, objContent); @@ -113,60 +113,60 @@ internal void UpdateContentItem(JournalItem objJournalItem, int tabId, int modul /// This removes a content item associated with a question/thread from the data store. Should run every time an entire thread is deleted. /// /// - internal void DeleteContentItem(int contentItemID) + internal void DeleteContentItem(int contentItemID) { - if (contentItemID <= Null.NullInteger) - { - return; - } - + if (contentItemID <= Null.NullInteger) + { + return; + } + var objContent = Util.GetContentController().GetContentItem(contentItemID); - if (objContent == null) - { - return; - } - - // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) - // var cntTerms = new Terms(); - // cntTerms.RemoveQuestionTerms(objContent); + if (objContent == null) + { + return; + } + + // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) + // var cntTerms = new Terms(); + // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - + /// /// Creates a Content Type (for taxonomy) in the data store. /// /// The primary key value of the new ContentType. - private static int CreateContentType(string ContentTypeName) + private static int CreateContentType(string ContentTypeName) { var typeController = new ContentTypeController(); var objContentType = new ContentType { ContentType = ContentTypeName }; return typeController.AddContentType(objContentType); } - + /// /// Creates the content text. /// /// /// - private static string GetContentBody(JournalItem objJournalItem) + private static string GetContentBody(JournalItem objJournalItem) { - if (!string.IsNullOrEmpty(objJournalItem.Title)) + if (!string.IsNullOrEmpty(objJournalItem.Title)) { return objJournalItem.Title; - } - else if (!string.IsNullOrEmpty(objJournalItem.Summary)) + } + else if (!string.IsNullOrEmpty(objJournalItem.Summary)) { return objJournalItem.Summary; - } - else if (!string.IsNullOrEmpty(objJournalItem.Body)) + } + else if (!string.IsNullOrEmpty(objJournalItem.Body)) { return objJournalItem.Body; - } - else + } + else { return null; } - } + } } } diff --git a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs index a03669707ac..1ce4bfafd45 100644 --- a/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs +++ b/DNN Platform/Library/Services/Journal/Data/IJournalDataService.cs @@ -29,22 +29,22 @@ IDataReader Journal_ListForGroup(int portalId, int moduleId, int currentUserId, void Journal_SoftDeleteByGroupId(int portalId, int groupId); IDataReader Journal_Get(int portalId, int currentUserId, int journalId); - + IDataReader Journal_Get(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck); - + IDataReader Journal_GetByKey(int portalId, string objectKey); - + IDataReader Journal_GetByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted); - + 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); - + 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 commentsHidden, bool commentsDisabled); int Journal_Update(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); - + int Journal_Update(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 commentsHidden, bool commentsDisabled); @@ -67,9 +67,9 @@ int Journal_Update(int portalId, int currentUserId, int profileId, int groupId, void Journal_Comment_Like(int journalId, int commentId, int userId, string displayName); IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId); - + void Journal_Comments_ToggleDisable(int portalId, int journalId, bool disable); - + void Journal_Comments_ToggleHidden(int portalId, int journalId, bool hidden); IDataReader Journal_Types_List(int portalId); diff --git a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs index 6a8e059cf3c..3f3b90b3ac8 100644 --- a/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs +++ b/DNN Platform/Library/Services/Journal/Data/JournalDataServiceImpl.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.Services.Journal internal class JournalDataServiceImpl : IJournalDataService { - private readonly DataProvider _provider = DataProvider.Instance(); - + private readonly DataProvider _provider = DataProvider.Instance(); + public IDataReader Journal_ListForSummary(int portalId, int moduleId, int currentUserId, int rowIndex, int maxRows) { @@ -77,35 +77,35 @@ public void Journal_UpdateContentItemId(int journalId, int contentItemId) { this._provider.ExecuteNonQuery("Journal_UpdateContentItemId", journalId, contentItemId); } - + public IDataReader Journal_Get(int portalId, int currentUserId, int journalId) { return this.Journal_Get(portalId, currentUserId, journalId, false, false, false); } - + public IDataReader Journal_Get(int portalId, int currentUserId, int journalId, bool includeAllItems, bool isDeleted, bool securityCheck) { return this._provider.ExecuteReader("Journal_Get", portalId, currentUserId, journalId, includeAllItems, isDeleted, securityCheck); } - - public IDataReader Journal_GetByKey(int portalId, string objectKey) + + public IDataReader Journal_GetByKey(int portalId, string objectKey) { return this.Journal_GetByKey(portalId, objectKey, false, false); } - + public IDataReader Journal_GetByKey(int portalId, string objectKey, bool includeAllItems, bool isDeleted) { return this._provider.ExecuteReader("Journal_GetByKey", portalId, objectKey, includeAllItems, isDeleted); } - + 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) { 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) { @@ -113,7 +113,7 @@ public int Journal_Save(int portalId, int currentUserId, int profileId, int grou groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, commentsDisabled, commentsHidden); return journalId; } - + public int Journal_Update(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) { @@ -122,7 +122,7 @@ public int Journal_Update(int portalId, int currentUserId, int profileId, int gr return journalId; } - + public int Journal_Update(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) { @@ -130,8 +130,8 @@ public int Journal_Update(int portalId, int currentUserId, int profileId, int gr groupId, title, summary, itemData, xml, objectKey, accessKey, securitySet, commentsDisabled, commentsHidden); return journalId; } - - public void Journal_Comment_Delete(int journalId, int commentId) + + public void Journal_Comment_Delete(int journalId, int commentId) { this._provider.ExecuteNonQuery("Journal_Comment_Delete", journalId, commentId); } @@ -161,12 +161,12 @@ public void Journal_Comment_Like(int journalId, int commentId, int userId, strin { this._provider.ExecuteNonQuery("Journal_Comment_Like", journalId, commentId, userId, displayName); } - - public IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId) + + public IDataReader Journal_Comment_LikeList(int portalId, int journalId, int commentId) { return this._provider.ExecuteReader("Journal_Comment_LikeList", portalId, journalId, commentId); } - + public void Journal_Comments_ToggleDisable(int portalId, int journalId, bool disable) { this._provider.ExecuteNonQuery("Journal_Comments_ToggleDisable", portalId, journalId, disable); @@ -176,8 +176,8 @@ public void Journal_Comments_ToggleHidden(int portalId, int journalId, bool hidd { this._provider.ExecuteNonQuery("Journal_Comments_ToggleHidden", portalId, journalId, hidden); } - - public IDataReader Journal_Types_List(int portalId) + + public IDataReader Journal_Types_List(int portalId) { return this._provider.ExecuteReader("Journal_Types_List", portalId); } @@ -225,6 +225,6 @@ public void Journal_TypeFilters_Delete(int portalId, int moduleId) public void Journal_TypeFilters_Save(int portalId, int moduleId, int journalTypeId) { this._provider.ExecuteNonQuery("Journal_TypeFilters_Save", portalId, moduleId, journalTypeId); - } + } } } diff --git a/DNN Platform/Library/Services/Journal/IJournalController.cs b/DNN Platform/Library/Services/Journal/IJournalController.cs index 5b9f447b638..03368d9a4b3 100644 --- a/DNN Platform/Library/Services/Journal/IJournalController.cs +++ b/DNN Platform/Library/Services/Journal/IJournalController.cs @@ -15,7 +15,7 @@ namespace DotNetNuke.Services.Journal public interface IJournalController { // Journal Items - + /// /// Get journal type by name. /// @@ -124,7 +124,7 @@ public interface IJournalController /// File content. /// A FileInfo object corresponding to the saved file. IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fileName, Stream fileContent); - + /// /// Save the journal object into database. /// diff --git a/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs b/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs index d60019bba0d..b9d06247b22 100644 --- a/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs +++ b/DNN Platform/Library/Services/Journal/Internal/IInternalJournalController.cs @@ -10,13 +10,13 @@ namespace DotNetNuke.Services.Journal.Internal public interface IInternalJournalController { IList GetJournalItemsByProfile(int portalId, int moduleId, int userID, int profileId, int currentIndex, int rows); - + IList GetJournalItemsByGroup(int portalId, int moduleId, int userID, int socialGroupId, int currentIndex, int rows); - + IList GetJournalItems(int portalId, int moduleId, int userID, int currentIndex, int rows); void DeleteFilters(int portalId, int moduleId); - + void SaveFilters(int portalId, int moduleId, int toInt32); } } diff --git a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs index d843c3bc2ad..81c46e0d3e4 100644 --- a/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/Internal/InternalJournalControllerImpl.cs @@ -12,13 +12,13 @@ namespace DotNetNuke.Services.Journal.Internal public class InternalJournalControllerImpl : IInternalJournalController { - private readonly IJournalDataService _dataService; - + private readonly IJournalDataService _dataService; + public InternalJournalControllerImpl() { this._dataService = JournalDataService.Instance; - } - + } + public IList GetJournalItemsByProfile(int portalId, int moduleId, int currentUserId, int profileId, int rowIndex, int maxRows) { diff --git a/DNN Platform/Library/Services/Journal/ItemData.cs b/DNN Platform/Library/Services/Journal/ItemData.cs index 3c85cd542ae..647d176080e 100644 --- a/DNN Platform/Library/Services/Journal/ItemData.cs +++ b/DNN Platform/Library/Services/Journal/ItemData.cs @@ -15,14 +15,6 @@ namespace DotNetNuke.Services.Journal 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 @@ -31,6 +23,14 @@ public CacheLevel Cacheability } } + public string Url { get; set; } + + public string Title { get; set; } + + public string Description { get; set; } + + public string ImageUrl { get; set; } + public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) { string OutputFormat = string.Empty; diff --git a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs index 27b953bf026..4ac7371970f 100644 --- a/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs +++ b/DNN Platform/Library/Services/Journal/JournalControllerImpl.cs @@ -30,18 +30,18 @@ internal class JournalControllerImpl : IJournalController { private const string AllowResizePhotosSetting = "Journal_AllowResizePhotos"; private const string AllowPhotosSetting = "Journal_AllowPhotos"; - private readonly IJournalDataService _dataService; - private const string EditorEnabledSetting = "Journal_EditorEnabled"; + 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' }; - + private static readonly char[] ValidSecurityDescriptors = new[] { 'E', 'C', 'R', 'U', 'F', 'P' }; + private readonly IJournalDataService _dataService; + public JournalControllerImpl() { this._dataService = JournalDataService.Instance; - } - - // Journal Items + } + + // Journal Items public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) { if (journalItem.UserId < 1) @@ -61,12 +61,12 @@ public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) { 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); @@ -89,30 +89,30 @@ public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) 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") { @@ -121,7 +121,7 @@ public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) this.PrepareSecuritySet(journalItem, currentUser); - journalItem.JournalId = this._dataService.Journal_Save( + journalItem.JournalId = this._dataService.Journal_Save( journalItem.PortalId, journalItem.UserId, journalItem.ProfileId, @@ -155,7 +155,7 @@ public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); journalItem.ContentItemId = ci.ContentItemId; } - + if (journalItem.SocialGroupId > 0) { try @@ -168,247 +168,6 @@ public void SaveJournalItem(JournalItem journalItem, int tabId, int moduleId) } } } - - private XmlElement CreateElement(XmlDocument xDoc, string name, string value) - { - XmlElement xnode = xDoc.CreateElement(name); - XmlText xtext = xDoc.CreateTextNode(value); - xnode.AppendChild(xtext); - return xnode; - } - - private XmlElement CreateCDataElement(XmlDocument xDoc, string name, string value) - { - XmlElement xnode = xDoc.CreateElement(name); - XmlCDataSection xdata = xDoc.CreateCDataSection(value); - xnode.AppendChild(xdata); - return xnode; - } - - private void UpdateGroupStats(int portalId, int groupId) - { - RoleInfo role = RoleController.Instance.GetRole(portalId, r => r.RoleID == groupId); - if (role == null) - { - return; - } - - for (var i = 0; i < role.Settings.Keys.Count; i++) - { - var key = role.Settings.Keys.ElementAt(i); - if (key.StartsWith("stat_")) - { - role.Settings[key] = "0"; - } - } - - using (IDataReader dr = this._dataService.Journal_GetStatsForGroup(portalId, groupId)) - { - while (dr.Read()) - { - string settingName = "stat_" + dr["JournalType"]; - if (role.Settings.ContainsKey(settingName)) - { - role.Settings[settingName] = dr["JournalTypeCount"].ToString(); - } - else - { - role.Settings.Add(settingName, dr["JournalTypeCount"].ToString()); - } - } - - dr.Close(); - } - - RoleController.Instance.UpdateRoleSettings(role, true); - } - - private void DeleteJournalItem(int portalId, int currentUserId, int journalId, bool softDelete) - { - var ji = this.GetJournalItem(portalId, currentUserId, journalId, !softDelete); - if (ji == null) - { - return; - } - - var groupId = ji.SocialGroupId; - - if (softDelete) - { - this._dataService.Journal_SoftDelete(journalId); - } - else - { - this._dataService.Journal_Delete(journalId); - } - - if (groupId > 0) - { - this.UpdateGroupStats(portalId, groupId); - } - - // queue remove journal from search index - var document = new SearchDocumentToDelete - { - PortalId = portalId, - AuthorUserId = currentUserId, - UniqueKey = ji.ContentItemId.ToString("D"), - - // QueryString = "journalid=" + journalId, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, - }; - - if (groupId > 0) - { - document.RoleId = groupId; - } - - DataProvider.Instance().AddSearchDeletedItems(document); - } - - private Stream GetJournalImageContent(Stream fileContent) - { - Image image = new Bitmap(fileContent); - int thumbnailWidth = 400; - int thumbnailHeight = 400; - this.GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); - var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, this.ThumbnailCallback, IntPtr.Zero); - var result = new MemoryStream(); - thumbnail.Save(result, image.RawFormat); - return result; - } - - private void GetThumbnailSize(int imageWidth, int imageHeight, ref int thumbnailWidth, ref int thumbnailHeight) - { - if (imageWidth >= imageHeight) - { - thumbnailWidth = Math.Min(imageWidth, thumbnailWidth); - thumbnailHeight = this.GetMinorSize(imageHeight, imageWidth, thumbnailWidth); - } - else - { - thumbnailHeight = Math.Min(imageHeight, thumbnailHeight); - thumbnailWidth = this.GetMinorSize(imageWidth, imageHeight, thumbnailHeight); - } - } - - private int GetMinorSize(int imageMinorSize, int imageMajorSize, int thumbnailMajorSize) - { - if (imageMajorSize == thumbnailMajorSize) - { - return imageMinorSize; - } - - double calculated = (Convert.ToDouble(imageMinorSize) * Convert.ToDouble(thumbnailMajorSize)) / Convert.ToDouble(imageMajorSize); - return Convert.ToInt32(Math.Round(calculated)); - } - - private bool IsImageFile(string fileName) - { - return (Globals.glbImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", string.Empty) + ",", StringComparison.InvariantCultureIgnoreCase) > -1; - } - - private bool ThumbnailCallback() - { - return true; - } - - private bool IsResizePhotosEnabled(ModuleInfo module) - { - return this.GetBooleanSetting(AllowResizePhotosSetting, false, module) && - this.GetBooleanSetting(AllowPhotosSetting, true, module) && - this.GetBooleanSetting(EditorEnabledSetting, true, module); - } - - private bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo module) - { - if (module.ModuleSettings.Contains(settingName)) - { - return Convert.ToBoolean(module.ModuleSettings[settingName].ToString()); - } - - return defaultValue; - } - - // none of the parameters should be null; checked before calling this method - private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) - { - var originalSecuritySet = - journalItem.SecuritySet = (journalItem.SecuritySet ?? string.Empty).ToUpperInvariant(); - - if (string.IsNullOrEmpty(journalItem.SecuritySet)) - { - journalItem.SecuritySet = "E,"; - } - else if (!journalItem.SecuritySet.EndsWith(",")) - { - journalItem.SecuritySet += ","; - originalSecuritySet = journalItem.SecuritySet; - } - - if (journalItem.SecuritySet == "F,") - { - journalItem.SecuritySet = "F" + journalItem.UserId + ","; - if (journalItem.ProfileId > 0) - { - journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; - } - } - else if (journalItem.SecuritySet == "U,") - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - else if (journalItem.SecuritySet == "R,") - { - if (journalItem.SocialGroupId > 0) - { - journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; - } - } - - if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId) - { - if (!journalItem.SecuritySet.Contains("P" + journalItem.ProfileId + ",")) - { - journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; - } - - if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - } - - if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) - { - journalItem.SecuritySet += "U" + journalItem.UserId + ","; - } - - // if the post is marked as private, we shouldn't make it visible to the group. - if (journalItem.SocialGroupId > 0 && originalSecuritySet.Contains("U,")) - { - var item = journalItem; - var role = RoleController.Instance.GetRole( - journalItem.PortalId, - r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId); - - if (role != null && !role.IsPublic) - { - journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", string.Empty).Replace("C,", string.Empty); - } - } - - // clean up and remove duplicates - var parts = journalItem.SecuritySet - .Replace(" ", string.Empty) - .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) - .Distinct() - .Except(InvalidSecuritySetsWithoutId) - .Where(p => p.IndexOfAny(ValidSecurityDescriptors) >= 0); - - // TODO: validate existence and visibility/accessability of all Roles added to the set (if any) - journalItem.SecuritySet = string.Join(",", parts); - } public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) { @@ -416,30 +175,30 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) { 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 }; @@ -457,31 +216,31 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) 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") { @@ -490,7 +249,7 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) this.PrepareSecuritySet(journalItem, currentUser); - journalItem.JournalId = this._dataService.Journal_Update( + journalItem.JournalId = this._dataService.Journal_Update( journalItem.PortalId, journalItem.UserId, journalItem.ProfileId, @@ -524,7 +283,7 @@ public void UpdateJournalItem(JournalItem journalItem, int tabId, int moduleId) this._dataService.Journal_UpdateContentItemId(journalItem.JournalId, ci.ContentItemId); journalItem.ContentItemId = ci.ContentItemId; } - + if (journalItem.SocialGroupId > 0) { try @@ -574,7 +333,7 @@ public JournalItem GetJournalItemByKey(int portalId, string objectKey, bool incl { return null; } - + return CBO.FillObject(this._dataService.Journal_GetByKey(portalId, objectKey, includeAllItems, isDeleted)); } @@ -589,7 +348,7 @@ public IFileInfo SaveJourmalFile(ModuleInfo module, UserInfo userInfo, string fi return FileManager.Instance.AddFile(userFolder, fileName, stream, true); } } - + // todo: deal with the case where the exact file name already exists. return FileManager.Instance.AddFile(userFolder, fileName, fileContent, true); } @@ -626,12 +385,12 @@ public void HideComments(int portalId, int journalId) } public void ShowComments(int portalId, int journalId) - { + { this._dataService.Journal_Comments_ToggleHidden(portalId, journalId, false); } // Delete Journal Items - + /// /// HARD deletes journal items. /// @@ -714,7 +473,7 @@ public void SaveComment(CommentInfo comment) comment.Comment = portalSecurity.InputFilter(comment.Comment, PortalSecurity.FilterFlag.NoScripting); } - + // TODO: enable once the profanity filter is working properly. // objCommentInfo.Comment = portalSecurity.Remove(objCommentInfo.Comment, DotNetNuke.Security.PortalSecurity.ConfigType.ListController, "ProfanityFilter", DotNetNuke.Security.PortalSecurity.FilterScope.PortalList); string xml = null; @@ -738,15 +497,15 @@ public CommentInfo GetComment(int commentId) public void DeleteComment(int journalId, int commentId) { this._dataService.Journal_Comment_Delete(journalId, commentId); - + // UNDONE: update the parent journal item and content item so this comment gets removed from search index } public void LikeComment(int journalId, int commentId, int userId, string displayName) { this._dataService.Journal_Comment_Like(journalId, commentId, userId, displayName); - } - + } + public JournalTypeInfo GetJournalType(string journalType) { return CBO.FillObject(this._dataService.Journal_Types_Get(journalType)); @@ -760,14 +519,14 @@ public JournalTypeInfo GetJournalTypeById(int journalTypeId) public IEnumerable GetJournalTypes(int portalId) { return CBO.GetCachedObject>( - new CacheItemArgs( + new CacheItemArgs( string.Format(DataCache.JournalTypesCacheKey, portalId), DataCache.JournalTypesTimeOut, DataCache.JournalTypesCachePriority, portalId), c => CBO.FillCollection(this._dataService.Journal_Types_List(portalId))); - } - + } + [Obsolete("Deprecated in DNN 7.2.2. Use SaveJournalItem(JournalItem, ModuleInfo). Scheduled removal in v10.0.0.")] public void SaveJournalItem(JournalItem journalItem, int tabId) { @@ -778,6 +537,247 @@ public void SaveJournalItem(JournalItem journalItem, int tabId) public void UpdateJournalItem(JournalItem journalItem, int tabId) { this.UpdateJournalItem(journalItem, tabId, Null.NullInteger); - } + } + + private XmlElement CreateElement(XmlDocument xDoc, string name, string value) + { + XmlElement xnode = xDoc.CreateElement(name); + XmlText xtext = xDoc.CreateTextNode(value); + xnode.AppendChild(xtext); + return xnode; + } + + private XmlElement CreateCDataElement(XmlDocument xDoc, string name, string value) + { + XmlElement xnode = xDoc.CreateElement(name); + XmlCDataSection xdata = xDoc.CreateCDataSection(value); + xnode.AppendChild(xdata); + return xnode; + } + + private void UpdateGroupStats(int portalId, int groupId) + { + RoleInfo role = RoleController.Instance.GetRole(portalId, r => r.RoleID == groupId); + if (role == null) + { + return; + } + + for (var i = 0; i < role.Settings.Keys.Count; i++) + { + var key = role.Settings.Keys.ElementAt(i); + if (key.StartsWith("stat_")) + { + role.Settings[key] = "0"; + } + } + + using (IDataReader dr = this._dataService.Journal_GetStatsForGroup(portalId, groupId)) + { + while (dr.Read()) + { + string settingName = "stat_" + dr["JournalType"]; + if (role.Settings.ContainsKey(settingName)) + { + role.Settings[settingName] = dr["JournalTypeCount"].ToString(); + } + else + { + role.Settings.Add(settingName, dr["JournalTypeCount"].ToString()); + } + } + + dr.Close(); + } + + RoleController.Instance.UpdateRoleSettings(role, true); + } + + private void DeleteJournalItem(int portalId, int currentUserId, int journalId, bool softDelete) + { + var ji = this.GetJournalItem(portalId, currentUserId, journalId, !softDelete); + if (ji == null) + { + return; + } + + var groupId = ji.SocialGroupId; + + if (softDelete) + { + this._dataService.Journal_SoftDelete(journalId); + } + else + { + this._dataService.Journal_Delete(journalId); + } + + if (groupId > 0) + { + this.UpdateGroupStats(portalId, groupId); + } + + // queue remove journal from search index + var document = new SearchDocumentToDelete + { + PortalId = portalId, + AuthorUserId = currentUserId, + UniqueKey = ji.ContentItemId.ToString("D"), + + // QueryString = "journalid=" + journalId, + SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, + }; + + if (groupId > 0) + { + document.RoleId = groupId; + } + + DataProvider.Instance().AddSearchDeletedItems(document); + } + + private Stream GetJournalImageContent(Stream fileContent) + { + Image image = new Bitmap(fileContent); + int thumbnailWidth = 400; + int thumbnailHeight = 400; + this.GetThumbnailSize(image.Width, image.Height, ref thumbnailWidth, ref thumbnailHeight); + var thumbnail = image.GetThumbnailImage(thumbnailWidth, thumbnailHeight, this.ThumbnailCallback, IntPtr.Zero); + var result = new MemoryStream(); + thumbnail.Save(result, image.RawFormat); + return result; + } + + private void GetThumbnailSize(int imageWidth, int imageHeight, ref int thumbnailWidth, ref int thumbnailHeight) + { + if (imageWidth >= imageHeight) + { + thumbnailWidth = Math.Min(imageWidth, thumbnailWidth); + thumbnailHeight = this.GetMinorSize(imageHeight, imageWidth, thumbnailWidth); + } + else + { + thumbnailHeight = Math.Min(imageHeight, thumbnailHeight); + thumbnailWidth = this.GetMinorSize(imageWidth, imageHeight, thumbnailHeight); + } + } + + private int GetMinorSize(int imageMinorSize, int imageMajorSize, int thumbnailMajorSize) + { + if (imageMajorSize == thumbnailMajorSize) + { + return imageMinorSize; + } + + double calculated = (Convert.ToDouble(imageMinorSize) * Convert.ToDouble(thumbnailMajorSize)) / Convert.ToDouble(imageMajorSize); + return Convert.ToInt32(Math.Round(calculated)); + } + + private bool IsImageFile(string fileName) + { + return (Globals.glbImageFileTypes + ",").IndexOf(Path.GetExtension(fileName).Replace(".", string.Empty) + ",", StringComparison.InvariantCultureIgnoreCase) > -1; + } + + private bool ThumbnailCallback() + { + return true; + } + + private bool IsResizePhotosEnabled(ModuleInfo module) + { + return this.GetBooleanSetting(AllowResizePhotosSetting, false, module) && + this.GetBooleanSetting(AllowPhotosSetting, true, module) && + this.GetBooleanSetting(EditorEnabledSetting, true, module); + } + + private bool GetBooleanSetting(string settingName, bool defaultValue, ModuleInfo module) + { + if (module.ModuleSettings.Contains(settingName)) + { + return Convert.ToBoolean(module.ModuleSettings[settingName].ToString()); + } + + return defaultValue; + } + + // none of the parameters should be null; checked before calling this method + private void PrepareSecuritySet(JournalItem journalItem, UserInfo currentUser) + { + var originalSecuritySet = + journalItem.SecuritySet = (journalItem.SecuritySet ?? string.Empty).ToUpperInvariant(); + + if (string.IsNullOrEmpty(journalItem.SecuritySet)) + { + journalItem.SecuritySet = "E,"; + } + else if (!journalItem.SecuritySet.EndsWith(",")) + { + journalItem.SecuritySet += ","; + originalSecuritySet = journalItem.SecuritySet; + } + + if (journalItem.SecuritySet == "F,") + { + journalItem.SecuritySet = "F" + journalItem.UserId + ","; + if (journalItem.ProfileId > 0) + { + journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + } + } + else if (journalItem.SecuritySet == "U,") + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + else if (journalItem.SecuritySet == "R,") + { + if (journalItem.SocialGroupId > 0) + { + journalItem.SecuritySet += "R" + journalItem.SocialGroupId + ","; + } + } + + if (journalItem.ProfileId > 0 && journalItem.UserId != journalItem.ProfileId) + { + if (!journalItem.SecuritySet.Contains("P" + journalItem.ProfileId + ",")) + { + journalItem.SecuritySet += "P" + journalItem.ProfileId + ","; + } + + if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + } + + if (!journalItem.SecuritySet.Contains("U" + journalItem.UserId + ",")) + { + journalItem.SecuritySet += "U" + journalItem.UserId + ","; + } + + // if the post is marked as private, we shouldn't make it visible to the group. + if (journalItem.SocialGroupId > 0 && originalSecuritySet.Contains("U,")) + { + var item = journalItem; + var role = RoleController.Instance.GetRole( + journalItem.PortalId, + r => r.SecurityMode != SecurityMode.SecurityRole && r.RoleID == item.SocialGroupId); + + if (role != null && !role.IsPublic) + { + journalItem.SecuritySet = journalItem.SecuritySet.Replace("E,", string.Empty).Replace("C,", string.Empty); + } + } + + // clean up and remove duplicates + var parts = journalItem.SecuritySet + .Replace(" ", string.Empty) + .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) + .Distinct() + .Except(InvalidSecuritySetsWithoutId) + .Where(p => p.IndexOfAny(ValidSecurityDescriptors) >= 0); + + // TODO: validate existence and visibility/accessability of all Roles added to the set (if any) + journalItem.SecuritySet = string.Join(",", parts); + } } } diff --git a/DNN Platform/Library/Services/Journal/JournalEntity.cs b/DNN Platform/Library/Services/Journal/JournalEntity.cs index 6193564a206..15c0e60c15d 100644 --- a/DNN Platform/Library/Services/Journal/JournalEntity.cs +++ b/DNN Platform/Library/Services/Journal/JournalEntity.cs @@ -14,26 +14,26 @@ namespace DotNetNuke.Services.Journal public class JournalEntity : IPropertyAccess { - public JournalEntity() + public JournalEntity() { } - - public JournalEntity(string entityXML) + + public JournalEntity(string entityXML) { - if (!string.IsNullOrEmpty(entityXML)) + if (!string.IsNullOrEmpty(entityXML)) { XmlDocument xDoc = new XmlDocument { XmlResolver = null }; xDoc.LoadXml(entityXML); - if (xDoc != null) + if (xDoc != null) { XmlNode xRoot = xDoc.DocumentElement; XmlNode xNode = null; xNode = xRoot.SelectSingleNode("//entity"); - if (xNode != null) + if (xNode != null) { this.Id = int.Parse(xNode["id"].InnerText); this.Name = xNode["name"].InnerText.ToString(); - if (xNode["vanity"] != null) + if (xNode["vanity"] != null) { this.Vanity = xNode["vanity"].InnerText.ToString(); } @@ -41,34 +41,34 @@ 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 + 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) + public int Id { get; set; } + + public string Name { get; set; } + + public string Vanity { get; set; } + + public string Avatar { get; set; } + + 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) + if (format == string.Empty) { OutputFormat = "g"; - } - else + } + else { OutputFormat = format; } - + propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) + switch (propertyName) { case "id": return PropertyAccess.FormatString(this.Id.ToString(), format); diff --git a/DNN Platform/Library/Services/Journal/JournalItem.cs b/DNN Platform/Library/Services/Journal/JournalItem.cs index eae1339a26b..b9c467c2aef 100644 --- a/DNN Platform/Library/Services/Journal/JournalItem.cs +++ b/DNN Platform/Library/Services/Journal/JournalItem.cs @@ -19,58 +19,66 @@ namespace DotNetNuke.Services.Journal public class JournalItem : IHydratable, IPropertyAccess { + public CacheLevel Cacheability + { + get + { + return CacheLevel.fullyCacheable; + } + } + public int JournalId { get; set; } - + public int JournalTypeId { get; set; } - + public int PortalId { get; set; } - + public int UserId { get; set; } - + public int ProfileId { get; set; } - + public int SocialGroupId { get; set; } - + public string Title { get; set; } - + public string Summary { get; set; } - + public string Body { get; set; } - + public ItemData ItemData { get; set; } - + public XmlDocument JournalXML { get; set; } - + public DateTime DateCreated { get; set; } - + public DateTime DateUpdated { get; set; } - + public string ObjectKey { get; set; } - + public Guid AccessKey { get; set; } - + public string SecuritySet { get; set; } - + public int ContentItemId { get; set; } - + public JournalEntity JournalAuthor { get; set; } - + public JournalEntity JournalOwner { get; set; } - + public string TimeFrame { get; set; } - + public bool CurrentUserLikes { get; set; } - + public string JournalType { get; set; } - + public bool IsDeleted { get; set; } - + public bool CommentsDisabled { get; set; } - + public bool CommentsHidden { get; set; } - - public int SimilarCount { get; set; } - + + public int SimilarCount { get; set; } + /// /// Gets or sets the key ID. /// @@ -81,28 +89,20 @@ public class JournalItem : IHydratable, IPropertyAccess /// 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 + public virtual int KeyID { - get + get { return this.JournalId; } - - set + + set { this.JournalId = value; } } - - public CacheLevel Cacheability - { - get - { - return CacheLevel.fullyCacheable; - } - } - public void Fill(IDataReader dr) + public void Fill(IDataReader dr) { this.JournalId = Null.SetNullInteger(dr["JournalId"]); this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); @@ -110,18 +110,18 @@ public void Fill(IDataReader dr) this.UserId = Null.SetNullInteger(dr["UserId"]); this.ProfileId = Null.SetNullInteger(dr["ProfileId"]); this.SocialGroupId = Null.SetNullInteger(dr["GroupId"]); - if (!string.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) + if (!string.IsNullOrEmpty(Null.SetNullString(dr["JournalXML"]))) { this.JournalXML = new XmlDocument { XmlResolver = null }; this.JournalXML.LoadXml(dr["JournalXML"].ToString()); XmlNode xRoot = this.JournalXML.DocumentElement; XmlNode xNode = xRoot.SelectSingleNode("//items/item/body"); - if (xNode != null) + if (xNode != null) { this.Body = xNode.InnerText; } } - + this.DateCreated = Null.SetNullDateTime(dr["DateCreated"]); this.DateUpdated = Null.SetNullDateTime(dr["DateUpdated"]); this.ObjectKey = Null.SetNullString(dr["ObjectKey"]); @@ -130,11 +130,11 @@ public void Fill(IDataReader dr) this.Summary = Null.SetNullString(dr["Summary"]); string itemd = Null.SetNullString(dr["ItemData"]); this.ItemData = new ItemData(); - if (!string.IsNullOrEmpty(itemd)) + if (!string.IsNullOrEmpty(itemd)) { this.ItemData = itemd.FromJson(); } - + this.ContentItemId = Null.SetNullInteger(dr["ContentItemId"]); this.JournalAuthor = new JournalEntity(dr["JournalAuthor"].ToString()); this.JournalOwner = new JournalEntity(dr["JournalOwner"].ToString()); @@ -146,20 +146,20 @@ public void Fill(IDataReader dr) this.SimilarCount = Null.SetNullInteger(dr["SimilarCount"]); } - public string GetProperty(string propertyName, string format, System.Globalization.CultureInfo formatProvider, Entities.Users.UserInfo accessingUser, Scope accessLevel, ref bool propertyNotFound) + 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) + if (format == string.Empty) { OutputFormat = "g"; - } - else + } + else { OutputFormat = format; } - + propertyName = propertyName.ToLowerInvariant(); - switch (propertyName) + switch (propertyName) { case "journalid": return PropertyAccess.FormatString(this.JournalId.ToString(), format); diff --git a/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs b/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs index 24fa6967348..a220cb3c9e1 100644 --- a/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs +++ b/DNN Platform/Library/Services/Journal/JournalTypeInfo.cs @@ -16,41 +16,41 @@ namespace DotNetNuke.Services.Journal public class JournalTypeInfo : IHydratable { public int JournalTypeId { get; set; } - + public int PortalId { get; set; } - + public string JournalType { get; set; } - + public string icon { get; set; } - + public bool AppliesToProfile { get; set; } - + public bool AppliesToGroup { get; set; } - + public bool AppliesToStream { get; set; } - + public bool SupportsNotify { get; set; } - + public string Options { get; set; } - + public bool IsEnabled { get; set; } - + public bool EnableComments { get; set; } - - public int KeyID + + public int KeyID { - get + get { return this.JournalTypeId; } - - set + + set { this.JournalTypeId = value; } } - public void Fill(System.Data.IDataReader dr) + public void Fill(System.Data.IDataReader dr) { this.JournalTypeId = Null.SetNullInteger(dr["JournalTypeId"]); this.PortalId = Null.SetNullInteger(dr["PortalId"]); diff --git a/DNN Platform/Library/Services/Localization/CultureDropDownTypes.cs b/DNN Platform/Library/Services/Localization/CultureDropDownTypes.cs new file mode 100644 index 00000000000..0c99065356f --- /dev/null +++ b/DNN Platform/Library/Services/Localization/CultureDropDownTypes.cs @@ -0,0 +1,50 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information +namespace DotNetNuke.Services.Localization +{ + using System; + + /// + /// CultureDropDownTypes allows the user to specify which culture name is displayed in the drop down list that is filled + /// by using one of the helper methods. + /// + [Serializable] + public enum CultureDropDownTypes + { + /// + /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the .NET Framework language + /// + DisplayName, + + /// + /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in English + /// + EnglishName, + + /// + /// Displays the culture identifier + /// + Lcid, + + /// + /// Displays the culture name in the format "<languagecode2> (<country/regioncode2>) + /// + Name, + + /// + /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the language that the culture is set to display + /// + NativeName, + + /// + /// Displays the IS0 639-1 two letter code + /// + TwoLetterIsoCode, + + /// + /// Displays the ISO 629-2 three letter code "<languagefull> (<country/regionfull>) + /// + ThreeLetterIsoCode, + } +} diff --git a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs index 6d6d1525673..746fa836e6a 100644 --- a/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs +++ b/DNN Platform/Library/Services/Localization/CultureInfoComparer.cs @@ -13,8 +13,8 @@ public class CultureInfoComparer : IComparer public CultureInfoComparer(string compareBy) { this._compare = compareBy; - } - + } + public int Compare(object x, object y) { switch (this._compare.ToUpperInvariant()) @@ -26,6 +26,6 @@ public int Compare(object x, object y) default: return ((CultureInfo)x).Name.CompareTo(((CultureInfo)y).Name); } - } + } } } diff --git a/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs b/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs index 3faeb576cff..fcf29715dbb 100644 --- a/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs +++ b/DNN Platform/Library/Services/Localization/ILocalizationProvider.cs @@ -15,13 +15,13 @@ namespace DotNetNuke.Services.Localization public interface ILocalizationProvider { string GetString(string key, string resourceFileRoot); - + string GetString(string key, string resourceFileRoot, string language); - + string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings); - + string GetString(string key, string resourceFileRoot, string language, PortalSettings portalSettings, bool disableShowMissingKeys); - + /// /// Saves a string to a resource file. /// diff --git a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs index 55901298efa..6c2bd9cdd87 100644 --- a/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs +++ b/DNN Platform/Library/Services/Localization/Internal/LocalizationImpl.cs @@ -31,7 +31,7 @@ public string BestCultureCodeBasedOnBrowserLanguages(IEnumerable culture foreach (string langHeader in HttpContextSource.Current.Request.UserLanguages ?? new string[0]) { string lang = langHeader; - + // strip any ;q=xx lang = lang.Split(';')[0]; diff --git a/DNN Platform/Library/Services/Localization/LanguagePackController.cs b/DNN Platform/Library/Services/Localization/LanguagePackController.cs index d6eb26baa98..6b930cb289f 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackController.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackController.cs @@ -38,7 +38,7 @@ public static void SaveLanguagePack(LanguagePackInfo languagePack) if (languagePack.LanguagePackID == Null.NullInteger) { // Add Language Pack - languagePack.LanguagePackID = DataProvider.Instance().AddLanguagePack( + languagePack.LanguagePackID = DataProvider.Instance().AddLanguagePack( languagePack.PackageID, languagePack.LanguageID, languagePack.DependentPackageID, @@ -48,7 +48,7 @@ public static void SaveLanguagePack(LanguagePackInfo languagePack) else { // Update LanguagePack - DataProvider.Instance().UpdateLanguagePack( + DataProvider.Instance().UpdateLanguagePack( languagePack.LanguagePackID, languagePack.PackageID, languagePack.LanguageID, diff --git a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs index 646a434d9fe..d6437dee04b 100644 --- a/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs +++ b/DNN Platform/Library/Services/Localization/LanguagePackInfo.cs @@ -12,19 +12,34 @@ namespace DotNetNuke.Services.Localization [Serializable] public class LanguagePackInfo : BaseEntityInfo, IHydratable - { + { private int _DependentPackageID = Null.NullInteger; private int _LanguageID = Null.NullInteger; private int _LanguagePackID = Null.NullInteger; - private int _PackageID = Null.NullInteger; - + private int _PackageID = Null.NullInteger; + + public LanguagePackType PackageType + { + get + { + if (this.DependentPackageID == -2) + { + return LanguagePackType.Core; + } + else + { + return LanguagePackType.Extension; + } + } + } + public int LanguagePackID { get { return this._LanguagePackID; } - + set { this._LanguagePackID = value; @@ -37,7 +52,7 @@ public int LanguageID { return this._LanguageID; } - + set { this._LanguageID = value; @@ -50,7 +65,7 @@ public int PackageID { return this._PackageID; } - + set { this._PackageID = value; @@ -63,48 +78,33 @@ public int DependentPackageID { return this._DependentPackageID; } - + set { this._DependentPackageID = value; } } - public LanguagePackType PackageType - { - get - { - if (this.DependentPackageID == -2) - { - return LanguagePackType.Core; - } - else - { - return LanguagePackType.Extension; - } - } - } - public int KeyID { get { return this.LanguagePackID; } - + set { 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 dc531d2925b..2e132f16aa5 100644 --- a/DNN Platform/Library/Services/Localization/Locale.cs +++ b/DNN Platform/Library/Services/Localization/Locale.cs @@ -22,9 +22,7 @@ public Locale() this.PortalId = Null.NullInteger; this.LanguageId = Null.NullInteger; this.IsPublished = Null.NullBoolean; - } - - public string Code { get; set; } + } public CultureInfo Culture { @@ -43,13 +41,11 @@ public string EnglishName { _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.EnglishName); } - + return _Name; } } - public string Fallback { get; set; } - public Locale FallBackLocale { get @@ -59,15 +55,11 @@ public Locale FallBackLocale { _FallbackLocale = LocaleController.Instance.GetLocale(this.PortalId, this.Fallback); } - + return _FallbackLocale; } } - public bool IsPublished { get; set; } - - public int LanguageId { get; set; } - public string NativeName { get @@ -77,14 +69,22 @@ public string NativeName { _Name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.NativeName); } - + return _Name; } } + public string Code { get; set; } + + public string Fallback { get; set; } + + public bool IsPublished { get; set; } + + public int LanguageId { get; set; } + public int PortalId { get; set; } - public string Text { get; set; } + public string Text { get; set; } public int KeyID { @@ -92,13 +92,13 @@ public int KeyID { return this.LanguageId; } - + set { this.LanguageId = value; } - } - + } + public void Fill(IDataReader dr) { this.LanguageId = Null.SetNullInteger(dr["LanguageID"]); diff --git a/DNN Platform/Library/Services/Localization/LocaleCollection.cs b/DNN Platform/Library/Services/Localization/LocaleCollection.cs index f57afa35f0a..10b58322f4b 100644 --- a/DNN Platform/Library/Services/Localization/LocaleCollection.cs +++ b/DNN Platform/Library/Services/Localization/LocaleCollection.cs @@ -58,7 +58,7 @@ public Locale this[string key] { 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 8e8c58de632..0527c1bdf08 100644 --- a/DNN Platform/Library/Services/Localization/LocaleController.cs +++ b/DNN Platform/Library/Services/Localization/LocaleController.cs @@ -29,15 +29,15 @@ namespace DotNetNuke.Services.Localization /// extensive changes to the core platform, we have been able to add this new feature while still improving overall system performance. /// public class LocaleController : ComponentBase, ILocaleController - { + { public static bool IsValidCultureName(string name) { return CultureInfo .GetCultures(CultureTypes.SpecificCultures) .Any(c => c.Name == name); - } - + } + /// /// Determines whether the language can be delete. /// @@ -61,15 +61,6 @@ 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. @@ -84,7 +75,7 @@ public Locale GetCurrentLocale(int PortalId) { locale = this.GetLocale(HttpContext.Current.Request.QueryString["language"]); } - + return locale ?? ((PortalId == Null.NullInteger) ? this.GetLocale(Localization.SystemLocale) : this.GetDefaultLocale(PortalId)); @@ -107,7 +98,7 @@ public Locale GetDefaultLocale(int portalId) locale = locales[portal.DefaultLanguage]; } } - + return locale ?? this.GetLocale(Localization.SystemLocale); } @@ -184,7 +175,7 @@ public Dictionary GetLocales(int portalID) { locales = CBO.FillDictionary("CultureCode", DataProvider.Instance().GetLanguages(), new Dictionary(StringComparer.OrdinalIgnoreCase)); } - + return locales; } @@ -239,7 +230,7 @@ public bool IsEnabled(ref string localeCode, int portalId) { enabled = true; } - + return enabled; } catch (Exception ex) @@ -312,5 +303,14 @@ public void PublishLanguage(int portalid, string cultureCode, bool publish) } } } + + 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; + } } } diff --git a/DNN Platform/Library/Services/Localization/Localization.cs b/DNN Platform/Library/Services/Localization/Localization.cs index cb9d342172f..3d84f9efb22 100644 --- a/DNN Platform/Library/Services/Localization/Localization.cs +++ b/DNN Platform/Library/Services/Localization/Localization.cs @@ -11,13 +11,13 @@ namespace DotNetNuke.Services.Localization using System.IO; using System.Linq; using System.Reflection; - using System.Text.RegularExpressions; + using System.Text.RegularExpressions; using System.Threading; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; - + using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; @@ -32,49 +32,6 @@ namespace DotNetNuke.Services.Localization using DotNetNuke.Services.Log.EventLog; using DotNetNuke.Services.Tokens; using DotNetNuke.UI.Modules; - - /// - /// CultureDropDownTypes allows the user to specify which culture name is displayed in the drop down list that is filled - /// by using one of the helper methods. - /// - [Serializable] - public enum CultureDropDownTypes - { - /// - /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the .NET Framework language - /// - DisplayName, - - /// - /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in English - /// - EnglishName, - - /// - /// Displays the culture identifier - /// - Lcid, - - /// - /// Displays the culture name in the format "<languagecode2> (<country/regioncode2>) - /// - Name, - - /// - /// Displays the culture name in the format "<languagefull> (<country/regionfull>) in the language that the culture is set to display - /// - NativeName, - - /// - /// Displays the IS0 639-1 two letter code - /// - TwoLetterIsoCode, - - /// - /// Displays the ISO 629-2 three letter code "<languagefull> (<country/regionfull>) - /// - ThreeLetterIsoCode, - } /// /// Localization class support localization in system. @@ -100,13 +57,13 @@ public enum CultureDropDownTypes /// public class Localization { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Localization)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Localization)); private static string _defaultKeyName = "resourcekey"; - + // private static readonly ILocaleController LocaleController.Instance = LocaleController.Instance; // private static readonly ILocalizationProvider _localizationProvider = LocalizationProvider.Instance; - private static bool? _showMissingKeys; - + private static bool? _showMissingKeys; + /// /// Gets ~/App_GlobalResources. /// @@ -140,30 +97,6 @@ public static string GlobalResourceFile } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets the KeyName property returns and caches the name of the key attribute used to lookup resources. - /// This can be configured by setting ResourceManagerKey property in the web.config file. The default value for this property - /// is 'key'. - /// - /// ----------------------------------------------------------------------------- - public static string KeyName - { - get - { - return _defaultKeyName; - } - - set - { - _defaultKeyName = value; - if (string.IsNullOrEmpty(_defaultKeyName)) - { - _defaultKeyName = "resourcekey"; - } - } - } - public static string LocalResourceDirectory { get @@ -239,8 +172,32 @@ public static string SystemTimeZone { return "Pacific Standard Time"; } - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the KeyName property returns and caches the name of the key attribute used to lookup resources. + /// This can be configured by setting ResourceManagerKey property in the web.config file. The default value for this property + /// is 'key'. + /// + /// ----------------------------------------------------------------------------- + public static string KeyName + { + get + { + return _defaultKeyName; + } + + set + { + _defaultKeyName = value; + if (string.IsNullOrEmpty(_defaultKeyName)) + { + _defaultKeyName = "resourcekey"; + } + } + } + /// ----------------------------------------------------------------------------- /// /// Gets the CurrentCulture returns the current Culture being used @@ -266,8 +223,8 @@ public string CurrentUICulture { return Thread.CurrentThread.CurrentUICulture.ToString(); } - } - + } + public static int ActiveLanguagesByPortalID(int portalID) { // Default to 1 (maybe called during portal creation before languages are enabled for portal) @@ -277,7 +234,7 @@ public static int ActiveLanguagesByPortalID(int portalID) { count = locales.Count; } - + return count; } @@ -307,7 +264,7 @@ public static void AddLanguageToPortal(int portalID, int languageID, bool clearC string cacheKey = string.Format(DataCache.LocalesCacheKey, portalID); DataCache.RemoveCache(cacheKey); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "portalID/languageID", portalID + "/" + languageID, PortalController.Instance.GetCurrentPortalSettings(), @@ -325,7 +282,7 @@ public static void AddLanguageToPortal(int portalID, int languageID, bool clearC { AddLanguageHttpAlias(portalID, LocaleController.Instance.GetLocale(portalID, portalInfo.DefaultLanguage)); } - + AddLanguageHttpAlias(portalID, newLocale); } @@ -336,108 +293,6 @@ public static void AddLanguageToPortal(int portalID, int languageID, bool clearC } } } - - private static void LocalizeDataControlField(DataControlField controlField, string resourceFile) - { - string localizedText; - - // Localize Header Text - if (!string.IsNullOrEmpty(controlField.HeaderText)) - { - localizedText = GetString(controlField.HeaderText + ".Header", resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - controlField.HeaderText = localizedText; - controlField.AccessibleHeaderText = controlField.HeaderText; - } - } - - if (controlField is TemplateField) - { - // do nothing - } - else if (controlField is ButtonField) - { - var button = (ButtonField)controlField; - localizedText = GetString(button.Text, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - button.Text = localizedText; - } - } - else if (controlField is CheckBoxField) - { - var checkbox = (CheckBoxField)controlField; - localizedText = GetString(checkbox.Text, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - checkbox.Text = localizedText; - } - } - else if (controlField is CommandField) - { - var commands = (CommandField)controlField; - localizedText = GetString(commands.CancelText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.CancelText = localizedText; - } - - localizedText = GetString(commands.DeleteText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.DeleteText = localizedText; - } - - localizedText = GetString(commands.EditText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.EditText = localizedText; - } - - localizedText = GetString(commands.InsertText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.InsertText = localizedText; - } - - localizedText = GetString(commands.NewText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.NewText = localizedText; - } - - localizedText = GetString(commands.SelectText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.SelectText = localizedText; - } - - localizedText = GetString(commands.UpdateText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - commands.UpdateText = localizedText; - } - } - else if (controlField is HyperLinkField) - { - var link = (HyperLinkField)controlField; - localizedText = GetString(link.Text, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - link.Text = localizedText; - } - } - else if (controlField is ImageField) - { - var image = (ImageField)controlField; - localizedText = GetString(image.AlternateText, resourceFile); - if (!string.IsNullOrEmpty(localizedText)) - { - image.AlternateText = localizedText; - } - } - } public static void AddLanguagesToPortal(int portalID) { @@ -446,7 +301,7 @@ public static void AddLanguagesToPortal(int portalID) // Add Portal/Language to PortalLanguages AddLanguageToPortal(portalID, language.LanguageId, false); } - + DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portalID)); } @@ -460,100 +315,6 @@ public static void AddLanguageToPortals(int languageID) DataCache.RemoveCache(string.Format(DataCache.LocalesCacheKey, portal.PortalID)); } } - - private static void AddLanguageHttpAlias(int portalId, Locale locale) - { - if (Config.GetFriendlyUrlProvider() == "advanced") - { - // create new HTTPAlias for language - var portalInfo = PortalController.Instance.GetPortal(portalId); - PortalAliasInfo currentAlias = null; - string httpAlias = null; - - var portalAliasses = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); - var portalAliasInfos = portalAliasses as IList ?? portalAliasses.ToList(); - if (portalAliasses != null && portalAliasInfos.Any()) - { - currentAlias = currentAlias - ?? portalAliasInfos - .Where(a => string.IsNullOrWhiteSpace(a.CultureCode)) - .OrderByDescending(a => a.IsPrimary) - .FirstOrDefault() - ?? portalAliasInfos.First(); - - httpAlias = currentAlias.HTTPAlias; - } - - if (currentAlias != null && !string.IsNullOrEmpty(httpAlias) && portalInfo != null) - { - if (!string.IsNullOrEmpty(currentAlias.CultureCode)) - { - // the portal alias is culture specific - if (currentAlias.CultureCode == portalInfo.CultureCode) - { - // remove the culture from the alias - httpAlias = httpAlias.Substring(0, httpAlias.LastIndexOf("/", StringComparison.Ordinal)); - } - } - - 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()), - }; - - PortalAliasController.Instance.AddPortalAlias(newAlias); - } - } - } - } - - private static string GetValidLanguageURL(int portalId, string httpAlias, string locale) - { - string alias; - - bool isValid; - int counter = 0; - do - { - string modifiedLocale = locale; - if (counter > 0) - { - modifiedLocale += counter.ToString(CultureInfo.InvariantCulture); - } - - alias = string.Format("{0}/{1}", httpAlias, modifiedLocale); - - var tab = TabController.Instance.GetTabByName(modifiedLocale, portalId); - isValid = tab == null; - - if (isValid) - { - var user = UserController.GetUserByVanityUrl(portalId, modifiedLocale); - isValid = user == null; - } - - if (isValid) - { - var aliases = PortalAliasController.Instance.GetPortalAliases(); - isValid = !aliases.Contains(alias); - } - - if (isValid) - { - isValid = PortalAliasController.ValidateAlias(alias, false); - } - - counter++; - } - while (!isValid); - - return alias; - } public static void AddTranslatorRole(int portalID, Locale language) { @@ -701,7 +462,7 @@ public static TimeZoneInfo ConvertLegacyTimeZoneOffsetToTimeZoneInfo(int timeZon break; } } - + break; } @@ -722,7 +483,7 @@ public static void DeleteLanguage(Locale language, bool isInstalling) EventLogController.Instance.AddLog(language, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGE_DELETED); DataCache.ClearHostCache(true); } - + public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes, string fallback) { return TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(cultureCodes, fallback); @@ -731,15 +492,15 @@ public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable public static string BestCultureCodeBasedOnBrowserLanguages(IEnumerable cultureCodes) { return TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(cultureCodes); - } - + } + public static string GetExceptionMessage(string key, string defaultValue) { if (HttpContext.Current == null) { return defaultValue; } - + return GetString(key, ExceptionsResourceFile); } @@ -749,10 +510,10 @@ public static string GetExceptionMessage(string key, string defaultValue, params { return string.Format(defaultValue, @params); } - + var content = GetString(key, ExceptionsResourceFile); return string.Format(string.IsNullOrEmpty(content) ? defaultValue : GetString(key, ExceptionsResourceFile), @params); - } + } public static string GetLanguageDisplayMode(int portalId) { @@ -762,7 +523,7 @@ public static string GetLanguageDisplayMode(int portalId) { viewType = "NATIVE"; } - + return viewType; } @@ -800,30 +561,8 @@ 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: @@ -842,42 +581,42 @@ public static CultureInfo GetPageLocale(PortalSettings portalSettings) CultureInfo pageCulture = null; // 1. querystring - if (portalSettings != null) - { - pageCulture = GetCultureFromQs(portalSettings); - } - - // 2. cookie - if (portalSettings != null && pageCulture == null) - { - pageCulture = GetCultureFromCookie(portalSettings); - } - - // 3. user preference - if (portalSettings != null && pageCulture == null) - { - pageCulture = GetCultureFromProfile(portalSettings); - } - - // 4. browser - if (portalSettings != null && pageCulture == null) - { - pageCulture = GetCultureFromBrowser(portalSettings); - } - - // 5. portal default - if (portalSettings != null && pageCulture == null) - { - pageCulture = GetCultureFromPortal(portalSettings); - } - - // 6. system default - if (pageCulture == null) - { - pageCulture = new CultureInfo(SystemLocale); - } - - // finally set the cookie + if (portalSettings != null) + { + pageCulture = GetCultureFromQs(portalSettings); + } + + // 2. cookie + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromCookie(portalSettings); + } + + // 3. user preference + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromProfile(portalSettings); + } + + // 4. browser + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromBrowser(portalSettings); + } + + // 5. portal default + if (portalSettings != null && pageCulture == null) + { + pageCulture = GetCultureFromPortal(portalSettings); + } + + // 6. system default + if (pageCulture == null) + { + pageCulture = new CultureInfo(SystemLocale); + } + + // finally set the cookie SetLanguage(pageCulture.Name); return pageCulture; } @@ -889,33 +628,33 @@ public static CultureInfo GetPageLocale(PortalSettings portalSettings) /// 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; - } - + 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; - } + 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")) @@ -927,7 +666,7 @@ public static string GetResourceFileName(string resourceFileName, string languag resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + language + ".resx"; } } - + if (mode == "Host") { resourceFileName = resourceFileName.Substring(0, resourceFileName.Length - 5) + "." + "Host.resx"; @@ -936,163 +675,15 @@ public static string GetResourceFileName(string resourceFileName, string languag { 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. - /// - /// Current PortalSettings. - /// A valid CultureInfo if any is found. - private static CultureInfo GetCultureFromQs(PortalSettings portalSettings) - { - if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) - { - return null; - } - - string language = HttpContext.Current.Request["language"]; - CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); - return culture; - } - - /// - /// Tries to get a valid language from the cookie. - /// - /// Current PortalSettings. - /// A valid CultureInfo if any is found. - private static CultureInfo GetCultureFromCookie(PortalSettings portalSettings) - { - CultureInfo culture; - if (HttpContext.Current == null || HttpContext.Current.Request.Cookies["language"] == null) - { - return null; - } - - string language = HttpContext.Current.Request.Cookies["language"].Value; - culture = GetCultureFromString(portalSettings.PortalId, language); - return culture; - } - - /// - /// Tries to get a valid language from the user profile. - /// - /// Current PortalSettings. - /// A valid CultureInfo if any is found. - private static CultureInfo GetCultureFromProfile(PortalSettings portalSettings) - { - UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); - - if (HttpContext.Current == null || !HttpContext.Current.Request.IsAuthenticated || objUserInfo.UserID == -1) - { - return null; - } - - string language = objUserInfo.Profile.PreferredLocale; - CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); - return culture; - } - - /// - /// Tries to get a valid language from the browser preferences if the portal has the setting - /// to use browser languages enabled. - /// - /// Current PortalSettings. - /// A valid CultureInfo if any is found. - private static CultureInfo GetCultureFromBrowser(PortalSettings portalSettings) - { - if (!portalSettings.EnableBrowserLanguage) - { - return null; - } - else - { - return GetBrowserCulture(portalSettings.PortalId); - } } - /// - /// Tries to get a valid language from the portal default preferences. - /// - /// Current PortalSettings. - /// A valid CultureInfo if any is found. - private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) - { - CultureInfo culture = null; - if (!string.IsNullOrEmpty(portalSettings.DefaultLanguage)) - { - // As the portal default language can never be disabled, we know this language is available and enabled - culture = new CultureInfo(portalSettings.DefaultLanguage); - } - else - { - // Get the first enabled locale on the portal - Dictionary enabledLocales = new Dictionary(); - if (portalSettings.PortalId > Null.NullInteger) - { - enabledLocales = LocaleController.Instance.GetLocales(portalSettings.PortalId); - } - - if (enabledLocales.Count > 0) - { - foreach (string localeCode in enabledLocales.Keys) - { - culture = new CultureInfo(localeCode); - break; - } - } - } - - return culture; - } - public static string GetString(string key, Control ctrl) { // We need to find the parent module @@ -1119,7 +710,7 @@ public static string GetString(string key, Control ctrl) // Get Resource File Root from Parents LocalResourceFile Property localizedText = GetString(key, moduleControl.LocalResourceFile); } - + return localizedText; } @@ -1225,8 +816,8 @@ public static string GetString(string key, string resourceFileRoot, PortalSettin public static string GetString(string key, string resourceFileRoot, PortalSettings portalSettings, string language, bool disableShowMissingKeys) { return LocalizationProvider.Instance.GetString(key, resourceFileRoot, language, portalSettings, disableShowMissingKeys); - } - + } + /// ----------------------------------------------------------------------------- /// /// GetStringUrl gets the localized string corresponding to the resourcekey. @@ -1244,8 +835,8 @@ public static string GetString(string key, string resourceFileRoot, PortalSettin public static string GetStringUrl(string key, string resourceFileRoot) { return GetString(key, resourceFileRoot, PortalController.Instance.GetCurrentPortalSettings(), null, true); - } - + } + /// /// this function will escape reserved character fields to their "safe" javascript equivalents. /// @@ -1271,8 +862,8 @@ public static string GetSafeJSString(string key, string resourceFileRoot) { var unsafeString = GetString(key, resourceFileRoot); return GetSafeJSString(unsafeString); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a SystemMessage. @@ -1478,8 +1069,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- - public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList custom, string customCaption, - int accessingUserID) + public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList custom, string customCaption, int accessingUserID) { return GetSystemMessage(strLanguage, portalSettings, messageName, userInfo, resourceFile, custom, null, customCaption, accessingUserID); } @@ -1504,8 +1094,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS /// will be used to find the replacement value in Custom parameter. /// /// ----------------------------------------------------------------------------- - public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList customArray, - IDictionary customDictionary, string customCaption, int accessingUserID) + public static string GetSystemMessage(string strLanguage, PortalSettings portalSettings, string messageName, UserInfo userInfo, string resourceFile, ArrayList customArray, IDictionary customDictionary, string customCaption, int accessingUserID) { try { @@ -1516,7 +1105,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS { customCaption = "Custom"; } - + var objTokenReplace = new TokenReplace(Scope.SystemMessages, strLanguage, portalSettings, userInfo); if ((accessingUserID != -1) && (userInfo != null)) { @@ -1526,7 +1115,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS UserController.Instance.GetUser(portalSettings.PortalId, accessingUserID); } } - + if (customArray != null) { strMessageValue = @@ -1538,7 +1127,7 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS objTokenReplace.ReplaceEnvironmentTokens(strMessageValue, customDictionary, customCaption); } } - + return strMessageValue; } catch (NullReferenceException ex) @@ -1546,8 +1135,8 @@ public static string GetSystemMessage(string strLanguage, PortalSettings portalS Logger.Error(ex); return messageName; } - } - + } + /// /// LoadCultureDropDownList loads a DropDownList with the list of supported cultures /// based on the languages defined in the supported locales file, for the current portal. @@ -1644,8 +1233,8 @@ public static IEnumerable LoadCultureInListItems(CultureDropDownTypes } return cultureListItems; - } - + } + /// ----------------------------------------------------------------------------- /// /// Localizes ModuleControl Titles. @@ -1682,7 +1271,7 @@ public static string LocalizeControlTitle(IModuleControl moduleControl) else { bool isAdminPage = false; - + // we should be checking that the tab path matches //Admin//pagename or //admin // in this way we should avoid partial matches (ie //Administrators if (PortalSettings.Current.ActiveTab.TabPath.StartsWith("//Admin//", StringComparison.CurrentCultureIgnoreCase) || @@ -1700,7 +1289,7 @@ public static string LocalizeControlTitle(IModuleControl moduleControl) controlTitle = localizedvalue; } } - + return controlTitle; } @@ -1726,7 +1315,7 @@ public static void LocalizeDataGrid(ref DataGrid grid, string resourceFile) col.HeaderText = localizedText; } } - + if (col is EditCommandColumn) { var editCol = (EditCommandColumn)col; @@ -1811,7 +1400,7 @@ public static void LocalizeGridView(ref GridView gridView, string resourceFile) /// Localizes: /// -DesktopTabs /// -BreadCrumbs. - /// + /// /// /// ----------------------------------------------------------------------------- public static string LocalizeRole(string role) @@ -1829,7 +1418,7 @@ public static string LocalizeRole(string role) localRole = role; break; } - + return localRole; } @@ -1899,7 +1488,7 @@ public static void RemoveLanguageFromPortal(int portalID, int languageID, bool i } DataProvider.Instance().DeletePortalLanguages(portalID, languageID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "portalID/languageID", portalID + "/" + languageID, PortalController.Instance.GetCurrentPortalSettings(), @@ -1910,11 +1499,6 @@ 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); @@ -1940,7 +1524,7 @@ public static void SaveLanguage(Locale locale) { SaveLanguage(locale, true); } - + public static void SaveLanguage(Locale locale, bool clearCache) { if (locale.LanguageId == Null.NullInteger) @@ -1953,11 +1537,11 @@ public static void SaveLanguage(Locale locale, bool clearCache) DataProvider.Instance().UpdateLanguage(locale.LanguageId, locale.Code, locale.Text, locale.Fallback, UserController.Instance.GetCurrentUserInfo().UserID); EventLogController.Instance.AddLog(locale, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, string.Empty, EventLogController.EventLogType.LANGUAGE_UPDATED); } - - if (clearCache) - { - DataCache.ClearHostCache(true); - } + + if (clearCache) + { + DataCache.ClearHostCache(true); + } } public static void SetLanguage(string value) @@ -2015,11 +1599,11 @@ public static void SetThreadCultures(CultureInfo cultureInfo, PortalSettings por throw new ArgumentNullException("cultureInfo"); } - if (cultureInfo.Name == "fa-IR") - { - cultureInfo = Persian.PersianController.GetPersianCultureInfo(); - } - + if (cultureInfo.Name == "fa-IR") + { + cultureInfo = Persian.PersianController.GetPersianCultureInfo(); + } + Thread.CurrentThread.CurrentCulture = cultureInfo; if (portalSettings != null && portalSettings.ContentLocalizationEnabled && @@ -2045,37 +1629,408 @@ public static int GetCultureLanguageID(string cultureCode) { var locale = LocaleController.Instance.GetLocale(cultureCode); return locale != null ? locale.LanguageId : Null.NullInteger; - } + } + + 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; + } /// - /// When portal allows users to select their preferred UI language, this method - /// will return the user ui preferred language if defined. Otherwise defaults - /// to the current 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". /// - /// Current culture. - /// PortalSettings for the current request. - /// - private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSettings portalSettings) + /// 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 uiCulture = currentCulture; - try + CultureInfo culture = null; + if (!string.IsNullOrEmpty(language)) { - object oCulture = Personalization.Personalization.GetProfile("Usability", "UICulture"); - if (oCulture != null) + if (LocaleController.Instance.IsEnabled(ref language, portalId)) { - CultureInfo ci = GetCultureFromString(portalSettings.PortalId, oCulture.ToString()); - if (ci != null) - { - uiCulture = ci; - } + 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; + } + } } } - catch - { - // UserCulture seems not valid anymore, update to current culture + + return culture; + } + + private static void LocalizeDataControlField(DataControlField controlField, string resourceFile) + { + string localizedText; + + // Localize Header Text + if (!string.IsNullOrEmpty(controlField.HeaderText)) + { + localizedText = GetString(controlField.HeaderText + ".Header", resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + controlField.HeaderText = localizedText; + controlField.AccessibleHeaderText = controlField.HeaderText; + } + } + + if (controlField is TemplateField) + { + // do nothing + } + else if (controlField is ButtonField) + { + var button = (ButtonField)controlField; + localizedText = GetString(button.Text, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + button.Text = localizedText; + } + } + else if (controlField is CheckBoxField) + { + var checkbox = (CheckBoxField)controlField; + localizedText = GetString(checkbox.Text, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + checkbox.Text = localizedText; + } + } + else if (controlField is CommandField) + { + var commands = (CommandField)controlField; + localizedText = GetString(commands.CancelText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.CancelText = localizedText; + } + + localizedText = GetString(commands.DeleteText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.DeleteText = localizedText; + } + + localizedText = GetString(commands.EditText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.EditText = localizedText; + } + + localizedText = GetString(commands.InsertText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.InsertText = localizedText; + } + + localizedText = GetString(commands.NewText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.NewText = localizedText; + } + + localizedText = GetString(commands.SelectText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.SelectText = localizedText; + } + + localizedText = GetString(commands.UpdateText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + commands.UpdateText = localizedText; + } + } + else if (controlField is HyperLinkField) + { + var link = (HyperLinkField)controlField; + localizedText = GetString(link.Text, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + link.Text = localizedText; + } + } + else if (controlField is ImageField) + { + var image = (ImageField)controlField; + localizedText = GetString(image.AlternateText, resourceFile); + if (!string.IsNullOrEmpty(localizedText)) + { + image.AlternateText = localizedText; + } + } + } + + private static void AddLanguageHttpAlias(int portalId, Locale locale) + { + if (Config.GetFriendlyUrlProvider() == "advanced") + { + // create new HTTPAlias for language + var portalInfo = PortalController.Instance.GetPortal(portalId); + PortalAliasInfo currentAlias = null; + string httpAlias = null; + + var portalAliasses = PortalAliasController.Instance.GetPortalAliasesByPortalId(portalId); + var portalAliasInfos = portalAliasses as IList ?? portalAliasses.ToList(); + if (portalAliasses != null && portalAliasInfos.Any()) + { + currentAlias = currentAlias + ?? portalAliasInfos + .Where(a => string.IsNullOrWhiteSpace(a.CultureCode)) + .OrderByDescending(a => a.IsPrimary) + .FirstOrDefault() + ?? portalAliasInfos.First(); + + httpAlias = currentAlias.HTTPAlias; + } + + if (currentAlias != null && !string.IsNullOrEmpty(httpAlias) && portalInfo != null) + { + if (!string.IsNullOrEmpty(currentAlias.CultureCode)) + { + // the portal alias is culture specific + if (currentAlias.CultureCode == portalInfo.CultureCode) + { + // remove the culture from the alias + httpAlias = httpAlias.Substring(0, httpAlias.LastIndexOf("/", StringComparison.Ordinal)); + } + } + + 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()), + }; + + PortalAliasController.Instance.AddPortalAlias(newAlias); + } + } + } + } + + private static string GetValidLanguageURL(int portalId, string httpAlias, string locale) + { + string alias; + + bool isValid; + int counter = 0; + do + { + string modifiedLocale = locale; + if (counter > 0) + { + modifiedLocale += counter.ToString(CultureInfo.InvariantCulture); + } + + alias = string.Format("{0}/{1}", httpAlias, modifiedLocale); + + var tab = TabController.Instance.GetTabByName(modifiedLocale, portalId); + isValid = tab == null; + + if (isValid) + { + var user = UserController.GetUserByVanityUrl(portalId, modifiedLocale); + isValid = user == null; + } + + if (isValid) + { + var aliases = PortalAliasController.Instance.GetPortalAliases(); + isValid = !aliases.Contains(alias); + } + + if (isValid) + { + isValid = PortalAliasController.ValidateAlias(alias, false); + } + + counter++; + } + while (!isValid); + + return alias; + } + + /// + /// Tries to get a valid language from the querystring. + /// + /// Current PortalSettings. + /// A valid CultureInfo if any is found. + private static CultureInfo GetCultureFromQs(PortalSettings portalSettings) + { + if (HttpContext.Current == null || HttpContext.Current.Request["language"] == null) + { + return null; + } + + string language = HttpContext.Current.Request["language"]; + CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); + return culture; + } + + /// + /// Tries to get a valid language from the cookie. + /// + /// Current PortalSettings. + /// A valid CultureInfo if any is found. + private static CultureInfo GetCultureFromCookie(PortalSettings portalSettings) + { + CultureInfo culture; + if (HttpContext.Current == null || HttpContext.Current.Request.Cookies["language"] == null) + { + return null; + } + + string language = HttpContext.Current.Request.Cookies["language"].Value; + culture = GetCultureFromString(portalSettings.PortalId, language); + return culture; + } + + /// + /// Tries to get a valid language from the user profile. + /// + /// Current PortalSettings. + /// A valid CultureInfo if any is found. + private static CultureInfo GetCultureFromProfile(PortalSettings portalSettings) + { + UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); + + if (HttpContext.Current == null || !HttpContext.Current.Request.IsAuthenticated || objUserInfo.UserID == -1) + { + return null; + } + + string language = objUserInfo.Profile.PreferredLocale; + CultureInfo culture = GetCultureFromString(portalSettings.PortalId, language); + return culture; + } + + /// + /// Tries to get a valid language from the browser preferences if the portal has the setting + /// to use browser languages enabled. + /// + /// Current PortalSettings. + /// A valid CultureInfo if any is found. + private static CultureInfo GetCultureFromBrowser(PortalSettings portalSettings) + { + if (!portalSettings.EnableBrowserLanguage) + { + return null; + } + else + { + return GetBrowserCulture(portalSettings.PortalId); + } + } + + /// + /// Tries to get a valid language from the portal default preferences. + /// + /// Current PortalSettings. + /// A valid CultureInfo if any is found. + private static CultureInfo GetCultureFromPortal(PortalSettings portalSettings) + { + CultureInfo culture = null; + if (!string.IsNullOrEmpty(portalSettings.DefaultLanguage)) + { + // As the portal default language can never be disabled, we know this language is available and enabled + culture = new CultureInfo(portalSettings.DefaultLanguage); + } + else + { + // Get the first enabled locale on the portal + Dictionary enabledLocales = new Dictionary(); + if (portalSettings.PortalId > Null.NullInteger) + { + enabledLocales = LocaleController.Instance.GetLocales(portalSettings.PortalId); + } + + if (enabledLocales.Count > 0) + { + foreach (string localeCode in enabledLocales.Keys) + { + culture = new CultureInfo(localeCode); + break; + } + } + } + + return culture; + } + + private static IList GetPortalLocalizations(int portalID) + { + return CBO.FillCollection(DataProvider.Instance().GetPortalLocalizations(portalID)); + } + + /// + /// When portal allows users to select their preferred UI language, this method + /// will return the user ui preferred language if defined. Otherwise defaults + /// to the current culture. + /// + /// Current culture. + /// PortalSettings for the current request. + /// + private static CultureInfo GetUserUICulture(CultureInfo currentCulture, PortalSettings portalSettings) + { + CultureInfo uiCulture = currentCulture; + try + { + object oCulture = Personalization.Personalization.GetProfile("Usability", "UICulture"); + if (oCulture != null) + { + CultureInfo ci = GetCultureFromString(portalSettings.PortalId, oCulture.ToString()); + if (ci != null) + { + uiCulture = ci; + } + } + } + catch + { + // UserCulture seems not valid anymore, update to current culture Personalization.Personalization.SetProfile("Usability", "UICulture", currentCulture.Name); } - + return uiCulture; } } diff --git a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs index cdd3e6b6809..87b6b10ec89 100644 --- a/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs +++ b/DNN Platform/Library/Services/Localization/LocalizationExpressionBuilder.cs @@ -40,7 +40,7 @@ public static object GetLocalizedResource(string key, Type targetType, string pr localResourceFile = virtualPath.Replace(filename, Localization.LocalResourceDirectory + "/" + filename); } } - + string value = Localization.GetString(key, localResourceFile); if (value == null) @@ -61,7 +61,7 @@ public static object GetLocalizedResource(string key, Type targetType, string pr { throw new InvalidOperationException(string.Format("Localized value '{0}' cannot be converted to type {1}.", key, propDesc.PropertyType)); } - + return propDesc.Converter.ConvertFrom(value); } } diff --git a/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs b/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs index deb676528c8..fd4b39ba688 100644 --- a/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs +++ b/DNN Platform/Library/Services/Localization/Persian/PersianCalendar.cs @@ -10,71 +10,71 @@ public class PersianCalendar : System.Globalization.PersianCalendar { public override int GetYear(DateTime time) { - try - { - return base.GetYear(time); - } + try + { + return base.GetYear(time); + } catch { // ignore } - + return time.Year; } public override int GetMonth(DateTime time) { - try - { - return base.GetMonth(time); - } + try + { + return base.GetMonth(time); + } catch { // ignore } - + return time.Month; } public override int GetDayOfMonth(DateTime time) { - try - { - return base.GetDayOfMonth(time); - } + try + { + return base.GetDayOfMonth(time); + } catch { // ignore } - + return time.Day; } public override int GetDayOfYear(DateTime time) { - try - { - return base.GetDayOfYear(time); - } + try + { + return base.GetDayOfYear(time); + } catch { // ignore } - + return time.DayOfYear; } public override DayOfWeek GetDayOfWeek(DateTime time) { - try - { - return base.GetDayOfWeek(time); - } + try + { + return base.GetDayOfWeek(time); + } catch { // ignore } - + return time.DayOfWeek; } } diff --git a/DNN Platform/Library/Services/Localization/Persian/PersianController.cs b/DNN Platform/Library/Services/Localization/Persian/PersianController.cs index 4785b9b7a0a..1458cf4259e 100644 --- a/DNN Platform/Library/Services/Localization/Persian/PersianController.cs +++ b/DNN Platform/Library/Services/Localization/Persian/PersianController.cs @@ -20,17 +20,17 @@ public static CultureInfo GetPersianCultureInfo() var cal = new PersianCalendar(); FieldInfo fieldInfo = persianCultureInfo.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance); - if (fieldInfo != null) - { - fieldInfo.SetValue(persianCultureInfo, cal); - } - + if (fieldInfo != null) + { + fieldInfo.SetValue(persianCultureInfo, cal); + } + FieldInfo info = persianCultureInfo.DateTimeFormat.GetType().GetField("calendar", BindingFlags.NonPublic | BindingFlags.Instance); - if (info != null) - { - info.SetValue(persianCultureInfo.DateTimeFormat, cal); - } - + if (info != null) + { + info.SetValue(persianCultureInfo.DateTimeFormat, cal); + } + return persianCultureInfo; } diff --git a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs index 9430cd5887f..356d84887e8 100644 --- a/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/DBLoggingProvider.cs @@ -24,14 +24,14 @@ public class DBLoggingProvider : LoggingProvider { public const string LogTypeCacheKey = "LogTypes"; public const string LogTypeInfoCacheKey = "GetLogTypeConfigInfo"; - + public const string LogTypeInfoByKeyCacheKey = "GetLogTypeConfigInfoByKey"; + 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 LogTypeInfoByKeyCacheKey = "GetLogTypeConfigInfoByKey"; public override void AddLog(LogInfo logInfo) { @@ -43,7 +43,7 @@ public override void AddLog(LogInfo logInfo) { return; } - + logInfo.LogConfigID = logTypeConfigInfo.ID; var logQueueItem = new LogQueueItem { LogInfo = logInfo, LogTypeConfigInfo = logTypeConfigInfo }; SchedulingProvider scheduler = SchedulingProvider.Instance(); @@ -65,209 +65,6 @@ public override void AddLogType(string logTypeKey, string logTypeFriendlyName, s DataCache.RemoveCache(LogTypeCacheKey); } - private static Hashtable FillLogTypeConfigInfoByKey(ArrayList arr) - { - var ht = new Hashtable(); - int i; - for (i = 0; i <= arr.Count - 1; i++) - { - var logTypeConfigInfo = (LogTypeConfigInfo)arr[i]; - if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypeKey)) - { - logTypeConfigInfo.LogTypeKey = "*"; - } - - if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypePortalID)) - { - logTypeConfigInfo.LogTypePortalID = "*"; - } - - ht.Add(logTypeConfigInfo.LogTypeKey + "|" + logTypeConfigInfo.LogTypePortalID, logTypeConfigInfo); - } - - DataCache.SetCache(LogTypeInfoByKeyCacheKey, ht); - return ht; - } - - private static LogInfo FillLogInfo(IDataReader dr) - { - var obj = new LogInfo(); - try - { - obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"]); - obj.LogGUID = Convert.ToString(dr["LogGUID"]); - obj.LogPortalID = Convert.ToInt32(Null.SetNull(dr["LogPortalID"], obj.LogPortalID)); - obj.LogPortalName = Convert.ToString(Null.SetNull(dr["LogPortalName"], obj.LogPortalName)); - obj.LogServerName = Convert.ToString(Null.SetNull(dr["LogServerName"], obj.LogServerName)); - obj.LogUserID = Convert.ToInt32(Null.SetNull(dr["LogUserID"], obj.LogUserID)); - obj.LogEventID = Convert.ToInt32(Null.SetNull(dr["LogEventID"], obj.LogEventID)); - obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"]); - obj.LogUserName = Convert.ToString(dr["LogUserName"]); - obj.LogConfigID = Convert.ToString(dr["LogConfigID"]); - obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"])); - obj.Exception.AssemblyVersion = Convert.ToString(Null.SetNull(dr["AssemblyVersion"], obj.Exception.AssemblyVersion)); - obj.Exception.PortalId = Convert.ToInt32(Null.SetNull(dr["PortalId"], obj.Exception.PortalId)); - obj.Exception.UserId = Convert.ToInt32(Null.SetNull(dr["UserId"], obj.Exception.UserId)); - obj.Exception.TabId = Convert.ToInt32(Null.SetNull(dr["TabId"], obj.Exception.TabId)); - obj.Exception.RawUrl = Convert.ToString(Null.SetNull(dr["RawUrl"], obj.Exception.RawUrl)); - obj.Exception.Referrer = Convert.ToString(Null.SetNull(dr["Referrer"], obj.Exception.Referrer)); - obj.Exception.UserAgent = Convert.ToString(Null.SetNull(dr["UserAgent"], obj.Exception.UserAgent)); - obj.Exception.ExceptionHash = Convert.ToString(Null.SetNull(dr["ExceptionHash"], obj.Exception.ExceptionHash)); - obj.Exception.Message = Convert.ToString(Null.SetNull(dr["Message"], obj.Exception.Message)); - obj.Exception.StackTrace = Convert.ToString(Null.SetNull(dr["StackTrace"], obj.Exception.StackTrace)); - obj.Exception.InnerMessage = Convert.ToString(Null.SetNull(dr["InnerMessage"], obj.Exception.InnerMessage)); - obj.Exception.InnerStackTrace = Convert.ToString(Null.SetNull(dr["InnerStackTrace"], obj.Exception.InnerStackTrace)); - obj.Exception.Source = Convert.ToString(Null.SetNull(dr["Source"], obj.Exception.Source)); - /* DNN-6218 + DNN-6242: DB logging provider throws errors - // the view "vw_EventLog" doesn't have these fields or any table in the database - obj.Exception.FileName = Convert.ToString(Null.SetNull(dr["FileName"], obj.Exception.FileName)); - obj.Exception.FileLineNumber = Convert.ToInt32(Null.SetNull(dr["FileLineNumber"], obj.Exception.FileLineNumber)); - obj.Exception.FileColumnNumber = Convert.ToInt32(Null.SetNull(dr["FileColumnNumber"], obj.Exception.FileColumnNumber)); - obj.Exception.Method = Convert.ToString(Null.SetNull(dr["Method"], obj.Exception.Method)); - */ - } - catch (Exception exc) - { - Logger.Error(exc); - } - - return obj; - } - - private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) - { - try - { - while (dr.Read()) - { - LogInfo logInfo = FillLogInfo(dr); - logs.Add(logInfo); - } - - dr.NextResult(); - while (dr.Read()) - { - totalRecords = Convert.ToInt32(dr["TotalRecords"]); - } - } - finally - { - CBO.CloseDataReader(dr, true); - } - } - - 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) - { - if (HttpContext.Current.IsCustomErrorEnabled) - { - HttpContext.Current.AddError(exc); - } - else - { - HttpResponse response = HttpContext.Current.Response; - response.StatusCode = 500; - HtmlUtils.WriteHeader(response, header); - - if (logTypeConfigInfo != null) - { - HtmlUtils.WriteError(response, logTypeConfigInfo.LogFileNameWithPath, message); - } - - HtmlUtils.WriteFooter(response); - response.End(); - } - } - } - - private static void WriteLog(LogQueueItem logQueueItem) - { - LogTypeConfigInfo logTypeConfigInfo = null; - try - { - logTypeConfigInfo = logQueueItem.LogTypeConfigInfo; - if (logTypeConfigInfo != null) - { - LogInfo objLogInfo = logQueueItem.LogInfo; - string logProperties = objLogInfo.LogProperties.Serialize(); - DataProvider.Instance().AddLog( - objLogInfo.LogGUID, - objLogInfo.LogTypeKey, - objLogInfo.LogUserID, - objLogInfo.LogUserName, - objLogInfo.LogPortalID, - objLogInfo.LogPortalName, - objLogInfo.LogCreateDate, - objLogInfo.LogServerName, - logProperties, - Convert.ToInt32(objLogInfo.LogConfigID), - objLogInfo.Exception, - logTypeConfigInfo.EmailNotificationIsActive); - if (logTypeConfigInfo.EmailNotificationIsActive) - { - if (LockNotif.TryEnterWriteLock(ReaderLockTimeout)) - { - try - { - if (logTypeConfigInfo.NotificationThreshold == 0) - { - string str = logQueueItem.LogInfo.Serialize(); - Mail.Mail.SendEmail(logTypeConfigInfo.MailFromAddress, logTypeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(str))); - } - } - finally - { - LockNotif.ExitWriteLock(); - } - } - } - } - } - catch (SqlException exc) - { - Logger.Error(exc); - WriteError(logTypeConfigInfo, exc, "SQL Exception", SqlUtils.TranslateSQLException(exc)); - } - catch (Exception exc) - { - Logger.Error(exc); - WriteError(logTypeConfigInfo, exc, "Unhandled Error", exc.Message); - } - } - 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) { @@ -279,23 +76,23 @@ public override void AddLogTypeConfigInfo(string id, bool loggingIsActive, strin { intThreshold = Convert.ToInt32(threshold); } - + if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { intThresholdTime = Convert.ToInt32(thresholdTime); } - + if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { intThresholdTimeType = Convert.ToInt32(thresholdTimeType); } - + if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { intKeepMostRecent = Convert.ToInt32(keepMostRecent); } - - DataProvider.Instance().AddLogTypeConfigInfo( + + DataProvider.Instance().AddLogTypeConfigInfo( loggingIsActive, logTypeKey, logTypePortalID, @@ -365,7 +162,7 @@ public override ArrayList GetLogTypeConfigInfo() } } } - + return list; } @@ -376,7 +173,7 @@ public override LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) public override ArrayList GetLogTypeInfo() { - return CBO.GetCachedObject( + return CBO.GetCachedObject( new CacheItemArgs(LogTypeCacheKey, 20, CacheItemPriority.Normal), c => CBO.FillCollection(DataProvider.Instance().GetLogTypeInfo(), typeof(LogTypeInfo))); } @@ -397,18 +194,18 @@ public override object GetSingleLog(LogInfo logInfo, ReturnType returnType) { CBO.CloseDataReader(dr, true); } - + if (returnType == ReturnType.LogInfoObjects) { return log; } - + var xmlDoc = new XmlDocument { XmlResolver = null }; if (log != null) { xmlDoc.LoadXml(log.Serialize()); } - + return xmlDoc.DocumentElement; } @@ -419,29 +216,29 @@ public override bool LoggingIsEnabled(string logType, int portalID) { configPortalID = "*"; } - + LogTypeConfigInfo configInfo = this.GetLogTypeConfigInfoByKey(logType, configPortalID); if (configInfo == null) { return false; } - + return configInfo.LoggingIsActive; } public override void PurgeLogBuffer() { - if (!LockQueueLog.TryEnterWriteLock(WriterLockTimeout)) - { - return; - } - + if (!LockQueueLog.TryEnterWriteLock(WriterLockTimeout)) + { + return; + } + try { for (int i = LogQueue.Count - 1; i >= 0; i += -1) { LogQueueItem logQueueItem = LogQueue[i]; - + // in case the log was removed // by another thread simultaneously if (logQueueItem != null) @@ -455,7 +252,7 @@ public override void PurgeLogBuffer() { LockQueueLog.ExitWriteLock(); } - + DataProvider.Instance().PurgeLog(); } @@ -478,7 +275,7 @@ public override void SendLogNotifications() { CBO.CloseDataReader(dr, true); } - + Mail.Mail.SendEmail(typeConfigInfo.MailFromAddress, typeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(log))); DataProvider.Instance().UpdateEventLogPendingNotif(Convert.ToInt32(typeConfigInfo.ID)); } @@ -521,23 +318,23 @@ public override void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, st { intThreshold = Convert.ToInt32(threshold); } - + if (Globals.NumberMatchRegex.IsMatch(thresholdTime)) { intThresholdTime = Convert.ToInt32(thresholdTime); } - + if (Globals.NumberMatchRegex.IsMatch(thresholdTimeType)) { intThresholdTimeType = Convert.ToInt32(thresholdTimeType); } - + if (Globals.NumberMatchRegex.IsMatch(keepMostRecent)) { intKeepMostRecent = Convert.ToInt32(keepMostRecent); } - - DataProvider.Instance().UpdateLogTypeConfigInfo( + + DataProvider.Instance().UpdateLogTypeConfigInfo( id, loggingIsActive, logTypeKey, @@ -552,5 +349,208 @@ public override void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, st DataCache.RemoveCache(LogTypeInfoCacheKey); DataCache.RemoveCache(LogTypeInfoByKeyCacheKey); } + + private static Hashtable FillLogTypeConfigInfoByKey(ArrayList arr) + { + var ht = new Hashtable(); + int i; + for (i = 0; i <= arr.Count - 1; i++) + { + var logTypeConfigInfo = (LogTypeConfigInfo)arr[i]; + if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypeKey)) + { + logTypeConfigInfo.LogTypeKey = "*"; + } + + if (string.IsNullOrEmpty(logTypeConfigInfo.LogTypePortalID)) + { + logTypeConfigInfo.LogTypePortalID = "*"; + } + + ht.Add(logTypeConfigInfo.LogTypeKey + "|" + logTypeConfigInfo.LogTypePortalID, logTypeConfigInfo); + } + + DataCache.SetCache(LogTypeInfoByKeyCacheKey, ht); + return ht; + } + + private static LogInfo FillLogInfo(IDataReader dr) + { + var obj = new LogInfo(); + try + { + obj.LogCreateDate = Convert.ToDateTime(dr["LogCreateDate"]); + obj.LogGUID = Convert.ToString(dr["LogGUID"]); + obj.LogPortalID = Convert.ToInt32(Null.SetNull(dr["LogPortalID"], obj.LogPortalID)); + obj.LogPortalName = Convert.ToString(Null.SetNull(dr["LogPortalName"], obj.LogPortalName)); + obj.LogServerName = Convert.ToString(Null.SetNull(dr["LogServerName"], obj.LogServerName)); + obj.LogUserID = Convert.ToInt32(Null.SetNull(dr["LogUserID"], obj.LogUserID)); + obj.LogEventID = Convert.ToInt32(Null.SetNull(dr["LogEventID"], obj.LogEventID)); + obj.LogTypeKey = Convert.ToString(dr["LogTypeKey"]); + obj.LogUserName = Convert.ToString(dr["LogUserName"]); + obj.LogConfigID = Convert.ToString(dr["LogConfigID"]); + obj.LogProperties.Deserialize(Convert.ToString(dr["LogProperties"])); + obj.Exception.AssemblyVersion = Convert.ToString(Null.SetNull(dr["AssemblyVersion"], obj.Exception.AssemblyVersion)); + obj.Exception.PortalId = Convert.ToInt32(Null.SetNull(dr["PortalId"], obj.Exception.PortalId)); + obj.Exception.UserId = Convert.ToInt32(Null.SetNull(dr["UserId"], obj.Exception.UserId)); + obj.Exception.TabId = Convert.ToInt32(Null.SetNull(dr["TabId"], obj.Exception.TabId)); + obj.Exception.RawUrl = Convert.ToString(Null.SetNull(dr["RawUrl"], obj.Exception.RawUrl)); + obj.Exception.Referrer = Convert.ToString(Null.SetNull(dr["Referrer"], obj.Exception.Referrer)); + obj.Exception.UserAgent = Convert.ToString(Null.SetNull(dr["UserAgent"], obj.Exception.UserAgent)); + obj.Exception.ExceptionHash = Convert.ToString(Null.SetNull(dr["ExceptionHash"], obj.Exception.ExceptionHash)); + obj.Exception.Message = Convert.ToString(Null.SetNull(dr["Message"], obj.Exception.Message)); + obj.Exception.StackTrace = Convert.ToString(Null.SetNull(dr["StackTrace"], obj.Exception.StackTrace)); + obj.Exception.InnerMessage = Convert.ToString(Null.SetNull(dr["InnerMessage"], obj.Exception.InnerMessage)); + obj.Exception.InnerStackTrace = Convert.ToString(Null.SetNull(dr["InnerStackTrace"], obj.Exception.InnerStackTrace)); + obj.Exception.Source = Convert.ToString(Null.SetNull(dr["Source"], obj.Exception.Source)); + /* DNN-6218 + DNN-6242: DB logging provider throws errors + // the view "vw_EventLog" doesn't have these fields or any table in the database + obj.Exception.FileName = Convert.ToString(Null.SetNull(dr["FileName"], obj.Exception.FileName)); + obj.Exception.FileLineNumber = Convert.ToInt32(Null.SetNull(dr["FileLineNumber"], obj.Exception.FileLineNumber)); + obj.Exception.FileColumnNumber = Convert.ToInt32(Null.SetNull(dr["FileColumnNumber"], obj.Exception.FileColumnNumber)); + obj.Exception.Method = Convert.ToString(Null.SetNull(dr["Method"], obj.Exception.Method)); + */ + } + catch (Exception exc) + { + Logger.Error(exc); + } + + return obj; + } + + private static void FillLogs(IDataReader dr, IList logs, ref int totalRecords) + { + try + { + while (dr.Read()) + { + LogInfo logInfo = FillLogInfo(dr); + logs.Add(logInfo); + } + + dr.NextResult(); + while (dr.Read()) + { + totalRecords = Convert.ToInt32(dr["TotalRecords"]); + } + } + finally + { + CBO.CloseDataReader(dr, true); + } + } + + private static void WriteError(LogTypeConfigInfo logTypeConfigInfo, Exception exc, string header, string message) + { + if (HttpContext.Current != null) + { + if (HttpContext.Current.IsCustomErrorEnabled) + { + HttpContext.Current.AddError(exc); + } + else + { + HttpResponse response = HttpContext.Current.Response; + response.StatusCode = 500; + HtmlUtils.WriteHeader(response, header); + + if (logTypeConfigInfo != null) + { + HtmlUtils.WriteError(response, logTypeConfigInfo.LogFileNameWithPath, message); + } + + HtmlUtils.WriteFooter(response); + response.End(); + } + } + } + + private static void WriteLog(LogQueueItem logQueueItem) + { + LogTypeConfigInfo logTypeConfigInfo = null; + try + { + logTypeConfigInfo = logQueueItem.LogTypeConfigInfo; + if (logTypeConfigInfo != null) + { + LogInfo objLogInfo = logQueueItem.LogInfo; + string logProperties = objLogInfo.LogProperties.Serialize(); + DataProvider.Instance().AddLog( + objLogInfo.LogGUID, + objLogInfo.LogTypeKey, + objLogInfo.LogUserID, + objLogInfo.LogUserName, + objLogInfo.LogPortalID, + objLogInfo.LogPortalName, + objLogInfo.LogCreateDate, + objLogInfo.LogServerName, + logProperties, + Convert.ToInt32(objLogInfo.LogConfigID), + objLogInfo.Exception, + logTypeConfigInfo.EmailNotificationIsActive); + if (logTypeConfigInfo.EmailNotificationIsActive) + { + if (LockNotif.TryEnterWriteLock(ReaderLockTimeout)) + { + try + { + if (logTypeConfigInfo.NotificationThreshold == 0) + { + string str = logQueueItem.LogInfo.Serialize(); + Mail.Mail.SendEmail(logTypeConfigInfo.MailFromAddress, logTypeConfigInfo.MailToAddress, "Event Notification", string.Format("
    {0}
    ", HttpUtility.HtmlEncode(str))); + } + } + finally + { + LockNotif.ExitWriteLock(); + } + } + } + } + } + catch (SqlException exc) + { + Logger.Error(exc); + WriteError(logTypeConfigInfo, exc, "SQL Exception", SqlUtils.TranslateSQLException(exc)); + } + catch (Exception exc) + { + Logger.Error(exc); + WriteError(logTypeConfigInfo, exc, "Unhandled Error", exc.Message); + } + } + + 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; + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs index 47a80fcb294..8986c9154fb 100644 --- a/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/EventLogController.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Services.Log.EventLog using DotNetNuke.Services.FileSystem; public class EventLogController : ServiceLocator, IEventLogController - { + { public enum EventLogType { USER_CREATED, @@ -176,8 +176,8 @@ public enum EventLogType WEBSERVER_ENABLED, WEBSERVER_PINGFAILED, FOLDER_MOVED, - } - + } + 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() }; @@ -186,8 +186,8 @@ public static void AddSettingLog(EventLogType logTypeKey, string idFieldName, in log.LogProperties.Add(new LogDetailInfo("SettingValue", settingValue)); LogController.Instance.AddLog(log); - } - + } + public void AddLog(string propertyName, string propertyValue, EventLogType logType) { this.AddLog(propertyName, propertyValue, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, logType); @@ -197,11 +197,6 @@ 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) { @@ -214,19 +209,19 @@ 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; log.LogPortalName = portalSettings.PortalName; } - + LogController.Instance.AddLog(log); } @@ -344,8 +339,8 @@ public void AddLog(object businessObject, PortalSettings portalSettings, int use } LogController.Instance.AddLog(log); - } - + } + public void AddLog(LogInfo logInfo) { LogController.Instance.AddLog(logInfo); @@ -424,6 +419,11 @@ public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) public virtual void UpdateLogType(LogTypeInfo logType) { LogController.Instance.UpdateLogType(logType); - } + } + + protected override Func GetFactory() + { + return () => new EventLogController(); + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs index 009d0e90b48..d1b450d0047 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ExceptionLogController.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Services.Log.EventLog using DotNetNuke.Services.Exceptions; public class ExceptionLogController : LogController - { + { public enum ExceptionLogType { GENERAL_EXCEPTION, @@ -23,8 +23,8 @@ public enum ExceptionLogType SECURITY_EXCEPTION, SEARCH_INDEXER_EXCEPTION, DATA_EXCEPTION, - } - + } + public void AddLog(Exception objException) { this.AddLog(objException, ExceptionLogType.GENERAL_EXCEPTION); @@ -114,9 +114,9 @@ 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. + { + // 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 b81f07fba02..69622b0913d 100644 --- a/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs +++ b/DNN Platform/Library/Services/Log/EventLog/ILogViewer.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Services.Log.EventLog public interface ILogViewer { 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 d77df9efb0c..b27ab5ac671 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogController.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogController.cs @@ -26,7 +26,7 @@ public partial class LogController : ServiceLocator GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) + { + return LoggingProvider.Instance().GetLogs(portalID, logType, pageSize, pageIndex, ref totalRecords); + } + + public virtual ArrayList GetLogTypeConfigInfo() + { + return LoggingProvider.Instance().GetLogTypeConfigInfo(); + } + + public virtual LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) + { + return LoggingProvider.Instance().GetLogTypeConfigInfoByID(id); + } + + public virtual Dictionary GetLogTypeInfoDictionary() + { + return LoggingProvider.Instance().GetLogTypeInfo().Cast().ToDictionary(logTypeInfo => logTypeInfo.LogTypeKey); + } + + public virtual object GetSingleLog(LogInfo log, LoggingProvider.ReturnType returnType) + { + return LoggingProvider.Instance().GetSingleLog(log, returnType); + } + + public void PurgeLogBuffer() + { + LoggingProvider.Instance().PurgeLogBuffer(); + } + + public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) + { + LoggingProvider.Instance().UpdateLogTypeConfigInfo( + logTypeConfig.ID, + logTypeConfig.LoggingIsActive, + logTypeConfig.LogTypeKey, + logTypeConfig.LogTypePortalID, + logTypeConfig.KeepMostRecent, + logTypeConfig.LogFileName, + logTypeConfig.EmailNotificationIsActive, + Convert.ToString(logTypeConfig.NotificationThreshold), + Convert.ToString(logTypeConfig.NotificationThresholdTime), + Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), + logTypeConfig.MailFromAddress, + logTypeConfig.MailToAddress); + } + + public virtual void UpdateLogType(LogTypeInfo logType) + { + LoggingProvider.Instance().UpdateLogType(logType.LogTypeKey, logType.LogTypeFriendlyName, logType.LogTypeDescription, logType.LogTypeCSSClass, logType.LogTypeOwner); + } + protected override Func GetFactory() { return () => new LogController(); - } - + } + private static void AddLogToFile(LogInfo logInfo) { try @@ -187,7 +281,7 @@ private static void AddLogToFile(LogInfo logInfo) var f = Globals.HostMapPath + "\\Logs\\LogFailures.xml.resources"; WriteLog(f, logInfo.Serialize()); } - + // ReSharper disable EmptyGeneralCatchClause catch (Exception exc) // ReSharper restore EmptyGeneralCatchClause { @@ -222,7 +316,7 @@ private static void WriteToStreamWriter(FileStream fs, string message) { message = "" + message; } - + sw.WriteLine(message + ""); sw.Flush(); } @@ -231,11 +325,11 @@ private static void WriteToStreamWriter(FileStream fs, string message) private static void WriteLog(string filePath, string message) { FileStream fs = null; - if (!LockLog.TryEnterWriteLock(WriterLockTimeout)) - { - return; - } - + if (!LockLog.TryEnterWriteLock(WriterLockTimeout)) + { + return; + } + try { var intAttempts = 0; @@ -252,7 +346,7 @@ private static void WriteLog(string filePath, string message) Thread.Sleep(1); } } - + if (fs == null) { if (HttpContext.Current != null) @@ -296,103 +390,9 @@ private static void WriteLog(string filePath, string message) { fs.Close(); } - + LockLog.ExitWriteLock(); } - } - - public void AddLogType(LogTypeInfo logType) - { - LoggingProvider.Instance().AddLogType(logType.LogTypeKey, logType.LogTypeFriendlyName, logType.LogTypeDescription, logType.LogTypeCSSClass, logType.LogTypeOwner); - } - - public void AddLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) - { - LoggingProvider.Instance().AddLogTypeConfigInfo( - logTypeConfig.ID, - logTypeConfig.LoggingIsActive, - logTypeConfig.LogTypeKey, - logTypeConfig.LogTypePortalID, - logTypeConfig.KeepMostRecent, - logTypeConfig.LogFileName, - logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), - logTypeConfig.MailFromAddress, - logTypeConfig.MailToAddress); - } - - public void ClearLog() - { - LoggingProvider.Instance().ClearLog(); - } - - public void DeleteLog(LogInfo logInfo) - { - LoggingProvider.Instance().DeleteLog(logInfo); - } - - public virtual void DeleteLogType(LogTypeInfo logType) - { - LoggingProvider.Instance().DeleteLogType(logType.LogTypeKey); - } - - public virtual void DeleteLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) - { - LoggingProvider.Instance().DeleteLogTypeConfigInfo(logTypeConfig.ID); - } - - public virtual List GetLogs(int portalID, string logType, int pageSize, int pageIndex, ref int totalRecords) - { - return LoggingProvider.Instance().GetLogs(portalID, logType, pageSize, pageIndex, ref totalRecords); - } - - public virtual ArrayList GetLogTypeConfigInfo() - { - return LoggingProvider.Instance().GetLogTypeConfigInfo(); - } - - public virtual LogTypeConfigInfo GetLogTypeConfigInfoByID(string id) - { - return LoggingProvider.Instance().GetLogTypeConfigInfoByID(id); - } - - public virtual Dictionary GetLogTypeInfoDictionary() - { - return LoggingProvider.Instance().GetLogTypeInfo().Cast().ToDictionary(logTypeInfo => logTypeInfo.LogTypeKey); - } - - public virtual object GetSingleLog(LogInfo log, LoggingProvider.ReturnType returnType) - { - return LoggingProvider.Instance().GetSingleLog(log, returnType); } - - public void PurgeLogBuffer() - { - LoggingProvider.Instance().PurgeLogBuffer(); - } - - public virtual void UpdateLogTypeConfigInfo(LogTypeConfigInfo logTypeConfig) - { - LoggingProvider.Instance().UpdateLogTypeConfigInfo( - logTypeConfig.ID, - logTypeConfig.LoggingIsActive, - logTypeConfig.LogTypeKey, - logTypeConfig.LogTypePortalID, - logTypeConfig.KeepMostRecent, - logTypeConfig.LogFileName, - logTypeConfig.EmailNotificationIsActive, - Convert.ToString(logTypeConfig.NotificationThreshold), - Convert.ToString(logTypeConfig.NotificationThresholdTime), - Convert.ToString((int)logTypeConfig.NotificationThresholdTimeType), - logTypeConfig.MailFromAddress, - logTypeConfig.MailToAddress); - } - - public virtual void UpdateLogType(LogTypeInfo logType) - { - LoggingProvider.Instance().UpdateLogType(logType.LogTypeKey, logType.LogTypeFriendlyName, logType.LogTypeDescription, logType.LogTypeCSSClass, logType.LogTypeOwner); - } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs index 35c2d347a7f..fe6484133da 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogDetailInfo.cs @@ -13,7 +13,7 @@ public class LogDetailInfo private string _PropertyName; private string _PropertyValue; - public LogDetailInfo() + public LogDetailInfo() : this(string.Empty, string.Empty) { } @@ -30,7 +30,7 @@ public string PropertyName { return this._PropertyName; } - + set { this._PropertyName = value; @@ -43,7 +43,7 @@ public string PropertyValue { return this._PropertyValue; } - + set { this._PropertyValue = value; diff --git a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs index 8e7a814232f..9e2c46bf16a 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogInfo.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Services.Log.EventLog [Serializable] public class LogInfo - { + { public LogInfo() { this.LogGUID = Guid.NewGuid().ToString(); @@ -26,12 +26,12 @@ public LogInfo() this.Exception = new ExceptionInfo(); } - public LogInfo(string content) + public LogInfo(string content) : this() { this.Deserialize(content); - } - + } + public string LogGUID { get; set; } public string LogFileID { get; set; } @@ -60,7 +60,7 @@ public LogInfo(string content) public string LogConfigID { get; set; } - public ExceptionInfo Exception { get; set; } + public ExceptionInfo Exception { get; set; } public static bool IsSystemType(string PropName) { @@ -79,10 +79,10 @@ public static bool IsSystemType(string PropName) case "LogServerName": return true; } - + return false; } - + public void AddProperty(string PropertyName, string PropertyValue) { try @@ -91,17 +91,17 @@ public void AddProperty(string PropertyName, string PropertyValue) { PropertyValue = string.Empty; } - + if (PropertyName.Length > 50) { PropertyName = PropertyName.Substring(0, 50); } - + if (PropertyValue.Length > 500) { PropertyValue = "(TRUNCATED TO 500 CHARS): " + PropertyValue.Substring(0, 500); } - + var objLogDetailInfo = new LogDetailInfo(); objLogDetailInfo.PropertyName = PropertyName; objLogDetailInfo.PropertyValue = PropertyValue; @@ -121,7 +121,7 @@ public void Deserialize(string content) { this.ReadXml(reader); } - + reader.Close(); } } @@ -187,7 +187,7 @@ public void ReadXml(XmlReader reader) this.LogProperties.ReadXml(reader); } } - + // Check for Exception child node if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "Exception") { @@ -226,7 +226,7 @@ public override string ToString() { str.Append(this.Exception.ToString()); } - + return str.ToString(); } @@ -251,8 +251,8 @@ public void WriteXml(XmlWriter writer) { this.Exception.WriteXml(writer); } - + writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs index b5fdf567ba2..7db17c1854e 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogProperties.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Services.Log.EventLog using DotNetNuke.Common.Utilities; public class LogProperties : ArrayList - { + { public string Summary { get @@ -22,11 +22,11 @@ public string Summary { summary = summary.Substring(0, 75); } - + return summary; } - } - + } + public void Deserialize(string content) { using (XmlReader reader = XmlReader.Create(new StringReader(content))) @@ -36,7 +36,7 @@ public void Deserialize(string content) { this.ReadXml(reader); } - + reader.Close(); } } @@ -55,7 +55,7 @@ public void ReadXml(XmlReader reader) // Add to the collection this.Add(logDetail); - } + } while (reader.ReadToNextSibling("LogProperty")); } @@ -80,7 +80,7 @@ public override string ToString() { sb.Append(logDetail.ToString()); } - + return sb.ToString(); } @@ -91,8 +91,8 @@ public void WriteXml(XmlWriter writer) { logDetail.WriteXml(writer); } - + writer.WriteEndElement(); - } + } } } diff --git a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs index 0ef91402ed4..af37b2ee2d6 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LogTypeConfigInfo.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.Services.Log.EventLog [Serializable] public class LogTypeConfigInfo : LogTypeInfo - { + { private string _mailFromAddress; - + public enum NotificationThresholdTimeTypes { None = 0, @@ -20,7 +20,7 @@ public enum NotificationThresholdTimeTypes Minutes = 2, Hours = 3, Days = 4, - } + } public DateTime StartDateTime { @@ -46,18 +46,18 @@ public DateTime StartDateTime public string MailFromAddress { - get + get { var portalSettings = Globals.GetPortalSettings(); return string.IsNullOrWhiteSpace(this._mailFromAddress) ? (portalSettings == null ? string.Empty : portalSettings.Email) - : this._mailFromAddress; + : this._mailFromAddress; } - + set { this._mailFromAddress = value; } } - + public string MailToAddress { get; set; } public int NotificationThreshold { get; set; } diff --git a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs index 23fbcff4952..8c09e3846cb 100644 --- a/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs +++ b/DNN Platform/Library/Services/Log/EventLog/LoggingProvider.cs @@ -12,19 +12,19 @@ namespace DotNetNuke.Services.Log.EventLog using DotNetNuke.ComponentModel; public abstract class LoggingProvider - { + { public enum ReturnType { LogInfoObjects, XML, - } - - // return the provider + } + + // return the provider public static LoggingProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + public abstract void AddLog(LogInfo logInfo); public abstract void AddLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); @@ -68,6 +68,6 @@ public virtual List GetLogs(int portalID, string logType, int pageSize, public abstract void UpdateLogType(string logTypeKey, string logTypeFriendlyName, string logTypeDescription, string logTypeCSSClass, string logTypeOwner); - public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); + public abstract void UpdateLogTypeConfigInfo(string id, bool loggingIsActive, string logTypeKey, string logTypePortalID, string keepMostRecent, string logFileName, bool emailNotificationIsActive, string threshold, string notificationThresholdTime, string notificationThresholdTimeType, string mailFromAddress, string mailToAddress); } } diff --git a/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs b/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs index aafc9dea15a..070963a640c 100644 --- a/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs +++ b/DNN Platform/Library/Services/Log/EventLog/PurgeLogBuffer.cs @@ -29,7 +29,7 @@ public override void DoWork() this.ScheduleHistoryItem.Succeeded = false; // REQUIRED this.ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); // OPTIONAL this.Errored(ref exc); // REQUIRED - + // log the exception Exceptions.Exceptions.LogException(exc); // OPTIONAL } diff --git a/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs b/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs index 8af03e24945..aff897de5de 100644 --- a/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs +++ b/DNN Platform/Library/Services/Log/EventLog/SendLogNotifications.cs @@ -29,7 +29,7 @@ public override void DoWork() this.ScheduleHistoryItem.Succeeded = false; // REQUIRED this.ScheduleHistoryItem.AddLogNote("EXCEPTION: " + exc); // OPTIONAL this.Errored(ref exc); // REQUIRED - + // log the exception Exceptions.Exceptions.LogException(exc); // OPTIONAL } diff --git a/DNN Platform/Library/Services/Mail/Mail.cs b/DNN Platform/Library/Services/Mail/Mail.cs index be93f07def0..32d741274b0 100644 --- a/DNN Platform/Library/Services/Mail/Mail.cs +++ b/DNN Platform/Library/Services/Mail/Mail.cs @@ -23,9 +23,9 @@ namespace DotNetNuke.Services.Mail using Localize = DotNetNuke.Services.Localization.Localization; 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); @@ -36,168 +36,17 @@ public static string ConvertToText(string sHTML) 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, - string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) - { - string retValue = string.Empty; - - mailMessage.Priority = (System.Net.Mail.MailPriority)priority; - mailMessage.IsBodyHtml = bodyFormat == MailFormat.Html; - - // Only modify senderAdress if smtpAuthentication is enabled - // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM. - if (smtpAuthentication == "1" || smtpAuthentication == "2") - { - // if the senderAddress is the email address of the Host then switch it smtpUsername if different - // if display name of senderAddress is empty, then use Host.HostTitle for it - if (mailMessage.Sender != null) - { - var senderAddress = mailMessage.Sender.Address; - var senderDisplayName = mailMessage.Sender.DisplayName; - var needUpdateSender = false; - if (smtpUsername.Contains("@") && senderAddress == Host.HostEmail && - !senderAddress.Equals(smtpUsername, StringComparison.InvariantCultureIgnoreCase)) - { - senderAddress = smtpUsername; - needUpdateSender = true; - } - - if (string.IsNullOrEmpty(senderDisplayName)) - { - senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle; - needUpdateSender = true; - } - - if (needUpdateSender) - { - mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName); - } - } - else if (smtpUsername.Contains("@")) - { - mailMessage.Sender = new MailAddress(smtpUsername, Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle); - } - } - - // attachments - foreach (var attachment in attachments) - { - mailMessage.Attachments.Add(attachment); - } - - // message - mailMessage.SubjectEncoding = bodyEncoding; - mailMessage.Subject = HtmlUtils.StripWhiteSpace(subject, true); - mailMessage.BodyEncoding = bodyEncoding; - - // added support for multipart html messages - // add text part as alternate view - var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain"); - mailMessage.AlternateViews.Add(PlainView); - if (mailMessage.IsBodyHtml) - { - var HTMLView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); - mailMessage.AlternateViews.Add(HTMLView); - } - - smtpServer = smtpServer.Trim(); - if (SmtpServerRegex.IsMatch(smtpServer)) - { - try - { - // to workaround problem in 4.0 need to specify host name - using (var smtpClient = new SmtpClient()) - { - var smtpHostParts = smtpServer.Split(':'); - smtpClient.Host = smtpHostParts[0]; - if (smtpHostParts.Length > 1) - { - // port is guaranteed to be of max 5 digits numeric by the RegEx check - var port = Convert.ToInt32(smtpHostParts[1]); - if (port < 1 || port > 65535) - { - return Localize.GetString("SmtpInvalidPort"); - } - - smtpClient.Port = port; - } - - // else the port defaults to 25 by .NET when not set - smtpClient.ServicePoint.MaxIdleTime = Host.SMTPMaxIdleTime; - smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit; - - switch (smtpAuthentication) - { - case "": - case "0": // anonymous - break; - case "1": // basic - if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword)) - { - smtpClient.UseDefaultCredentials = false; - smtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword); - } - - break; - case "2": // NTLM - smtpClient.UseDefaultCredentials = true; - break; - } - - smtpClient.EnableSsl = smtpEnableSSL; - smtpClient.Send(mailMessage); - smtpClient.Dispose(); - } - } - catch (Exception exc) - { - var exc2 = exc as SmtpFailedRecipientException; - if (exc2 != null) - { - retValue = string.Format(Localize.GetString("FailedRecipient"), exc2.FailedRecipient) + " "; - } - else if (exc is SmtpException) - { - retValue = Localize.GetString("SMTPConfigurationProblem") + " "; - } - - // mail configuration problem - if (exc.InnerException != null) - { - retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message); - Exceptions.Exceptions.LogException(exc.InnerException); - } - else - { - retValue += exc.Message; - Exceptions.Exceptions.LogException(exc); - } - } - finally - { - mailMessage.Dispose(); - } - } - else - { - retValue = Localize.GetString("SMTPConfigurationProblem"); - } - - return retValue; - } - public static void SendEmail(string fromAddress, string toAddress, string subject, string body) { SendEmail(fromAddress, fromAddress, toAddress, subject, body); @@ -306,7 +155,7 @@ public static string SendMail(int portalId, int userId, MessageType msgType, Por user, Scope.SystemMessages, ref propertyNotFound)), }; } - + break; case MessageType.PasswordReminder: subject = "EMAIL_PASSWORD_REMINDER_SUBJECT"; @@ -382,7 +231,7 @@ public static string SendMail(string mailFrom, string mailTo, string bcc, string break; } } - + return SendMail(mailFrom, mailTo, string.Empty, bcc, MailPriority.Normal, subject, bodyFormat, Encoding.UTF8, body, attachment, smtpServer, smtpAuthentication, smtpUsername, smtpPassword); } @@ -414,7 +263,7 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string attachment, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail( + return SendMail( mailFrom, mailTo, cc, @@ -436,7 +285,7 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, string[] attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail( + return SendMail( mailFrom, mailTo, cc, @@ -500,7 +349,7 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string select new Attachment(attachment)) .ToList(); - return SendMail( + return SendMail( mailFrom, mailTo, cc, @@ -522,7 +371,7 @@ public static string SendMail(string mailFrom, string mailTo, string cc, string public static string SendMail(string mailFrom, string mailTo, string cc, string bcc, string replyTo, MailPriority priority, string subject, MailFormat bodyFormat, Encoding bodyEncoding, string body, List attachments, string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) { - return SendMail( + return SendMail( mailFrom, string.Empty, mailTo, @@ -550,17 +399,17 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, { smtpServer = Host.SMTPServer; } - + if (string.IsNullOrEmpty(smtpAuthentication) && !string.IsNullOrEmpty(Host.SMTPAuthentication)) { smtpAuthentication = Host.SMTPAuthentication; } - + if (string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(Host.SMTPUsername)) { smtpUsername = Host.SMTPUsername; } - + if (string.IsNullOrEmpty(smtpPassword) && !string.IsNullOrEmpty(Host.SMTPPassword)) { smtpPassword = Host.SMTPPassword; @@ -573,7 +422,7 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, ? new MailMessage { From = - new MailAddress( + new MailAddress( mailFrom, UserController.GetUserByEmail(PortalSettings.Current.PortalId, mailFrom).DisplayName), } @@ -595,21 +444,21 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, mailTo = mailTo.Replace(";", ","); mailMessage.To.Add(mailTo); } - + if (!string.IsNullOrEmpty(cc)) { // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons cc = cc.Replace(";", ","); mailMessage.CC.Add(cc); } - + if (!string.IsNullOrEmpty(bcc)) { // translate semi-colon delimiters to commas as ASP.NET 2.0 does not support semi-colons bcc = bcc.Replace(";", ","); mailMessage.Bcc.Add(bcc); } - + if (replyTo != string.Empty) { mailMessage.ReplyToList.Add(new MailAddress(replyTo)); @@ -620,6 +469,157 @@ public static string SendMail(string mailFrom, string mailSender, string mailTo, return SendMailInternal(mailMessage, subject, body, priority, bodyFormat, bodyEncoding, attachments, smtpServer, smtpAuthentication, smtpUsername, smtpPassword, smtpEnableSSL); } - } + } + + private static string SendMailInternal(MailMessage mailMessage, string subject, string body, MailPriority priority, + MailFormat bodyFormat, Encoding bodyEncoding, IEnumerable attachments, + string smtpServer, string smtpAuthentication, string smtpUsername, string smtpPassword, bool smtpEnableSSL) + { + string retValue = string.Empty; + + mailMessage.Priority = (System.Net.Mail.MailPriority)priority; + mailMessage.IsBodyHtml = bodyFormat == MailFormat.Html; + + // Only modify senderAdress if smtpAuthentication is enabled + // Can be "0", empty or Null - anonymous, "1" - basic, "2" - NTLM. + if (smtpAuthentication == "1" || smtpAuthentication == "2") + { + // if the senderAddress is the email address of the Host then switch it smtpUsername if different + // if display name of senderAddress is empty, then use Host.HostTitle for it + if (mailMessage.Sender != null) + { + var senderAddress = mailMessage.Sender.Address; + var senderDisplayName = mailMessage.Sender.DisplayName; + var needUpdateSender = false; + if (smtpUsername.Contains("@") && senderAddress == Host.HostEmail && + !senderAddress.Equals(smtpUsername, StringComparison.InvariantCultureIgnoreCase)) + { + senderAddress = smtpUsername; + needUpdateSender = true; + } + + if (string.IsNullOrEmpty(senderDisplayName)) + { + senderDisplayName = Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle; + needUpdateSender = true; + } + + if (needUpdateSender) + { + mailMessage.Sender = new MailAddress(senderAddress, senderDisplayName); + } + } + else if (smtpUsername.Contains("@")) + { + mailMessage.Sender = new MailAddress(smtpUsername, Host.SMTPPortalEnabled ? PortalSettings.Current.PortalName : Host.HostTitle); + } + } + + // attachments + foreach (var attachment in attachments) + { + mailMessage.Attachments.Add(attachment); + } + + // message + mailMessage.SubjectEncoding = bodyEncoding; + mailMessage.Subject = HtmlUtils.StripWhiteSpace(subject, true); + mailMessage.BodyEncoding = bodyEncoding; + + // added support for multipart html messages + // add text part as alternate view + var PlainView = AlternateView.CreateAlternateViewFromString(ConvertToText(body), null, "text/plain"); + mailMessage.AlternateViews.Add(PlainView); + if (mailMessage.IsBodyHtml) + { + var HTMLView = AlternateView.CreateAlternateViewFromString(body, null, "text/html"); + mailMessage.AlternateViews.Add(HTMLView); + } + + smtpServer = smtpServer.Trim(); + if (SmtpServerRegex.IsMatch(smtpServer)) + { + try + { + // to workaround problem in 4.0 need to specify host name + using (var smtpClient = new SmtpClient()) + { + var smtpHostParts = smtpServer.Split(':'); + smtpClient.Host = smtpHostParts[0]; + if (smtpHostParts.Length > 1) + { + // port is guaranteed to be of max 5 digits numeric by the RegEx check + var port = Convert.ToInt32(smtpHostParts[1]); + if (port < 1 || port > 65535) + { + return Localize.GetString("SmtpInvalidPort"); + } + + smtpClient.Port = port; + } + + // else the port defaults to 25 by .NET when not set + smtpClient.ServicePoint.MaxIdleTime = Host.SMTPMaxIdleTime; + smtpClient.ServicePoint.ConnectionLimit = Host.SMTPConnectionLimit; + + switch (smtpAuthentication) + { + case "": + case "0": // anonymous + break; + case "1": // basic + if (!string.IsNullOrEmpty(smtpUsername) && !string.IsNullOrEmpty(smtpPassword)) + { + smtpClient.UseDefaultCredentials = false; + smtpClient.Credentials = new NetworkCredential(smtpUsername, smtpPassword); + } + + break; + case "2": // NTLM + smtpClient.UseDefaultCredentials = true; + break; + } + + smtpClient.EnableSsl = smtpEnableSSL; + smtpClient.Send(mailMessage); + smtpClient.Dispose(); + } + } + catch (Exception exc) + { + var exc2 = exc as SmtpFailedRecipientException; + if (exc2 != null) + { + retValue = string.Format(Localize.GetString("FailedRecipient"), exc2.FailedRecipient) + " "; + } + else if (exc is SmtpException) + { + retValue = Localize.GetString("SMTPConfigurationProblem") + " "; + } + + // mail configuration problem + if (exc.InnerException != null) + { + retValue += string.Concat(exc.Message, Environment.NewLine, exc.InnerException.Message); + Exceptions.Exceptions.LogException(exc.InnerException); + } + else + { + retValue += exc.Message; + Exceptions.Exceptions.LogException(exc); + } + } + finally + { + mailMessage.Dispose(); + } + } + else + { + retValue = Localize.GetString("SMTPConfigurationProblem"); + } + + return retValue; + } } } diff --git a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs index 829b1428f84..dfc586776f4 100644 --- a/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs +++ b/DNN Platform/Library/Services/Mail/SendTokenizedBulkEmail.cs @@ -38,24 +38,25 @@ namespace DotNetNuke.Services.Mail /// ----------------------------------------------------------------------------- public class SendTokenizedBulkEmail : IDisposable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SendTokenizedBulkEmail)); - - // ReSharper restore InconsistentNaming + 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). /// - // ReSharper disable InconsistentNaming - // Existing public API + // ReSharper disable InconsistentNaming + // Existing public API public enum AddressMethods { Send_TO = 1, Send_BCC = 2, Send_Relay = 3, - } + } + private UserInfo _replyToUser; private bool _smtpEnableSSL; private TokenReplace _tokenReplace; @@ -72,8 +73,8 @@ public enum AddressMethods private string _smtpServer = string.Empty; private string _smtpUsername = string.Empty; private string _strSenderLanguage; - private bool _isDisposed; - + private bool _isDisposed; + public SendTokenizedBulkEmail() { this.ReportRecipients = true; @@ -97,13 +98,13 @@ public SendTokenizedBulkEmail(List addressedRoles, List addres this.Body = body; this.SuppressTokenReplace = this.SuppressTokenReplace; this.Initialize(); - } + } ~SendTokenizedBulkEmail() { this.Dispose(false); } - + /// /// Gets or sets priority of emails to be sent. /// @@ -125,7 +126,7 @@ public string Body { return this._body; } - + set { this._body = value; @@ -152,7 +153,7 @@ public UserInfo SendingUser { return this._sendingUser; } - + set { this._sendingUser = value; @@ -176,21 +177,21 @@ public UserInfo ReplyTo { return this._replyToUser ?? this.SendingUser; } - + set { 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; } - + 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; } - + 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; } @@ -201,15 +202,15 @@ public string RelayEmailAddress { return this.AddressMethod == AddressMethods.Send_Relay ? this._relayEmail : string.Empty; } - + set { this._relayEmail = value; } } - public string[] LanguageFilter { get; set; } - + public string[] LanguageFilter { get; set; } + /// Specify SMTP server to be used. /// name of the SMTP server. /// authentication string (0: anonymous, 1: basic, 2: NTLM). @@ -238,7 +239,7 @@ 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() { @@ -292,7 +293,7 @@ private void SendConfirmationMail(int numRecipients, int numMessages, int numErr { strSubject = this._tokenReplace.ReplaceEnvironmentTokens(strSubject); } - + var message = new Message { FromUserID = this._sendingUser.UserID, ToUserID = this._sendingUser.UserID, Subject = strSubject, Body = body, Status = MessageStatusType.Unread }; Mail.SendEmail(this._sendingUser.Email, this._sendingUser.Email, message.Subject, message.Body); @@ -335,7 +336,7 @@ private void ConditionallyAddUser(UserInfo user, ref List keyList, ref L { key = user.UserID.ToString(CultureInfo.InvariantCulture); } - + if (key != string.Empty && !keyList.Contains(key)) { userList.Add(user); @@ -362,14 +363,14 @@ private List LoadAttachments() { break; } - + memoryStream.Write(buffer, 0, read); } - + newAttachment = new Attachment(memoryStream, attachment.ContentType); newAttachment.ContentStream.Position = 0; attachments.Add(newAttachment); - + // reset original position attachment.ContentStream.Position = 0; memoryStream = null; @@ -379,9 +380,9 @@ private List LoadAttachments() memoryStream?.Dispose(); } } - + return attachments; - } + } public void AddAttachment(Stream contentStream, ContentType contentType) { @@ -427,7 +428,7 @@ public List Recipients() UserInfo user = objUser; ProfileController.GetUserProfile(ref user); var userRole = RoleController.Instance.GetUserRole(this._portalSettings.PortalId, objUser.UserID, roleInfo.RoleID); - + // only add if user role has not expired and effectivedate has been passed if ((userRole.EffectiveDate <= DateTime.Now || Null.IsNull(userRole.EffectiveDate)) && (userRole.ExpiryDate >= DateTime.Now || Null.IsNull(userRole.ExpiryDate))) { @@ -464,7 +465,7 @@ public int SendMails() var host = this.PortalAlias.Contains("/") ? this.PortalAlias.Substring(0, this.PortalAlias.IndexOf('/')) : this.PortalAlias; body = "" + this.Subject + "" + body + ""; } - + string subject = this.Subject; string startedAt = DateTime.Now.ToString(CultureInfo.InvariantCulture); @@ -488,13 +489,13 @@ public int SendMails() { body = this._tokenReplace.ReplaceEnvironmentTokens(body); } - + if (!individualSubj) { subject = this._tokenReplace.ReplaceEnvironmentTokens(subject); } } - + foreach (UserInfo user in this.Recipients()) { recipients += 1; @@ -506,16 +507,16 @@ public int SendMails() { body = this._tokenReplace.ReplaceEnvironmentTokens(this._body); } - + if (individualSubj) { subject = this._tokenReplace.ReplaceEnvironmentTokens(this.Subject); } } - + string recipient = this.AddressMethod == AddressMethods.Send_TO ? user.Email : this.RelayEmailAddress; - string mailError = Mail.SendMail( + string mailError = Mail.SendMail( this._sendingUser.Email, recipient, string.Empty, @@ -572,8 +573,8 @@ public int SendMails() body = this._body; subject = this.Subject; } - - string mailError = Mail.SendMail( + + string mailError = Mail.SendMail( this._sendingUser.Email, this._sendingUser.Email, string.Empty, @@ -600,15 +601,15 @@ public int SendMails() errors += 1; } } - + break; } - + if (mailErrors.Length > 0) { mailRecipients = new StringBuilder(); } - + this.SendConfirmationMail(recipients, messagesSent, errors, subject, startedAt, mailErrors.ToString(), mailRecipients.ToString()); } catch (Exception exc) // send mail failure @@ -624,7 +625,7 @@ public int SendMails() attachment.Dispose(); } } - + return messagesSent; } @@ -633,7 +634,7 @@ public void Send() { this.EnsureNotDisposed(); this.SendMails(); - } + } public void Dispose() { @@ -654,11 +655,11 @@ protected virtual void Dispose(bool disposing) this._isDisposed = true; } } - + // get rid of unmanaged resources } } - + private void EnsureNotDisposed() { if (this._isDisposed) diff --git a/DNN Platform/Library/Services/Messaging/Data/Message.cs b/DNN Platform/Library/Services/Messaging/Data/Message.cs index 8141202eea8..ce79ab1d64f 100644 --- a/DNN Platform/Library/Services/Messaging/Data/Message.cs +++ b/DNN Platform/Library/Services/Messaging/Data/Message.cs @@ -35,17 +35,17 @@ public class Message : IHydratable private string _ToUserName; private bool _allowReply; - private bool _skipInbox; - + private bool _skipInbox; + private Guid _EmailSchedulerInstance; private DateTime _EmailSentDate; - + public Message() { this.Conversation = Guid.Empty; this.Status = MessageStatusType.Draft; this.MessageDate = DateTime.Now; - } + } public string FromUserName { @@ -53,59 +53,59 @@ public string FromUserName { return this._FromUserName; } - + private set { this._FromUserName = value; } } - + public int FromUserID { get { return this._FromUserID; } - + set { this._FromUserID = value; } } - + public int ToRoleID { get { return this._ToRoleId; } - + set { this._ToRoleId = value; } } - + public bool AllowReply { get { return this._allowReply; } - + set { this._allowReply = value; } } - + public bool SkipInbox { get { return this._skipInbox; } - + set { this._skipInbox = value; @@ -118,20 +118,20 @@ public bool EmailSent { return this._EmailSent; } - + set { this._EmailSent = value; } } - + public string Body { get { return this._Body; } - + set { this._Body = value; @@ -144,7 +144,7 @@ public DateTime MessageDate { return this._MessageDate; } - + set { this._MessageDate = value; @@ -157,7 +157,7 @@ public Guid Conversation { return this._Conversation; } - + set { this._Conversation = value; @@ -170,20 +170,20 @@ public int MessageID { return this._MessageID; } - + private set { this._MessageID = value; } } - + public int PortalID { get { return this._PortalID; } - + set { this._PortalID = value; @@ -196,7 +196,7 @@ public int ReplyTo { return this._ReplyTo; } - + private set { this._ReplyTo = value; @@ -209,7 +209,7 @@ public MessageStatusType Status { return this._Status; } - + set { this._Status = value; @@ -223,7 +223,7 @@ public string Subject var ps = PortalSecurity.Instance; return ps.InputFilter(this._Subject, PortalSecurity.FilterFlag.NoMarkup); } - + set { var ps = PortalSecurity.Instance; @@ -231,14 +231,14 @@ public string Subject this._Subject = ps.InputFilter(value, PortalSecurity.FilterFlag.NoMarkup); } } - + public int ToUserID { get { return this._ToUserID; } - + set { this._ToUserID = value; @@ -251,38 +251,38 @@ public string ToUserName { return this._ToUserName; } - + private set { this._ToUserName = value; } } - + public DateTime EmailSentDate { get { return this._EmailSentDate; } - + private set { this._EmailSentDate = value; } } - + public Guid EmailSchedulerInstance { get { return this._EmailSchedulerInstance; } - + private set { this._EmailSchedulerInstance = value; } - } + } public int KeyID { @@ -290,13 +290,13 @@ public int KeyID { return this.MessageID; } - + set { this.MessageID = value; } - } - + } + public Message GetReplyMessage() { var message = new Message(); @@ -312,8 +312,8 @@ public Message GetReplyMessage() message.Subject = "RE:" + this.Subject; return message; - } - + } + public void Fill(IDataReader dr) { this.MessageID = Null.SetNullInteger(dr["MessageID"]); @@ -321,7 +321,7 @@ public void Fill(IDataReader dr) this.FromUserID = Null.SetNullInteger(dr["FromUserID"]); this.FromUserName = Null.SetNullString(dr["FromUserName"]); this.ToUserID = Null.SetNullInteger(dr["ToUserID"]); - + // '_ToUserName = Null.SetNullString(dr.Item("ToUserName")) this.ReplyTo = Null.SetNullInteger(dr["ReplyTo"]); this.Status = (MessageStatusType)Enum.Parse(typeof(MessageStatusType), Null.SetNullString(dr["Status"])); @@ -337,7 +337,7 @@ public void Fill(IDataReader dr) this.EmailSentDate = Null.SetNullDateTime(dr["EmailSentDate"]); this.EmailSchedulerInstance = Null.SetNullGuid(dr["EmailSchedulerInstance"]); this.Conversation = Null.SetNullGuid(dr["Conversation"]); - + // 'Conversation = New Guid(g) } } diff --git a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs index d10078a5329..29cf7294820 100644 --- a/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs +++ b/DNN Platform/Library/Services/Messaging/Data/MessagingDataService.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.Services.Messaging.Data public class MessagingDataService : IMessagingDataService { - private readonly DataProvider provider = DataProvider.Instance(); - + private readonly DataProvider provider = DataProvider.Instance(); + public IDataReader GetMessageByID(int messageId) { return this.provider.ExecuteReader("Messaging_GetMessage", messageId); @@ -29,7 +29,7 @@ public int GetInboxCount(int PortalID, int UserID) public long SaveMessage(Message objMessaging) { - return this.provider.ExecuteScalar( + return this.provider.ExecuteScalar( "Messaging_Save_Message", objMessaging.PortalID, objMessaging.FromUserID, @@ -62,7 +62,7 @@ public void MarkMessageAsDispatched(int MessageID) public void UpdateMessage(Message message) { - this.provider.ExecuteNonQuery( + this.provider.ExecuteNonQuery( "Messaging_UpdateMessage", message.MessageID, message.ToUserID, @@ -74,6 +74,6 @@ public void UpdateMessage(Message message) message.ReplyTo, message.AllowReply, message.SkipInbox); - } + } } } diff --git a/DNN Platform/Library/Services/Mobile/IMatchRule.cs b/DNN Platform/Library/Services/Mobile/IMatchRule.cs index 99a2ecac627..f9cca203385 100644 --- a/DNN Platform/Library/Services/Mobile/IMatchRule.cs +++ b/DNN Platform/Library/Services/Mobile/IMatchRule.cs @@ -11,7 +11,7 @@ public interface IMatchRule /// Gets primary Id. /// int Id { get; } - + /// /// Gets or sets capbility name. /// diff --git a/DNN Platform/Library/Services/Mobile/IRedirection.cs b/DNN Platform/Library/Services/Mobile/IRedirection.cs index 24c928a8fb5..b16820d676c 100644 --- a/DNN Platform/Library/Services/Mobile/IRedirection.cs +++ b/DNN Platform/Library/Services/Mobile/IRedirection.cs @@ -12,12 +12,12 @@ public interface IRedirection /// Gets primary ID. /// int Id { get; } - + /// /// Gets or sets portal Id. /// int PortalId { get; set; } - + /// /// Gets or sets redirection name. /// diff --git a/DNN Platform/Library/Services/Mobile/MatchRule.cs b/DNN Platform/Library/Services/Mobile/MatchRule.cs index c9669a8b16a..9018627b32a 100644 --- a/DNN Platform/Library/Services/Mobile/MatchRule.cs +++ b/DNN Platform/Library/Services/Mobile/MatchRule.cs @@ -26,7 +26,7 @@ public int Id { return this._id; } - + set { this._id = value; @@ -63,7 +63,7 @@ public int KeyID { return this.Id; } - + set { this.Id = value; diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs index b404f6cbe04..9537743e3e7 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfile.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfile.cs @@ -25,7 +25,7 @@ public int Id { return this._id; } - + set { this._id = value; @@ -86,7 +86,7 @@ public int KeyID { return this.Id; } - + set { this.Id = value; diff --git a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs index 012f6d413d4..f9ad2436884 100644 --- a/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs +++ b/DNN Platform/Library/Services/Mobile/PreviewProfileController.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Services.Mobile /// The business of mobile preview profiles. /// public class PreviewProfileController : IPreviewProfileController - { + { /// /// save a preview profile. If profile.Id equals Null.NullInteger(-1), that means need to add a new profile; /// otherwise will update the profile by profile.Id. @@ -36,7 +36,7 @@ public void Save(IPreviewProfile profile) profile.SortOrder = this.GetProfilesByPortal(profile.PortalId, false).Count + 1; } - int id = DataProvider.Instance().SavePreviewProfile( + int id = DataProvider.Instance().SavePreviewProfile( profile.Id, profile.PortalId, profile.Name, @@ -98,8 +98,8 @@ public IList GetProfilesByPortal(int portalId) public IPreviewProfile GetProfileById(int portalId, int id) { return this.GetProfilesByPortal(portalId).Where(r => r.Id == id).FirstOrDefault(); - } - + } + private IList GetProfilesByPortal(int portalId, bool addDefault) { string cacheKey = string.Format(DataCache.PreviewProfilesCacheKey, portalId); @@ -130,7 +130,7 @@ private void AddLog(string logContent) { EventLogController.Instance.AddLog("Message", logContent, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.ADMIN_ALERT); } - + private List CreateDefaultDevices(int portalId) { string defaultPreviewProfiles; @@ -172,6 +172,6 @@ private List CreateDefaultDevices(int portalId) } return profiles; - } + } } } diff --git a/DNN Platform/Library/Services/Mobile/Redirection.cs b/DNN Platform/Library/Services/Mobile/Redirection.cs index 2b999f40065..889168cfa8a 100644 --- a/DNN Platform/Library/Services/Mobile/Redirection.cs +++ b/DNN Platform/Library/Services/Mobile/Redirection.cs @@ -30,7 +30,7 @@ public int Id { return this._id; } - + set { this._id = value; @@ -93,7 +93,7 @@ public IList MatchRules return this._matchRules; } - + set { this._matchRules = value; @@ -139,7 +139,7 @@ public int KeyID { return this.Id; } - + set { this.Id = value; diff --git a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs index d5eda6af7d7..38b1f535a7a 100644 --- a/DNN Platform/Library/Services/ModuleCache/FileProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/FileProvider.cs @@ -17,11 +17,11 @@ namespace DotNetNuke.Services.ModuleCache using DotNetNuke.Entities.Portals; public class FileProvider : ModuleCachingProvider - { + { private const string DataFileExtension = ".data.resources"; private const string AttribFileExtension = ".attrib.resources"; - private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); - + private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + public override string GenerateCacheKey(int tabModuleId, SortedDictionary varyBy) { var cacheKey = new StringBuilder(); @@ -34,7 +34,7 @@ public override string GenerateCacheKey(int tabModuleId, SortedDictionary - /// [jmarino] 2011-06-16 Check for ContainsKey for a write added. - /// - /// - /// - private static string GetCacheFolder(int portalId) - { - string cacheFolder; - - using (var readerLock = CacheFolderPath.GetReadLock()) - { - if (CacheFolderPath.TryGetValue(portalId, out cacheFolder)) - { - return cacheFolder; - } - } - - var portalInfo = PortalController.Instance.GetPortal(portalId); - - string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - - if (!string.IsNullOrEmpty(homeDirectoryMapPath)) - { - cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (!Directory.Exists(cacheFolder)) - { - Directory.CreateDirectory(cacheFolder); - } - } - - using (var writerLock = CacheFolderPath.GetWriteLock()) - { - if (!CacheFolderPath.ContainsKey(portalId)) - { - CacheFolderPath.Add(portalId, cacheFolder); - } - } - - return cacheFolder; - } - - private static string GetCacheFolder() - { - int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; - return GetCacheFolder(portalId); - } - - private static bool IsPathInApplication(string cacheFolder) - { - return cacheFolder.Contains(Globals.ApplicationMapPath); - } - - private bool IsFileExpired(string file) - { - StreamReader oRead = null; - try - { - oRead = File.OpenText(file); - DateTime expires = DateTime.Parse(oRead.ReadLine(), CultureInfo.InvariantCulture); - if (expires < DateTime.UtcNow) - { - return true; - } - else - { - return false; - } - } - catch - { - // if check expire time failed, then force to expire the cache. - return true; - } - finally - { - if (oRead != null) - { - oRead.Close(); - } - } - } - - private void PurgeCache(string folder) - { - var filesNotDeleted = new StringBuilder(); - int i = 0; - foreach (string File in Directory.GetFiles(folder, "*.resources")) - { - if (!FileSystemUtils.DeleteFileWithWait(File, 100, 200)) - { - filesNotDeleted.Append(string.Format("{0};", File)); - } - else - { - i += 1; - } - } - - if (filesNotDeleted.Length > 0) - { - throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); - } - } public override byte[] GetModule(int tabModuleId, string cacheKey) { @@ -179,7 +50,7 @@ public override byte[] GetModule(int tabModuleId, string cacheKey) { return null; } - + var fInfo = new FileInfo(cachedModule); long numBytes = fInfo.Length; using (var fStream = new FileStream(cachedModule, FileMode.Open, FileAccess.Read)) @@ -219,7 +90,7 @@ public override void PurgeExpiredItems(int portalId) } } } - + if (filesNotDeleted.Length > 0) { throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); @@ -279,7 +150,7 @@ public override void Remove(int tabModuleId) i += 1; } } - + if (filesNotDeleted.Length > 0) { throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); @@ -289,6 +160,135 @@ public override void Remove(int tabModuleId) { Exceptions.Exceptions.LogException(ex); } - } + } + + private static string GetAttribFileName(int tabModuleId, string cacheKey) + { + return string.Concat(GetCacheFolder(), cacheKey, AttribFileExtension); + } + + private static int GetCachedItemCount(int tabModuleId) + { + return Directory.GetFiles(GetCacheFolder(), string.Format("*{0}", DataFileExtension)).Length; + } + + private static string GetCachedOutputFileName(int tabModuleId, string cacheKey) + { + return string.Concat(GetCacheFolder(), cacheKey, DataFileExtension); + } + + /// + /// [jmarino] 2011-06-16 Check for ContainsKey for a write added. + /// + /// + /// + private static string GetCacheFolder(int portalId) + { + string cacheFolder; + + using (var readerLock = CacheFolderPath.GetReadLock()) + { + if (CacheFolderPath.TryGetValue(portalId, out cacheFolder)) + { + return cacheFolder; + } + } + + var portalInfo = PortalController.Instance.GetPortal(portalId); + + string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; + + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) + { + cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); + if (!Directory.Exists(cacheFolder)) + { + Directory.CreateDirectory(cacheFolder); + } + } + + using (var writerLock = CacheFolderPath.GetWriteLock()) + { + if (!CacheFolderPath.ContainsKey(portalId)) + { + CacheFolderPath.Add(portalId, cacheFolder); + } + } + + return cacheFolder; + } + + private static string GetCacheFolder() + { + int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; + return GetCacheFolder(portalId); + } + + private static bool IsPathInApplication(string cacheFolder) + { + return cacheFolder.Contains(Globals.ApplicationMapPath); + } + + 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 bool IsFileExpired(string file) + { + StreamReader oRead = null; + try + { + oRead = File.OpenText(file); + DateTime expires = DateTime.Parse(oRead.ReadLine(), CultureInfo.InvariantCulture); + if (expires < DateTime.UtcNow) + { + return true; + } + else + { + return false; + } + } + catch + { + // if check expire time failed, then force to expire the cache. + return true; + } + finally + { + if (oRead != null) + { + oRead.Close(); + } + } + } + + private void PurgeCache(string folder) + { + var filesNotDeleted = new StringBuilder(); + int i = 0; + foreach (string File in Directory.GetFiles(folder, "*.resources")) + { + if (!FileSystemUtils.DeleteFileWithWait(File, 100, 200)) + { + filesNotDeleted.Append(string.Format("{0};", File)); + } + else + { + i += 1; + } + } + + if (filesNotDeleted.Length > 0) + { + throw new IOException(string.Format("Deleted {0} files, however, some files are locked. Could not delete the following files: {1}", i, filesNotDeleted)); + } + } } } diff --git a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs index e0ebd4e6157..f1759227f3b 100644 --- a/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/MemoryProvider.cs @@ -26,7 +26,7 @@ public override string GenerateCacheKey(int tabModuleId, SortedDictionary 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); @@ -75,5 +60,20 @@ public override void PurgeExpiredItems(int portalId) { // throw new NotSupportedException(); } + + 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; + } } } diff --git a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs index 56a0fba715f..20b765db605 100644 --- a/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs +++ b/DNN Platform/Library/Services/ModuleCache/ModuleCachingProvider.cs @@ -28,35 +28,35 @@ 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) - { - int i; - var sOutput = new StringBuilder(arrInput.Length); - for (i = 0; i <= arrInput.Length - 1; i++) - { - sOutput.Append(arrInput[i].ToString("X2")); - } - - return sOutput.ToString(); - } - public abstract byte[] GetModule(int tabModuleId, string cacheKey); public abstract void Remove(int tabModuleId); - public abstract void SetModule(int tabModuleId, string cacheKey, TimeSpan duration, byte[] moduleOutput); - + public abstract void SetModule(int tabModuleId, string cacheKey, TimeSpan duration, byte[] moduleOutput); + public virtual void PurgeCache(int portalId) { } public virtual void PurgeExpiredItems(int portalId) { - } + } + + protected string ByteArrayToString(byte[] arrInput) + { + int i; + var sOutput = new StringBuilder(arrInput.Length); + for (i = 0; i <= arrInput.Length - 1; i++) + { + sOutput.Append(arrInput[i].ToString("X2")); + } + + return sOutput.ToString(); + } } } diff --git a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs index 3bc65f4588d..b08c6c9d0cf 100644 --- a/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs +++ b/DNN Platform/Library/Services/ModuleCache/PurgeModuleCache.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.ModuleCache public class PurgeModuleCache : SchedulerClient { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PurgeModuleCache)); - + public PurgeModuleCache(ScheduleHistoryItem objScheduleHistoryItem) { this.ScheduleHistoryItem = objScheduleHistoryItem; // REQUIRED @@ -41,7 +41,7 @@ public override void DoWork() Logger.Debug(exc); } } - + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED } catch (Exception exc) // REQUIRED diff --git a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs index 6a6029ee462..3454eef7691 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCacheResponseFilter.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.Services.OutputCache // helper class to capture the response into a file public abstract class OutputCacheResponseFilter : Stream { - private Stream _captureStream; - + private Stream _captureStream; + public OutputCacheResponseFilter(Stream filterChain, string cacheKey, TimeSpan cacheDuration, int maxVaryByCount) { this.ChainedStream = filterChain; @@ -19,31 +19,8 @@ public OutputCacheResponseFilter(Stream filterChain, string cacheKey, TimeSpan c this.CacheDuration = cacheDuration; this.MaxVaryByCount = maxVaryByCount; this._captureStream = this.CaptureStream; - } - - public TimeSpan CacheDuration { get; set; } - - public virtual string CacheKey { get; set; } - - public Stream CaptureStream - { - get - { - return this._captureStream; - } - - set - { - this._captureStream = value; - } } - public Stream ChainedStream { get; set; } - - public bool HasErrored { get; set; } - - public int MaxVaryByCount { get; set; } - public override bool CanRead { get @@ -76,19 +53,42 @@ public override long Length } } + public TimeSpan CacheDuration { get; set; } + + public virtual string CacheKey { get; set; } + + public Stream CaptureStream + { + get + { + return this._captureStream; + } + + set + { + this._captureStream = value; + } + } + + public Stream ChainedStream { get; set; } + + public bool HasErrored { get; set; } + + public int MaxVaryByCount { get; set; } + public override long Position { get { throw new NotSupportedException(); } - + set { throw new NotSupportedException(); } - } - + } + public override void Flush() { this.ChainedStream.Flush(); @@ -96,7 +96,7 @@ public override void Flush() { return; } - + if (this._captureStream != null) { this._captureStream.Flush(); @@ -110,7 +110,7 @@ public override void Write(byte[] buffer, int offset, int count) { return; } - + if (this._captureStream != null) { this._captureStream.Write(buffer, offset, count); @@ -130,7 +130,7 @@ public override long Seek(long offset, SeekOrigin origin) public override void SetLength(long value) { throw new NotSupportedException(); - } + } public virtual byte[] StopFiltering(int itemId, bool deleteData) { @@ -147,19 +147,19 @@ public virtual byte[] StopFiltering(int itemId, bool deleteData) string output = reader.ReadToEnd(); this.AddItemToCache(itemId, output); } - + this.CaptureStream.Close(); this.CaptureStream = null; } - + if (deleteData) { this.RemoveItemFromCache(itemId); } - + return null; } - + protected virtual void AddItemToCache(int itemId, string output) { } diff --git a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs index 50a4b907126..8768e154f41 100644 --- a/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/OutputCachingProvider.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.OutputCache using DotNetNuke.ComponentModel; public abstract class OutputCachingProvider - { + { public static Dictionary GetProviderList() { return ComponentFactory.GetComponents(); @@ -24,50 +24,6 @@ public static OutputCachingProvider Instance(string FriendlyName) { return ComponentFactory.GetComponent(FriendlyName); } - - protected string ByteArrayToString(byte[] arrInput) - { - int i = 0; - var sOutput = new StringBuilder(arrInput.Length); - for (i = 0; i <= arrInput.Length - 1; i++) - { - sOutput.Append(arrInput[i].ToString("X2")); - } - - return sOutput.ToString(); - } - - protected string GenerateCacheKeyHash(int tabId, string cacheKey) - { - byte[] hash = Encoding.ASCII.GetBytes(cacheKey); - using (var sha256 = new SHA256CryptoServiceProvider()) - { - hash = sha256.ComputeHash(hash); - return string.Concat(tabId.ToString(), "_", this.ByteArrayToString(hash)); - } - } - - protected void WriteStreamAsText(HttpContext context, Stream stream, long offset, long length) - { - if (length < 0) - { - length = stream.Length - offset; - } - - if (length > 0) - { - if (offset > 0) - { - stream.Seek(offset, SeekOrigin.Begin); - } - - var buffer = new byte[Convert.ToInt32(length)]; - int count = stream.Read(buffer, 0, Convert.ToInt32(length)); - char[] output = Encoding.UTF8.GetChars(buffer, 0, count); - context.Response.ContentEncoding = Encoding.UTF8; - context.Response.Output.Write(output); - } - } public static void RemoveItemFromAllProviders(int tabId) { @@ -75,8 +31,8 @@ public static void RemoveItemFromAllProviders(int tabId) { kvp.Value.Remove(tabId); } - } - + } + public abstract int GetItemCount(int tabId); public abstract byte[] GetOutput(int tabId, string cacheKey); @@ -87,8 +43,8 @@ public static void RemoveItemFromAllProviders(int tabId) public abstract void SetOutput(int tabId, string cacheKey, TimeSpan duration, byte[] output); - public abstract bool StreamOutput(int tabId, string cacheKey, HttpContext context); - + public abstract bool StreamOutput(int tabId, string cacheKey, HttpContext context); + public virtual string GenerateCacheKey(int tabId, StringCollection includeVaryByKeys, StringCollection excludeVaryByKeys, SortedDictionary varyBy) { var cacheKey = new StringBuilder(); @@ -104,7 +60,7 @@ public virtual string GenerateCacheKey(int tabId, StringCollection includeVaryBy } } } - + return this.GenerateCacheKeyHash(tabId, cacheKey.ToString()); } @@ -114,6 +70,50 @@ public virtual void PurgeCache(int portalId) public virtual void PurgeExpiredItems(int portalId) { - } + } + + protected string ByteArrayToString(byte[] arrInput) + { + int i = 0; + var sOutput = new StringBuilder(arrInput.Length); + for (i = 0; i <= arrInput.Length - 1; i++) + { + sOutput.Append(arrInput[i].ToString("X2")); + } + + return sOutput.ToString(); + } + + protected string GenerateCacheKeyHash(int tabId, string cacheKey) + { + byte[] hash = Encoding.ASCII.GetBytes(cacheKey); + using (var sha256 = new SHA256CryptoServiceProvider()) + { + hash = sha256.ComputeHash(hash); + return string.Concat(tabId.ToString(), "_", this.ByteArrayToString(hash)); + } + } + + protected void WriteStreamAsText(HttpContext context, Stream stream, long offset, long length) + { + if (length < 0) + { + length = stream.Length - offset; + } + + if (length > 0) + { + if (offset > 0) + { + stream.Seek(offset, SeekOrigin.Begin); + } + + var buffer = new byte[Convert.ToInt32(length)]; + int count = stream.Read(buffer, 0, Convert.ToInt32(length)); + char[] output = Encoding.UTF8.GetChars(buffer, 0, count); + context.Response.ContentEncoding = Encoding.UTF8; + context.Response.Output.Write(output); + } + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs index 6a2fcfaba16..bbb6f1ca54b 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseProvider.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Services.OutputCache.Providers /// DatabaseProvider implements the OutputCachingProvider for database storage. /// public class DatabaseProvider : OutputCachingProvider - { + { public override int GetItemCount(int tabId) { return DataProvider.Instance().GetOutputCacheItemCount(tabId); @@ -112,6 +112,6 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex dr.Close(); } } - } + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs index 848d1420415..5c570ada82a 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/DatabaseResponseFilter.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.OutputCache.Providers /// public class DatabaseResponseFilter : OutputCacheResponseFilter { - internal DatabaseResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + internal DatabaseResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && DataProvider.Instance().GetOutputCacheItemCount(itemId) >= maxVaryByCount) diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs index 6c620f5e368..295c1b0a0f5 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileProvider.cs @@ -24,8 +24,8 @@ public class FileProvider : OutputCachingProvider public const string AttribFileExtension = ".attrib.resources"; public const string TempFileExtension = ".temp.resources"; - private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); - + private static readonly SharedDictionary CacheFolderPath = new SharedDictionary(LockingStrategy.ReaderWriter); + public override int GetItemCount(int tabId) { return GetCachedItemCount(tabId); @@ -38,7 +38,7 @@ public override byte[] GetOutput(int tabId, string cacheKey) { return null; } - + var fInfo = new FileInfo(cachedOutput); long numBytes = fInfo.Length; using (var fStream = new FileStream(cachedOutput, FileMode.Open, FileAccess.Read)) @@ -47,119 +47,6 @@ public override byte[] GetOutput(int tabId, string cacheKey) 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; - return GetCacheFolder(portalId); - } - - private static string GetCacheFolder(int portalId) - { - string cacheFolder; - - using (var readerLock = CacheFolderPath.GetReadLock()) - { - if (CacheFolderPath.TryGetValue(portalId, out cacheFolder)) - { - return cacheFolder; - } - } - - var portalInfo = PortalController.Instance.GetPortal(portalId); - - string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; - - if (!string.IsNullOrEmpty(homeDirectoryMapPath)) - { - cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); - if (!Directory.Exists(cacheFolder)) - { - Directory.CreateDirectory(cacheFolder); - } - } - - using (var writerLock = CacheFolderPath.GetWriteLock()) - { - CacheFolderPath.Add(portalId, cacheFolder); - } - - return cacheFolder; - } - - private bool IsFileExpired(string file) - { - StreamReader oRead = null; - try - { - oRead = File.OpenText(file); - DateTime expires = Convert.ToDateTime(oRead.ReadLine()); - if (expires < DateTime.UtcNow) - { - return true; - } - else - { - return false; - } - } - finally - { - if (oRead != null) - { - oRead.Close(); - } - } - } - - private void PurgeCache(string folder) - { - try - { - var filesNotDeleted = new StringBuilder(); - int i = 0; - foreach (string file in Directory.GetFiles(folder, "*.resources")) - { - if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) - { - filesNotDeleted.Append(file + ";"); - } - else - { - i += 1; - } - } - - if (filesNotDeleted.Length > 0) - { - throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); - } - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - } - } - - internal static string GetCachedOutputFileName(int tabId, string cacheKey) - { - return string.Concat(GetCacheFolder(), cacheKey, DataFileExtension); - } - - internal static string GetTempFileName(int tabId, string cacheKey) - { - return string.Concat(GetCacheFolder(), cacheKey, TempFileExtension); - } public override OutputCacheResponseFilter GetResponseFilter(int tabId, int maxVaryByCount, Stream responseFilter, string cacheKey, TimeSpan cacheDuration) { @@ -198,7 +85,7 @@ public override void PurgeExpiredItems(int portalId) } } } - + if (filesNotDeleted.Length > 0) { throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); @@ -230,7 +117,7 @@ public override void Remove(int tabId) i += 1; } } - + if (filesNotDeleted.Length > 0) { var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; @@ -317,8 +204,121 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex { Exceptions.Exceptions.LogException(ex); } - + return foundFile; - } + } + + 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) + { + return string.Concat(GetCacheFolder(), cacheKey, DataFileExtension); + } + + internal static string GetTempFileName(int tabId, string cacheKey) + { + return string.Concat(GetCacheFolder(), cacheKey, TempFileExtension); + } + + private static string GetCacheFolder() + { + int portalId = PortalController.Instance.GetCurrentPortalSettings().PortalId; + return GetCacheFolder(portalId); + } + + private static string GetCacheFolder(int portalId) + { + string cacheFolder; + + using (var readerLock = CacheFolderPath.GetReadLock()) + { + if (CacheFolderPath.TryGetValue(portalId, out cacheFolder)) + { + return cacheFolder; + } + } + + var portalInfo = PortalController.Instance.GetPortal(portalId); + + string homeDirectoryMapPath = portalInfo.HomeSystemDirectoryMapPath; + + if (!string.IsNullOrEmpty(homeDirectoryMapPath)) + { + cacheFolder = string.Concat(homeDirectoryMapPath, "Cache\\Pages\\"); + if (!Directory.Exists(cacheFolder)) + { + Directory.CreateDirectory(cacheFolder); + } + } + + using (var writerLock = CacheFolderPath.GetWriteLock()) + { + CacheFolderPath.Add(portalId, cacheFolder); + } + + return cacheFolder; + } + + private bool IsFileExpired(string file) + { + StreamReader oRead = null; + try + { + oRead = File.OpenText(file); + DateTime expires = Convert.ToDateTime(oRead.ReadLine()); + if (expires < DateTime.UtcNow) + { + return true; + } + else + { + return false; + } + } + finally + { + if (oRead != null) + { + oRead.Close(); + } + } + } + + private void PurgeCache(string folder) + { + try + { + var filesNotDeleted = new StringBuilder(); + int i = 0; + foreach (string file in Directory.GetFiles(folder, "*.resources")) + { + if (!FileSystemUtils.DeleteFileWithWait(file, 100, 200)) + { + filesNotDeleted.Append(file + ";"); + } + else + { + i += 1; + } + } + + if (filesNotDeleted.Length > 0) + { + throw new IOException("Deleted " + i + " files, however, some files are locked. Could not delete the following files: " + filesNotDeleted); + } + } + catch (Exception ex) + { + Exceptions.Exceptions.LogException(ex); + } + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs index 61c60e140d6..dddc608b90d 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/FileResponseFilter.cs @@ -17,7 +17,7 @@ public class FileResponseFilter : OutputCacheResponseFilter // Private _content As StringBuilder private DateTime _cacheExpiration; - internal FileResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + internal FileResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && Services.OutputCache.Providers.FileProvider.GetCachedItemCount(itemId) >= maxVaryByCount) @@ -37,7 +37,7 @@ internal FileResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, this.HasErrored = true; } } - + if (this.HasErrored == false) { try @@ -67,7 +67,7 @@ public DateTime CacheExpiration { return this._cacheExpiration; } - + set { this._cacheExpiration = value; @@ -96,7 +96,7 @@ public override byte[] StopFiltering(int itemId, bool deleteData) oWrite.WriteLine(this._cacheExpiration.ToString()); oWrite.Close(); } - + if (deleteData) { FileSystemUtils.DeleteFileWithWait(this.CachedOutputFileName, 100, 200); diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs index 272b68e872c..c5c2908092d 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryProvider.cs @@ -19,8 +19,8 @@ namespace DotNetNuke.Services.OutputCache.Providers public class MemoryProvider : OutputCachingProvider { protected const string cachePrefix = "DNN_OUTPUT:"; - private static System.Web.Caching.Cache runtimeCache; - + private static System.Web.Caching.Cache runtimeCache; + internal static System.Web.Caching.Cache Cache { get @@ -30,7 +30,7 @@ internal static System.Web.Caching.Cache Cache { runtimeCache = HttpRuntime.Cache; } - + return runtimeCache; } } @@ -41,8 +41,8 @@ internal static string CachePrefix { return cachePrefix; } - } - + } + 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)); @@ -52,46 +52,6 @@ public override int GetItemCount(int tabId) { return GetCacheKeys(tabId).Count(); } - - internal static List GetCacheKeys() - { - var keys = new List(); - IDictionaryEnumerator CacheEnum = Cache.GetEnumerator(); - while (CacheEnum.MoveNext()) - { - if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix))) - { - keys.Add(CacheEnum.Key.ToString()); - } - } - - return keys; - } - - internal static List GetCacheKeys(int tabId) - { - var keys = new List(); - IDictionaryEnumerator CacheEnum = Cache.GetEnumerator(); - while (CacheEnum.MoveNext()) - { - if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, tabId.ToString(), "_"))) - { - keys.Add(CacheEnum.Key.ToString()); - } - } - - return keys; - } - - private string GetCacheKey(string CacheKey) - { - 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) { @@ -146,6 +106,46 @@ public override bool StreamOutput(int tabId, string cacheKey, HttpContext contex context.Response.BinaryWrite(Encoding.Default.GetBytes(Cache[cacheKey].ToString())); return true; - } + } + + internal static List GetCacheKeys() + { + var keys = new List(); + IDictionaryEnumerator CacheEnum = Cache.GetEnumerator(); + while (CacheEnum.MoveNext()) + { + if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix))) + { + keys.Add(CacheEnum.Key.ToString()); + } + } + + return keys; + } + + internal static List GetCacheKeys(int tabId) + { + var keys = new List(); + IDictionaryEnumerator CacheEnum = Cache.GetEnumerator(); + while (CacheEnum.MoveNext()) + { + if (CacheEnum.Key.ToString().StartsWith(string.Concat(cachePrefix, tabId.ToString(), "_"))) + { + keys.Add(CacheEnum.Key.ToString()); + } + } + + return keys; + } + + private string GetCacheKey(string CacheKey) + { + if (string.IsNullOrEmpty(CacheKey)) + { + throw new ArgumentException("Argument cannot be null or an empty string", "CacheKey"); + } + + return string.Concat(cachePrefix, CacheKey); + } } } diff --git a/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs b/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs index a5f61383daa..27d50c187d7 100644 --- a/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs +++ b/DNN Platform/Library/Services/OutputCache/Providers/MemoryResponseFilter.cs @@ -17,7 +17,7 @@ public class MemoryResponseFilter : OutputCacheResponseFilter // Private _content As StringBuilder private static System.Web.Caching.Cache runtimeCache; - internal MemoryResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) + internal MemoryResponseFilter(int itemId, int maxVaryByCount, Stream filterChain, string cacheKey, TimeSpan cacheDuration) : base(filterChain, cacheKey, cacheDuration, maxVaryByCount) { if (maxVaryByCount > -1 && Services.OutputCache.Providers.MemoryProvider.GetCacheKeys(itemId).Count >= maxVaryByCount) @@ -25,7 +25,7 @@ internal MemoryResponseFilter(int itemId, int maxVaryByCount, Stream filterChain this.HasErrored = true; return; } - + this.CaptureStream = new MemoryStream(); } @@ -38,7 +38,7 @@ protected static System.Web.Caching.Cache Cache { runtimeCache = HttpRuntime.Cache; } - + return runtimeCache; } } diff --git a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs index ac19fe59fb6..4d9ddfc7fa7 100644 --- a/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs +++ b/DNN Platform/Library/Services/OutputCache/PurgeOutputCache.cs @@ -41,7 +41,7 @@ public override void DoWork() Logger.Debug(exc); } } - + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED } catch (Exception exc) // REQUIRED diff --git a/DNN Platform/Library/Services/Personalization/Personalization.cs b/DNN Platform/Library/Services/Personalization/Personalization.cs index c13203b9a87..bc47111f626 100644 --- a/DNN Platform/Library/Services/Personalization/Personalization.cs +++ b/DNN Platform/Library/Services/Personalization/Personalization.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Services.Personalization using DotNetNuke.Security; public class Personalization - { + { /// /// load users profile and extract value base on naming container and key. /// @@ -34,32 +34,6 @@ public static object GetProfile(PersonalizationInfo personalization, string nami { return personalization != null ? personalization.Profile[namingContainer + ":" + key] : string.Empty; } - - private static PersonalizationInfo LoadProfile() - { - HttpContext context = HttpContext.Current; - - // First try and load Personalization object from the Context - var personalization = (PersonalizationInfo)context.Items["Personalization"]; - - // If the Personalization object is nothing load it and store it in the context for future calls - if (personalization == null) - { - var _portalSettings = (PortalSettings)context.Items["PortalSettings"]; - - // load the user info object - UserInfo UserInfo = UserController.Instance.GetCurrentUserInfo(); - - // get the personalization object - var personalizationController = new PersonalizationController(); - personalization = personalizationController.LoadProfile(UserInfo.UserID, _portalSettings.PortalId); - - // store it in the context - context.Items.Add("Personalization", personalization); - } - - return personalization; - } /// /// load users profile and extract secure value base on naming container and key. @@ -87,7 +61,7 @@ public static object GetSecureProfile(PersonalizationInfo personalization, strin var ps = PortalSecurity.Instance; return ps.DecryptString(personalization.Profile[namingContainer + ":" + key].ToString(), Config.GetDecryptionkey()); } - + return string.Empty; } @@ -173,6 +147,32 @@ public static void SetSecureProfile(PersonalizationInfo personalization, string personalization.Profile[namingContainer + ":" + key] = ps.EncryptString(value.ToString(), Config.GetDecryptionkey()); personalization.IsModified = true; } - } + } + + private static PersonalizationInfo LoadProfile() + { + HttpContext context = HttpContext.Current; + + // First try and load Personalization object from the Context + var personalization = (PersonalizationInfo)context.Items["Personalization"]; + + // If the Personalization object is nothing load it and store it in the context for future calls + if (personalization == null) + { + var _portalSettings = (PortalSettings)context.Items["PortalSettings"]; + + // load the user info object + UserInfo UserInfo = UserController.Instance.GetCurrentUserInfo(); + + // get the personalization object + var personalizationController = new PersonalizationController(); + personalization = personalizationController.LoadProfile(UserInfo.UserID, _portalSettings.PortalId); + + // store it in the context + context.Items.Add("Personalization", personalization); + } + + return personalization; + } } } diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs index cf43f8cba2d..f881e28a9e8 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationController.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationController.cs @@ -37,10 +37,10 @@ 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, + { + var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); + profileData = CBO.GetCachedObject( + new CacheItemArgs(cacheKey, DataCache.UserPersonalizationCacheTimeout, DataCache.UserPersonalizationCachePriority, portalId, userId), GetCachedUserPersonalizationCallback); } else @@ -62,7 +62,7 @@ public PersonalizationInfo LoadProfile(int userId, int portalId) } } } - + personalization.Profile = string.IsNullOrEmpty(profileData) ? new Hashtable() : Globals.DeserializeHashTableXml(profileData); return personalization; @@ -80,36 +80,6 @@ public void SaveProfile(HttpContext httpContext, int userId, int portalId) this.SaveProfile(objPersonalization, userId, portalId); } - private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheItemArgs) - { - var portalId = (int)cacheItemArgs.ParamList[0]; - var userId = (int)cacheItemArgs.ParamList[1]; - var returnValue = Null.NullString; // Default is no profile - IDataReader dr = null; - try - { - dr = DataProvider.Instance().GetProfile(userId, portalId); - if (dr.Read()) - { - returnValue = dr["ProfileData"].ToString(); - } - else // does not exist - { - DataProvider.Instance().AddProfile(userId, portalId); - } - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - } - finally - { - CBO.CloseDataReader(dr, true); - } - - return returnValue; - } - // override allows for manipulation of PersonalizationInfo outside of HTTPContext public void SaveProfile(PersonalizationInfo personalization, int userId, int portalId) { @@ -123,8 +93,8 @@ public void SaveProfile(PersonalizationInfo personalization, int userId, int por // remove then re-add the updated one var cacheKey = string.Format(DataCache.UserPersonalizationCacheKey, portalId, userId); DataCache.RemoveCache(cacheKey); - CBO.GetCachedObject( - new CacheItemArgs( + CBO.GetCachedObject( + new CacheItemArgs( cacheKey, DataCache.UserPersonalizationCacheTimeout, DataCache.UserPersonalizationCachePriority), _ => profileData); } @@ -145,6 +115,36 @@ public void SaveProfile(PersonalizationInfo personalization, int userId, int por } } + private static object GetCachedUserPersonalizationCallback(CacheItemArgs cacheItemArgs) + { + var portalId = (int)cacheItemArgs.ParamList[0]; + var userId = (int)cacheItemArgs.ParamList[1]; + var returnValue = Null.NullString; // Default is no profile + IDataReader dr = null; + try + { + dr = DataProvider.Instance().GetProfile(userId, portalId); + if (dr.Read()) + { + returnValue = dr["ProfileData"].ToString(); + } + else // does not exist + { + DataProvider.Instance().AddProfile(userId, portalId); + } + } + catch (Exception ex) + { + Exceptions.Exceptions.LogException(ex); + } + finally + { + CBO.CloseDataReader(dr, true); + } + + return returnValue; + } + private static string EncryptData(string profileData) { return PortalSecurity.Instance.Encrypt(ValidationUtils.GetDecryptionKey(), profileData); diff --git a/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs b/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs index a5ed3315ec2..95ec9e4bee2 100644 --- a/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs +++ b/DNN Platform/Library/Services/Personalization/PersonalizationInfo.cs @@ -8,13 +8,13 @@ namespace DotNetNuke.Services.Personalization [Serializable] public class PersonalizationInfo - { + { public int UserId { get; set; } public int PortalId { get; set; } public bool IsModified { get; set; } - public Hashtable Profile { get; set; } + public Hashtable Profile { get; set; } } } diff --git a/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs b/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs index e1374c25990..1744979f508 100644 --- a/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/DNNScheduler.cs @@ -16,22 +16,22 @@ namespace DotNetNuke.Services.Scheduling using Globals = DotNetNuke.Common.Globals; public class DNNScheduler : SchedulingProvider - { + { public override Dictionary Settings { get { return ComponentFactory.GetComponentSettings() as Dictionary; } - } - + } + public override int AddSchedule(ScheduleItem scheduleItem) { // Remove item from queue Scheduler.CoreScheduler.RemoveFromScheduleQueue(scheduleItem); - + // save item - scheduleItem.ScheduleID = SchedulingController.AddSchedule( + scheduleItem.ScheduleID = SchedulingController.AddSchedule( scheduleItem.TypeFullName, scheduleItem.TimeLapse, scheduleItem.TimeLapseMeasurement, @@ -45,7 +45,7 @@ public override int AddSchedule(ScheduleItem scheduleItem) scheduleItem.Servers, scheduleItem.FriendlyName, scheduleItem.ScheduleStartDate); - + // Add schedule to queue this.RunScheduleItemNow(scheduleItem); @@ -218,7 +218,7 @@ public override void StartAndWaitForResponse() { return; } - + Thread.Sleep(1000); } } @@ -233,10 +233,10 @@ public override void UpdateSchedule(ScheduleItem scheduleItem) { // Remove item from queue Scheduler.CoreScheduler.RemoveFromScheduleQueue(scheduleItem); - + // save item SchedulingController.UpdateSchedule(scheduleItem); - + // Update items that are already scheduled var futureHistory = this.GetScheduleHistory(scheduleItem.ScheduleID).Cast().Where(h => h.NextStart > DateTime.Now); @@ -248,7 +248,7 @@ public override void UpdateSchedule(ScheduleItem scheduleItem) scheduleHistoryItem.NextStart = scheduleItemStart; SchedulingController.UpdateScheduleHistory(scheduleHistoryItem); } - + // Add schedule to queue this.RunScheduleItemNow(scheduleItem); } @@ -259,6 +259,6 @@ public override void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) // get ScheduleHistoryItem of the running task var runningscheduleHistoryItem = this.GetScheduleHistory(scheduleItem.ScheduleID).Cast().ElementAtOrDefault(0); Scheduler.CoreScheduler.StopScheduleInProgress(scheduleItem, runningscheduleHistoryItem); - } + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs index d64380637d8..29fa587b95b 100644 --- a/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs +++ b/DNN Platform/Library/Services/Scheduling/ProcessGroup.cs @@ -14,19 +14,19 @@ namespace DotNetNuke.Services.Scheduling public class ProcessGroup { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(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 ticksElapsed; + // '''''''''''''''''''''''''''''''''''''''''''''''''' + // This class represents a process group for + // our threads to run in. + // '''''''''''''''''''''''''''''''''''''''''''''''''' + public delegate void CompletedEventHandler(); + public event CompletedEventHandler Completed; private static int GetTicksElapsed @@ -70,7 +70,7 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) Process.ProcessProgressing += Scheduler.CoreScheduler.WorkProgressing; Process.ProcessCompleted += Scheduler.CoreScheduler.WorkCompleted; Process.ProcessErrored += Scheduler.CoreScheduler.WorkErrored; - + // This kicks off the DoWork method of the class // type specified in the configuration. Process.Started(); @@ -92,11 +92,11 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) { Process.ScheduleHistoryItem.Succeeded = false; } - + Process.Errored(ref exc); } } - + if (Process.ScheduleHistoryItem.Succeeded) { Process.Completed(); @@ -131,7 +131,7 @@ public void Run(ScheduleHistoryItem objScheduleHistoryItem) { Process.ScheduleHistoryItem.Succeeded = false; } - + Process.Errored(ref exc); } else @@ -165,7 +165,7 @@ public void AddQueueUserWorkItem(ScheduleItem s) { // Create a callback to subroutine RunPooledThread WaitCallback callback = this.RunPooledThread; - + // And put in a request to ThreadPool to run the process. ThreadPool.QueueUserWorkItem(callback, obj); } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs b/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs index 30e69483f74..af4ea102587 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleHistoryItem.cs @@ -61,8 +61,6 @@ public ScheduleHistoryItem(ScheduleItem objScheduleItem) : Null.NullDate; } - public override DateTime NextStart { get; set; } - public double ElapsedTime { get @@ -89,21 +87,6 @@ public double ElapsedTime } } - public DateTime EndDate { get; set; } - - public string LogNotes - { - get - { - return this._LogNotes.ToString(); - } - - set - { - this._LogNotes = new StringBuilder(value); - } - } - public bool Overdue { get @@ -163,13 +146,30 @@ public double RemainingTime } } + public override DateTime NextStart { get; set; } + + public DateTime EndDate { get; set; } + + public string LogNotes + { + get + { + return this._LogNotes.ToString(); + } + + set + { + this._LogNotes = new StringBuilder(value); + } + } + public int ScheduleHistoryID { get { return this._ScheduleHistoryID; } - + set { this._ScheduleHistoryID = value; @@ -182,7 +182,7 @@ public string Server { return this._Server; } - + set { this._Server = value; @@ -195,7 +195,7 @@ public DateTime StartDate { return this._StartDate; } - + set { this._StartDate = value; @@ -208,24 +208,24 @@ public bool Succeeded { return this._Succeeded; } - + set { this._Succeeded = value; - if (_tracelLogger.IsDebugEnabled) - { - _tracelLogger.Debug($"ScheduleHistoryItem.Succeeded Info (ScheduledTask {(value == false ? "Start" : "End")}): {this.FriendlyName}"); - } + if (_tracelLogger.IsDebugEnabled) + { + _tracelLogger.Debug($"ScheduleHistoryItem.Succeeded Info (ScheduledTask {(value == false ? "Start" : "End")}): {this.FriendlyName}"); + } } } public virtual void AddLogNote(string notes) { this._LogNotes.Append(notes); - if (_tracelLogger.IsTraceEnabled) - { - _tracelLogger.Trace(notes.Replace(@"
    ", Environment.NewLine)); - } + if (_tracelLogger.IsTraceEnabled) + { + _tracelLogger.Trace(notes.Replace(@"
    ", Environment.NewLine)); + } } public override void Fill(IDataReader dr) diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs b/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs index e57dc82735d..468bd64ea63 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleHistorySortStartDate.cs @@ -14,10 +14,10 @@ namespace DotNetNuke.Services.Scheduling /// /// ----------------------------------------------------------------------------- public class ScheduleHistorySortStartDate : IComparer - { + { public int Compare(object x, object y) { return ((ScheduleHistoryItem)y).StartDate.CompareTo(((ScheduleHistoryItem)x).StartDate); - } + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs index af52c88f0a2..5a756757d1b 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleItem.cs @@ -13,11 +13,11 @@ namespace DotNetNuke.Services.Scheduling [Serializable] public class ScheduleItem : BaseEntityInfo, IHydratable - { + { private static readonly DateTime MinNextTime = DateTime.Now; private DateTime? _NextStart; - private Hashtable _ScheduleItemSettings; - + private Hashtable _ScheduleItemSettings; + public ScheduleItem() { this.ScheduleID = Null.NullInteger; @@ -35,8 +35,8 @@ public ScheduleItem() this.ProcessGroup = Null.NullInteger; this.Servers = Null.NullString; this.ScheduleStartDate = Null.NullDate; - } - + } + public string AttachToEvent { get; set; } public bool CatchUpEnabled { get; set; } @@ -55,10 +55,10 @@ public virtual DateTime NextStart { this._NextStart = MinNextTime; } - + return this._NextStart.Value > MinNextTime ? this._NextStart.Value : MinNextTime; } - + set { this._NextStart = value; @@ -87,15 +87,15 @@ public virtual DateTime NextStart public ScheduleSource ScheduleSource { get; set; } - public int ThreadID { get; set; } - + public int ThreadID { get; set; } + public int KeyID { get { return this.ScheduleID; } - + set { this.ScheduleID = value; @@ -105,8 +105,8 @@ public int KeyID public virtual void Fill(IDataReader dr) { this.FillInternal(dr); - } - + } + public bool HasObjectDependencies(string strObjectDependencies) { if (strObjectDependencies.IndexOf(",") > -1) @@ -126,10 +126,10 @@ public bool HasObjectDependencies(string strObjectDependencies) { return true; } - + return false; - } - + } + public void AddSetting(string Key, string Value) { this._ScheduleItemSettings.Add(Key, Value); @@ -141,7 +141,7 @@ public virtual string GetSetting(string Key) { this.GetSettings(); } - + if (this._ScheduleItemSettings != null && this._ScheduleItemSettings.ContainsKey(Key)) { return Convert.ToString(this._ScheduleItemSettings[Key]); @@ -181,15 +181,15 @@ protected override void FillInternal(IDataReader dr) { this.NextStart = Null.SetNullDateTime(dr["NextStart"]); } - + if (schema.Select("ColumnName = 'ScheduleStartDate'").Length > 0) { this.ScheduleStartDate = Null.SetNullDateTime(dr["ScheduleStartDate"]); } } - + // Fill BaseEntityInfo base.FillInternal(dr); - } + } } } diff --git a/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs b/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs index 8e77f0c3476..ed206798575 100644 --- a/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs +++ b/DNN Platform/Library/Services/Scheduling/ScheduleStatusSortRemainingTimeDescending.cs @@ -14,10 +14,10 @@ namespace DotNetNuke.Services.Scheduling /// /// ----------------------------------------------------------------------------- public class ScheduleStatusSortRemainingTimeDescending : IComparer - { + { public int Compare(object x, object y) { return ((ScheduleHistoryItem)x).RemainingTime.CompareTo(((ScheduleHistoryItem)y).RemainingTime); - } + } } } diff --git a/DNN Platform/Library/Services/Scheduling/Scheduler.cs b/DNN Platform/Library/Services/Scheduling/Scheduler.cs index 2102667baa0..745c79f5142 100644 --- a/DNN Platform/Library/Services/Scheduling/Scheduler.cs +++ b/DNN Platform/Library/Services/Scheduling/Scheduler.cs @@ -21,14 +21,19 @@ namespace DotNetNuke.Services.Scheduling internal static class Scheduler { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(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; - + + private static readonly SharedList ScheduleQueue; + private static readonly SharedList ScheduleInProgress; + private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(45); + private static readonly ReaderWriterLockSlim StatusLock = new ReaderWriterLockSlim(); + // This is the heart of the scheduler mechanism. // This class manages running new events according // to the schedule. @@ -50,9 +55,6 @@ internal static class CoreScheduler private static int _numberOfProcessGroups; - private static readonly SharedList ScheduleQueue; - private static readonly SharedList ScheduleInProgress; - // This is our array that holds the process group // where our threads will be kicked off. private static ProcessGroup[] _processGroup; @@ -64,8 +66,6 @@ internal static class CoreScheduler // of the ReaderWriter locks. private static int _readerTimeouts; private static int _writerTimeouts; - private static readonly TimeSpan LockTimeout = TimeSpan.FromSeconds(45); - private static readonly ReaderWriterLockSlim StatusLock = new ReaderWriterLockSlim(); private static ScheduleStatus _status = ScheduleStatus.STOPPED; static CoreScheduler() @@ -137,179 +137,6 @@ public static void AddToScheduleQueue(ScheduleHistoryItem scheduleHistoryItem) } } - 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. - /// - /// Item to add. - /// Thread Safe. - private static void AddToScheduleInProgress(ScheduleHistoryItem scheduleHistoryItem) - { - if (!ScheduleInProgressContains(scheduleHistoryItem)) - { - try - { - using (ScheduleInProgress.GetWriteLock(LockTimeout)) - { - if (!ScheduleInProgressContains(scheduleHistoryItem)) - { - ScheduleInProgress.Add(scheduleHistoryItem); - } - } - } - catch (ApplicationException ex) - { - // The writer lock request timed out. - Interlocked.Increment(ref _writerTimeouts); - Exceptions.Exceptions.LogException(ex); - } - } - } - - private static int GetProcessGroup() - { - // return a random process group - var r = new Random(); - return r.Next(0, _numberOfProcessGroups - 1); - } - - private static bool IsInProgress(ScheduleItem scheduleItem) - { - try - { - using (ScheduleInProgress.GetReadLock(LockTimeout)) - { - return ScheduleInProgress.Any(si => si.ScheduleID == scheduleItem.ScheduleID); - } - } - catch (ApplicationException ex) - { - // The reader lock request timed out. - Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - { - Logger.Debug(ex); - } - - return false; - } - } - - /// - /// Removes an item from the collection of schedule items in progress. - /// - /// - /// Thread Safe. - private static void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) - { - try - { - using (ScheduleInProgress.GetWriteLock(LockTimeout)) - { - var item = ScheduleInProgress.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); - if (item != null) - { - ScheduleInProgress.Remove(item); - } - } - } - catch (ApplicationException ex) - { - // The writer lock request timed out. - Interlocked.Increment(ref _writerTimeouts); - Exceptions.Exceptions.LogException(ex); - } - } - - /// - /// Gets a schedulehistory item from the collection of schedule items in progress. - /// - /// - /// Thread Safe. - private static ScheduleHistoryItem GetScheduleItemFromScheduleInProgress(ScheduleItem scheduleItem) - { - try - { - using (ScheduleInProgress.GetWriteLock(LockTimeout)) - { - var item = ScheduleInProgress.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); - return item; - } - } - catch (ApplicationException ex) - { - // The writer lock request timed out. - Interlocked.Increment(ref _writerTimeouts); - Exceptions.Exceptions.LogException(ex); - } - - return null; - } - - private static bool ScheduleInProgressContains(ScheduleHistoryItem scheduleHistoryItem) - { - try - { - using (ScheduleInProgress.GetReadLock(LockTimeout)) - { - return ScheduleInProgress.Any(si => si.ScheduleID == scheduleHistoryItem.ScheduleID); - } - } - catch (ApplicationException ex) - { - Interlocked.Increment(ref _readerTimeouts); - Exceptions.Exceptions.LogException(ex); - return false; - } - } - - private static bool ScheduleQueueContains(ScheduleItem objScheduleItem) - { - try - { - using (ScheduleQueue.GetReadLock(LockTimeout)) - { - return ScheduleQueue.Any(si => si.ScheduleID == objScheduleItem.ScheduleID); - } - } - catch (ApplicationException ex) - { - Interlocked.Increment(ref _readerTimeouts); - Exceptions.Exceptions.LogException(ex); - return false; - } - } - public static void FireEvents() { // This method uses a thread pool to @@ -393,71 +220,6 @@ public static int GetFreeThreadCount() return FreeThreads; } - private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) - { - if (_debug) - { - bool appended = false; - var strDebug = new StringBuilder("Task not run because "); - if (!(scheduleItem.NextStart <= DateTime.Now)) - { - strDebug.Append(" task is scheduled for " + scheduleItem.NextStart); - appended = true; - } - - if (!scheduleItem.Enabled) - { - if (appended) - { - strDebug.Append(" and"); - } - - strDebug.Append(" task is not enabled"); - appended = true; - } - - if (IsInProgress(scheduleItem)) - { - if (appended) - { - strDebug.Append(" and"); - } - - strDebug.Append(" task is already in progress"); - appended = true; - } - - if (HasDependenciesConflict(scheduleItem)) - { - if (appended) - { - strDebug.Append(" and"); - } - - strDebug.Append(" task has conflicting dependency"); - } - - var log = new LogInfo(); - log.AddProperty("EVENT NOT RUN REASON", strDebug.ToString()); - log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); - log.AddProperty("TYPE FULL NAME", scheduleItem.TypeFullName); - log.LogTypeKey = "DEBUG"; - LogController.Instance.AddLog(log); - } - } - - private static void LogEventAddedToProcessGroup(ScheduleItem scheduleItem) - { - if (_debug) - { - var log = new LogInfo(); - log.AddProperty("EVENT ADDED TO PROCESS GROUP " + scheduleItem.ProcessGroup, scheduleItem.TypeFullName); - log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); - log.LogTypeKey = "DEBUG"; - LogController.Instance.AddLog(log); - } - } - public static int GetMaxThreadCount() { return _maxThreadCount; @@ -487,7 +249,7 @@ public static Collection GetScheduleInProgress() Interlocked.Increment(ref _readerTimeouts); Exceptions.Exceptions.LogException(ex); } - + return c; } @@ -511,11 +273,11 @@ public static int GetScheduleInProgressCount() { // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - { - Logger.Debug(ex); - } - + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + return 0; } } @@ -539,7 +301,7 @@ public static Collection GetScheduleQueue() c.Add(item, item.ScheduleID.ToString(), null, null); } } - + return c; } catch (ApplicationException ex) @@ -547,7 +309,7 @@ public static Collection GetScheduleQueue() Interlocked.Increment(ref _readerTimeouts); Exceptions.Exceptions.LogException(ex); } - + return c; } @@ -597,7 +359,7 @@ public static ScheduleStatus GetScheduleStatus() // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); } - + return ScheduleStatus.NOT_SET; } @@ -613,7 +375,7 @@ public static void Halt(string sourceOfHalt) { return; } - + SetScheduleStatus(ScheduleStatus.SHUTTING_DOWN); var log = new LogInfo { LogTypeKey = "SCHEDULER_SHUTTING_DOWN" }; log.AddProperty("Initiator", sourceOfHalt); @@ -629,7 +391,7 @@ public static void Halt(string sourceOfHalt) { return; } - + Thread.Sleep(1000); } @@ -660,11 +422,11 @@ public static bool HasDependenciesConflict(ScheduleItem scheduleItem) { // The reader lock request timed out. Interlocked.Increment(ref _readerTimeouts); - if (Logger.IsDebugEnabled) - { - Logger.Debug(ex); - } - + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + return false; } } @@ -673,11 +435,11 @@ public static void LoadQueueFromEvent(EventName eventName) { var executingServer = ServerController.GetExecutingServerName(); List schedule = SchedulingController.GetScheduleByEvent(eventName.ToString(), executingServer); - if (Logger.IsDebugEnabled) - { - Logger.Debug("loadqueue executingServer:" + executingServer); - } - + if (Logger.IsDebugEnabled) + { + Logger.Debug("loadqueue executingServer:" + executingServer); + } + var thisServer = GetServer(executingServer); if (thisServer == null) { @@ -694,7 +456,7 @@ public static void LoadQueueFromEvent(EventName eventName) { scheduleItem.Servers = serverGroupServers; } - + var historyItem = new ScheduleHistoryItem(scheduleItem); if (!IsInQueue(historyItem) && @@ -713,11 +475,11 @@ public static void LoadQueueFromTimer() _forceReloadSchedule = false; var executingServer = ServerController.GetExecutingServerName(); List schedule = SchedulingController.GetSchedule(executingServer); - if (Logger.IsDebugEnabled) - { - Logger.Debug("LoadQueueFromTimer executingServer:" + executingServer); - } - + if (Logger.IsDebugEnabled) + { + Logger.Debug("LoadQueueFromTimer executingServer:" + executingServer); + } + var thisServer = GetServer(executingServer); if (thisServer == null) { @@ -727,7 +489,7 @@ public static void LoadQueueFromTimer() bool runningInAGroup = !string.IsNullOrEmpty(thisServer.ServerGroup); var serverGroupServers = ServerGroupServers(thisServer); - + foreach (ScheduleItem scheduleItem in schedule) { if (runningInAGroup && string.IsNullOrEmpty(scheduleItem.Servers)) @@ -750,7 +512,7 @@ public static void LoadQueueFromTimer() { historyItem.ScheduleSource = ScheduleSource.STARTED_FROM_BEGIN_REQUEST; } - + AddToScheduleQueue(historyItem); } } @@ -766,13 +528,6 @@ 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. /// @@ -823,7 +578,7 @@ public static void RunEventSchedule(EventName eventName) { FireEvents(); } - + if (_writerTimeouts > 20 || _readerTimeouts > 20) { // Wait for 10 minutes so we don't fill up the logs @@ -901,11 +656,11 @@ public static void Start() { if (Common.Globals.ElapsedSinceAppStart.TotalSeconds < SchedulingProvider.DelayAtAppStart) { - if (!KeepThreadAlive) - { - return; - } - + if (!KeepThreadAlive) + { + return; + } + Thread.Sleep(1000); continue; } @@ -918,7 +673,7 @@ public static void Start() { SetScheduleStatus(ScheduleStatus.RUNNING_REQUEST_SCHEDULE); } - + // Load the queue to determine which schedule // items need to be run. LoadQueueFromTimer(); @@ -936,7 +691,7 @@ public static void Start() // not sure why R# thinks it is always false // ReSharper disable ConditionIsAlwaysTrueOrFalse while (FreeThreads > 0 && !refreshQueueSchedule && KeepRunning && !_forceReloadSchedule) - + // ReSharper restore ConditionIsAlwaysTrueOrFalse { // Fire off the events that need running. @@ -955,12 +710,12 @@ public static void Start() { FireEvents(); } - + if (KeepThreadAlive == false) { return; } - + if (_writerTimeouts > 20 || _readerTimeouts > 20) { // Some kind of deadlock on a resource. @@ -1014,7 +769,7 @@ public static void Start() catch (Exception exc) { Exceptions.Exceptions.ProcessSchedulerException(exc); - + // sleep for 10 minutes Thread.Sleep(600000); } @@ -1030,7 +785,7 @@ public static void Start() { SetScheduleStatus(ScheduleStatus.WAITING_FOR_REQUEST); } - + if (SchedulingProvider.SchedulerMode != SchedulerMode.REQUEST_METHOD || _debug) { var log = new LogInfo { LogTypeKey = "SCHEDULER_STOPPED" }; @@ -1143,7 +898,7 @@ public static void WorkCompleted(SchedulerClient schedulerClient) scheduleHistoryItem.ProcessGroup = -1; AddToScheduleQueue(scheduleHistoryItem); } - + if (schedulerClient.ScheduleHistoryItem.RetainHistoryNum > 0) { var log = new LogInfo { LogTypeKey = "SCHEDULER_EVENT_COMPLETED" }; @@ -1181,7 +936,7 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio // A SchedulerClient is notifying us that their // process has errored. Decrease our ActiveThreadCount Interlocked.Decrement(ref _activeThreadCount); - + Exceptions.Exceptions.ProcessSchedulerException(exception); // Update the schedule item object property @@ -1218,7 +973,7 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio break; } } - + // Update the ScheduleHistory in the database UpdateScheduleHistory(scheduleHistoryItem); @@ -1243,7 +998,7 @@ public static void WorkErrored(ScheduleHistoryItem scheduleHistoryItem, Exceptio { log.AddProperty("EXCEPTION", exception.Message); } - + log.AddProperty("RESCHEDULED FOR", Convert.ToString(scheduleHistoryItem.NextStart)); log.AddProperty("SOURCE", scheduleHistoryItem.ScheduleSource.ToString()); log.AddProperty("ACTIVE THREADS", _activeThreadCount.ToString()); @@ -1342,7 +1097,7 @@ public static void WorkStarted(ScheduleHistoryItem scheduleHistoryItem) { Interlocked.Decrement(ref _activeThreadCount); } - + Exceptions.Exceptions.ProcessSchedulerException(exc); } } @@ -1358,7 +1113,7 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis var scheduleHistoryItem = GetScheduleItemFromScheduleInProgress(scheduleItem); scheduleHistoryItem.ScheduleHistoryID = runningscheduleHistoryItem.ScheduleHistoryID; scheduleHistoryItem.StartDate = runningscheduleHistoryItem.StartDate; - + // Remove the object in the ScheduleInProgress collection RemoveFromScheduleInProgress(scheduleHistoryItem); @@ -1445,10 +1200,10 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis } } } - + // Update the ScheduleHistory in the database UpdateScheduleHistory(scheduleHistoryItem); - + if (scheduleHistoryItem.NextStart != Null.NullDate) { // Put the object back into the ScheduleQueue @@ -1475,6 +1230,37 @@ public static void StopScheduleInProgress(ScheduleItem scheduleItem, ScheduleHis } } + 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; + } + } + internal static void InitializeThreadPool(bool boolDebug, int maxThreads) { _debug = boolDebug; @@ -1487,7 +1273,7 @@ internal static void InitializeThreadPool(bool boolDebug, int maxThreads) { maxThreads = 1; } - + _numberOfProcessGroups = maxThreads; _maxThreadCount = maxThreads; for (int i = 0; i < _numberOfProcessGroups; i++) @@ -1498,6 +1284,220 @@ internal static void InitializeThreadPool(bool boolDebug, int maxThreads) } } } + + /// + /// adds an item to the collection of schedule items in progress. + /// + /// Item to add. + /// Thread Safe. + private static void AddToScheduleInProgress(ScheduleHistoryItem scheduleHistoryItem) + { + if (!ScheduleInProgressContains(scheduleHistoryItem)) + { + try + { + using (ScheduleInProgress.GetWriteLock(LockTimeout)) + { + if (!ScheduleInProgressContains(scheduleHistoryItem)) + { + ScheduleInProgress.Add(scheduleHistoryItem); + } + } + } + catch (ApplicationException ex) + { + // The writer lock request timed out. + Interlocked.Increment(ref _writerTimeouts); + Exceptions.Exceptions.LogException(ex); + } + } + } + + private static int GetProcessGroup() + { + // return a random process group + var r = new Random(); + return r.Next(0, _numberOfProcessGroups - 1); + } + + private static bool IsInProgress(ScheduleItem scheduleItem) + { + try + { + using (ScheduleInProgress.GetReadLock(LockTimeout)) + { + return ScheduleInProgress.Any(si => si.ScheduleID == scheduleItem.ScheduleID); + } + } + catch (ApplicationException ex) + { + // The reader lock request timed out. + Interlocked.Increment(ref _readerTimeouts); + if (Logger.IsDebugEnabled) + { + Logger.Debug(ex); + } + + return false; + } + } + + /// + /// Removes an item from the collection of schedule items in progress. + /// + /// + /// Thread Safe. + private static void RemoveFromScheduleInProgress(ScheduleItem scheduleItem) + { + try + { + using (ScheduleInProgress.GetWriteLock(LockTimeout)) + { + var item = ScheduleInProgress.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); + if (item != null) + { + ScheduleInProgress.Remove(item); + } + } + } + catch (ApplicationException ex) + { + // The writer lock request timed out. + Interlocked.Increment(ref _writerTimeouts); + Exceptions.Exceptions.LogException(ex); + } + } + + /// + /// Gets a schedulehistory item from the collection of schedule items in progress. + /// + /// + /// Thread Safe. + private static ScheduleHistoryItem GetScheduleItemFromScheduleInProgress(ScheduleItem scheduleItem) + { + try + { + using (ScheduleInProgress.GetWriteLock(LockTimeout)) + { + var item = ScheduleInProgress.FirstOrDefault(si => si.ScheduleID == scheduleItem.ScheduleID); + return item; + } + } + catch (ApplicationException ex) + { + // The writer lock request timed out. + Interlocked.Increment(ref _writerTimeouts); + Exceptions.Exceptions.LogException(ex); + } + + return null; + } + + private static bool ScheduleInProgressContains(ScheduleHistoryItem scheduleHistoryItem) + { + try + { + using (ScheduleInProgress.GetReadLock(LockTimeout)) + { + return ScheduleInProgress.Any(si => si.ScheduleID == scheduleHistoryItem.ScheduleID); + } + } + catch (ApplicationException ex) + { + Interlocked.Increment(ref _readerTimeouts); + Exceptions.Exceptions.LogException(ex); + return false; + } + } + + private static bool ScheduleQueueContains(ScheduleItem objScheduleItem) + { + try + { + using (ScheduleQueue.GetReadLock(LockTimeout)) + { + return ScheduleQueue.Any(si => si.ScheduleID == objScheduleItem.ScheduleID); + } + } + catch (ApplicationException ex) + { + Interlocked.Increment(ref _readerTimeouts); + Exceptions.Exceptions.LogException(ex); + return false; + } + } + + private static void LogWhyTaskNotRun(ScheduleItem scheduleItem) + { + if (_debug) + { + bool appended = false; + var strDebug = new StringBuilder("Task not run because "); + if (!(scheduleItem.NextStart <= DateTime.Now)) + { + strDebug.Append(" task is scheduled for " + scheduleItem.NextStart); + appended = true; + } + + if (!scheduleItem.Enabled) + { + if (appended) + { + strDebug.Append(" and"); + } + + strDebug.Append(" task is not enabled"); + appended = true; + } + + if (IsInProgress(scheduleItem)) + { + if (appended) + { + strDebug.Append(" and"); + } + + strDebug.Append(" task is already in progress"); + appended = true; + } + + if (HasDependenciesConflict(scheduleItem)) + { + if (appended) + { + strDebug.Append(" and"); + } + + strDebug.Append(" task has conflicting dependency"); + } + + var log = new LogInfo(); + log.AddProperty("EVENT NOT RUN REASON", strDebug.ToString()); + log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); + log.AddProperty("TYPE FULL NAME", scheduleItem.TypeFullName); + log.LogTypeKey = "DEBUG"; + LogController.Instance.AddLog(log); + } + } + + private static void LogEventAddedToProcessGroup(ScheduleItem scheduleItem) + { + if (_debug) + { + var log = new LogInfo(); + log.AddProperty("EVENT ADDED TO PROCESS GROUP " + scheduleItem.ProcessGroup, scheduleItem.TypeFullName); + log.AddProperty("SCHEDULE ID", scheduleItem.ScheduleID.ToString()); + log.LogTypeKey = "DEBUG"; + LogController.Instance.AddLog(log); + } + } + + 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) + ","); + } } } } diff --git a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs index e8fc213f58c..f0f69ad4f04 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulerClient.cs @@ -23,18 +23,12 @@ public SchedulerClient() } public event WorkStarted ProcessStarted; - - public event WorkProgressing ProcessProgressing; - - public event WorkCompleted ProcessCompleted; - - public ScheduleHistoryItem ScheduleHistoryItem { get; set; } - public string SchedulerEventGUID { get; set; } + public event WorkProgressing ProcessProgressing; - public string aProcessMethod { get; set; } + public event WorkCompleted ProcessCompleted; - public string Status { get; set; } + public event WorkErrored ProcessErrored; public int ThreadID { @@ -43,8 +37,14 @@ public int ThreadID return Thread.CurrentThread.ManagedThreadId; } } - - public event WorkErrored ProcessErrored; + + public ScheduleHistoryItem ScheduleHistoryItem { get; set; } + + public string SchedulerEventGUID { get; set; } + + public string aProcessMethod { get; set; } + + public string Status { get; set; } public void Started() { diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs index 48285323b48..57573c6b51c 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingController.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingController.cs @@ -24,7 +24,7 @@ public class SchedulingController public static int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName) { - return AddSchedule( + return AddSchedule( TypeFullName, TimeLapse, TimeLapseMeasurement, @@ -39,12 +39,12 @@ public static int AddSchedule(string TypeFullName, int TimeLapse, string TimeLap FriendlyName, DateTime.Now); } - + public static int AddSchedule(string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName, DateTime ScheduleStartDate) { EventLogController.Instance.AddLog("TypeFullName", TypeFullName, PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.SCHEDULE_CREATED); - return DataProvider.Instance().AddSchedule( + return DataProvider.Instance().AddSchedule( TypeFullName, TimeLapse, TimeLapseMeasurement, @@ -74,7 +74,7 @@ public static void AddScheduleItemSetting(int ScheduleID, string Name, string Va public static void DeleteSchedule(int ScheduleID) { DataProvider.Instance().DeleteSchedule(ScheduleID); - EventLogController.Instance.AddLog( + EventLogController.Instance.AddLog( "ScheduleID", ScheduleID.ToString(), PortalController.Instance.GetCurrentPortalSettings(), @@ -142,7 +142,7 @@ public static Hashtable GetScheduleItemSettings(int ScheduleID) h.Add(r["SettingName"], r["SettingValue"]); } } - + return h; } @@ -174,7 +174,7 @@ public static void ReloadSchedule() public static void UpdateSchedule(ScheduleItem scheduleItem) { #pragma warning disable 618 - UpdateSchedule( + UpdateSchedule( scheduleItem.ScheduleID, scheduleItem.TypeFullName, scheduleItem.TimeLapse, @@ -196,7 +196,7 @@ public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeL string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName) { #pragma warning disable 618 - UpdateSchedule( + UpdateSchedule( ScheduleID, TypeFullName, TimeLapse, @@ -218,7 +218,7 @@ public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeL public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeLapse, string TimeLapseMeasurement, int RetryTimeLapse, string RetryTimeLapseMeasurement, int RetainHistoryNum, string AttachToEvent, bool CatchUpEnabled, bool Enabled, string ObjectDependencies, string Servers, string FriendlyName, DateTime ScheduleStartDate) { - DataProvider.Instance().UpdateSchedule( + DataProvider.Instance().UpdateSchedule( ScheduleID, TypeFullName, TimeLapse, @@ -239,7 +239,7 @@ public static void UpdateSchedule(int ScheduleID, string TypeFullName, int TimeL public static void UpdateScheduleHistory(ScheduleHistoryItem objScheduleHistoryItem) { - DataProvider.Instance().UpdateScheduleHistory( + DataProvider.Instance().UpdateScheduleHistory( objScheduleHistoryItem.ScheduleHistoryID, objScheduleHistoryItem.EndDate, objScheduleHistoryItem.Succeeded, @@ -254,7 +254,7 @@ public static bool CanRunOnThisServer(string servers) { lwrServers = servers.ToLowerInvariant(); } - + if (string.IsNullOrEmpty(lwrServers) || lwrServers.Contains(Globals.ServerName.ToLowerInvariant())) { return true; diff --git a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs index b0fd2d1cc2a..0d659c4c5dd 100644 --- a/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs +++ b/DNN Platform/Library/Services/Scheduling/SchedulingProvider.cs @@ -86,7 +86,7 @@ protected SchedulingProvider() { value = 1; } - + MaxThreads = value; // if (!settings.TryGetValue("delayAtAppStart", out str) || !int.TryParse(str, out value)) @@ -116,16 +116,6 @@ protected SchedulingProvider() } } - /// - /// Gets the number of seconds since application start where no timer-initiated - /// schedulers are allowed to run before. This safeguards against ovelapped - /// application re-starts. See "Disable Ovelapped Recycling" under Recycling - /// of IIS Manager Application Pool's Advanced Settings. - /// - public static int DelayAtAppStart { get; private set; } - - public static bool Debug { get; private set; } - public static bool Enabled { get @@ -134,8 +124,6 @@ public static bool Enabled } } - public static int MaxThreads { get; private set; } - public static bool ReadyForPoll { get @@ -144,6 +132,26 @@ public static bool ReadyForPoll } } + public static SchedulerMode SchedulerMode + { + get + { + return Host.SchedulerMode; + } + } + + /// + /// Gets the number of seconds since application start where no timer-initiated + /// schedulers are allowed to run before. This safeguards against ovelapped + /// application re-starts. See "Disable Ovelapped Recycling" under Recycling + /// of IIS Manager Application Pool's Advanced Settings. + /// + public static int DelayAtAppStart { get; private set; } + + public static bool Debug { get; private set; } + + public static int MaxThreads { get; private set; } + public static DateTime ScheduleLastPolled { get @@ -151,7 +159,7 @@ public static DateTime ScheduleLastPolled return DataCache.GetCache("ScheduleLastPolled") != null ? (DateTime)DataCache.GetCache("ScheduleLastPolled") : DateTime.MinValue; } - + set { var nextScheduledTask = Instance().GetNextScheduledTask(ServerController.GetExecutingServerName()); @@ -161,16 +169,6 @@ public static DateTime ScheduleLastPolled } } - public string ProviderPath { get; private set; } - - public static SchedulerMode SchedulerMode - { - get - { - return Host.SchedulerMode; - } - } - public virtual Dictionary Settings { get @@ -179,11 +177,13 @@ public virtual Dictionary Settings } } + public string ProviderPath { get; private set; } + public static SchedulingProvider Instance() { return ComponentFactory.GetComponent(); } - + public abstract void Start(); public abstract void ExecuteTasks(); @@ -238,12 +238,12 @@ public virtual void RunScheduleItemNow(ScheduleItem scheduleItem) { // Do Nothing } - + public virtual void RunScheduleItemNow(ScheduleItem scheduleItem, bool runNow) { // Do Nothing } - + public abstract void RemoveFromScheduleInProgress(ScheduleItem scheduleItem); } } diff --git a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs index b7da74f764d..458eeff8edf 100644 --- a/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/BaseResultController.cs @@ -14,12 +14,12 @@ namespace DotNetNuke.Services.Search.Controllers /// The abstract methods in this Class will be called by Search Result engine for every Hit found in Search Index. [Serializable] public abstract class BaseResultController - { + { /// /// Gets the localized search type name. /// - public virtual string LocalizedSearchTypeName => string.Empty; - + public virtual string LocalizedSearchTypeName => string.Empty; + /// /// Does the user in the Context have View Permission on the Document. /// diff --git a/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs b/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs index e4be421b391..93df2658b78 100644 --- a/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/ISearchController.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.Services.Search.Controllers using DotNetNuke.Services.Search.Entities; public interface ISearchController - { + { /// /// Get Search Result for the searchQuery at the Site Level. /// @@ -22,6 +22,6 @@ public interface ISearchController /// SearchQuery object with various search criteria. /// SearchResults. /// SearchTypeIds provided in the searchQuery will be ignored. - SearchResults ModuleSearch(SearchQuery searchQuery); + SearchResults ModuleSearch(SearchQuery searchQuery); } } diff --git a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs index 3ac5f12c07d..1a020bd0450 100644 --- a/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Controllers/SearchControllerImpl.cs @@ -28,11 +28,11 @@ namespace DotNetNuke.Services.Search.Controllers ///
    /// ----------------------------------------------------------------------------- internal class SearchControllerImpl : ISearchController - { + { private const string SeacrchContollersCacheKey = "SearchControllers"; - private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - + private readonly int _moduleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; + public SearchResults SiteSearch(SearchQuery searchQuery) { var results = this.GetResults(searchQuery); @@ -44,17 +44,17 @@ public SearchResults ModuleSearch(SearchQuery searchQuery) searchQuery.SearchTypeIds = new List { this._moduleSearchTypeId }; 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; - } - + if (field.StringValue == null) + { + continue; + } + int intField; switch (field.Name) { @@ -84,56 +84,56 @@ private static void FillTagsValues(Document doc, SearchResult result) result.Url = field.StringValue; break; case Constants.SearchTypeTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.SearchTypeId = intField; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.SearchTypeId = intField; + } + break; case Constants.ModuleIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.ModuleId = intField; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleId = intField; + } + break; case Constants.ModuleDefIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.ModuleDefId = intField; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.ModuleDefId = intField; + } + break; case Constants.PortalIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.PortalId = intField; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.PortalId = intField; + } + break; case Constants.AuthorIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.AuthorUserId = intField; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.AuthorUserId = intField; + } + break; case Constants.RoleIdTag: - if (int.TryParse(field.StringValue, out intField)) - { - result.RoleId = intField; - } - + 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; - } - + if (int.TryParse(field.StringValue, out intField)) + { + result.TabId = intField; + } + break; case Constants.ModifiedTimeTag: DateTime modifiedTimeUtc; @@ -146,21 +146,21 @@ private static void FillTagsValues(Document doc, SearchResult result) 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); - } + 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); - } + if (!result.Keywords.ContainsKey(key)) + { + result.Keywords.Add(key, field.StringValue); + } } - + break; } } @@ -170,59 +170,75 @@ private static string GetSnippet(SearchResult searchResult, LuceneResult luceneR { 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 + "..."); - } - + 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; - } - + if (string.IsNullOrEmpty(snippet)) + { + snippet = searchResult.Title; + } + return snippet; } - + + 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; + } + private Tuple> GetResults(SearchQuery searchQuery) { Requires.NotNull("Query", searchQuery); Requires.PropertyNotEqualTo("searchQuery", "SearchTypeIds", searchQuery.SearchTypeIds.Count(), 0); - if ((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(this._moduleSearchTypeId))) - { - throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustHaveSearchTypeIdForModule", "ModuleId based search must have SearchTypeId for a module only")); - } - + if ((searchQuery.ModuleId > 0) && (searchQuery.SearchTypeIds.Count() > 1 || !searchQuery.SearchTypeIds.Contains(this._moduleSearchTypeId))) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustHaveSearchTypeIdForModule", "ModuleId based search must have SearchTypeId for a module only")); + } + if (searchQuery.SortField == SortFields.CustomStringField || searchQuery.SortField == SortFields.CustomNumericField - || searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword) - { - Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField); + || searchQuery.SortField == SortFields.NumericKey || searchQuery.SortField == SortFields.Keyword) + { + Requires.NotNullOrEmpty("CustomSortField", searchQuery.CustomSortField); } var query = new BooleanQuery(); @@ -232,7 +248,7 @@ private Tuple> GetResults(SearchQuery searchQuery) { var allowLeadingWildcard = HostController.Instance.GetString("Search_AllowLeadingWildcard", "N") == "Y" || searchQuery.AllowLeadingWildcard; var keywords = SearchHelper.Instance.RephraseSearchText(searchQuery.KeyWords, searchQuery.WildCardSearch, allowLeadingWildcard); - + // don't use stemming analyzer for exact matches or non-analyzed fields (e.g. Tags) var analyzer = LuceneController.Instance.GetCustomAnalyzer() ?? new SearchQueryAnalyzer(true); var nonStemmerAnalyzer = new SearchQueryAnalyzer(false); @@ -245,7 +261,7 @@ private Tuple> GetResults(SearchQuery searchQuery) var parsedQueryContent = parserContent.Parse(keywords); keywordQuery.Add(parsedQueryContent, Occur.SHOULD); } - + query.Add(keywordQuery, Occur.MUST); } catch (Exception) @@ -262,12 +278,12 @@ private Tuple> GetResults(SearchQuery searchQuery) { portalIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.PortalIdTag, portalId, portalId, true, true), Occur.SHOULD); } - - if (searchQuery.PortalIds.Any()) - { - query.Add(portalIdQuery, Occur.MUST); - } - + + if (searchQuery.PortalIds.Any()) + { + query.Add(portalIdQuery, Occur.MUST); + } + this.ApplySearchTypeIdFilter(query, searchQuery); if (searchQuery.BeginModifiedTimeUtc > DateTime.MinValue && searchQuery.EndModifiedTimeUtc >= searchQuery.BeginModifiedTimeUtc) @@ -275,11 +291,11 @@ private Tuple> GetResults(SearchQuery searchQuery) query.Add(NumericRangeQuery.NewLongRange(Constants.ModifiedTimeTag, long.Parse(searchQuery.BeginModifiedTimeUtc.ToString(Constants.DateTimeFormat)), long.Parse(searchQuery.EndModifiedTimeUtc.ToString(Constants.DateTimeFormat)), true, true), Occur.MUST); } - if (searchQuery.RoleId > 0) - { - query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST); - } - + if (searchQuery.RoleId > 0) + { + query.Add(NumericRangeQuery.NewIntRange(Constants.RoleIdTag, searchQuery.RoleId, searchQuery.RoleId, true, true), Occur.MUST); + } + foreach (var tag in searchQuery.Tags) { var text = tag.ToLowerInvariant(); @@ -287,13 +303,13 @@ private Tuple> GetResults(SearchQuery searchQuery) { text = System.Net.WebUtility.HtmlDecode(text); } - + query.Add(new TermQuery(new Term(Constants.Tag, text)), Occur.MUST); } foreach (var kvp in searchQuery.CustomKeywords) { - query.Add( + query.Add( new TermQuery(new Term( SearchHelper.Instance.StripTagsNoAttributes(Constants.KeywordsPrefixTag + kvp.Key, true), kvp.Value)), Occur.MUST); } @@ -383,11 +399,11 @@ private void ApplySearchTypeIdFilter(BooleanQuery query, SearchQuery searchQuery { modDefQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD); } - - if (searchQuery.ModuleDefIds.Any()) - { - query.Add(modDefQuery, Occur.MUST); // Note the MUST - } + + if (searchQuery.ModuleDefIds.Any()) + { + query.Add(modDefQuery, Occur.MUST); // Note the MUST + } } query.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, this._moduleSearchTypeId, this._moduleSearchTypeId, true, true), Occur.MUST); @@ -398,23 +414,23 @@ 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)) { searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.ModuleDefIdTag, moduleDefId, moduleDefId, true, true), Occur.SHOULD); - } - - if (!searchQuery.ModuleDefIds.Any()) - { - searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); - } + } + + if (!searchQuery.ModuleDefIds.Any()) + { + searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); + } } else { searchTypeIdQuery.Add(NumericRangeQuery.NewIntRange(Constants.SearchTypeTag, searchTypeId, searchTypeId, true, true), Occur.SHOULD); } } - + query.Add(searchTypeIdQuery, Occur.MUST); } } @@ -447,22 +463,6 @@ private SearchResult GetSearchResultFromLuceneResult(LuceneResult luceneResult) return 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; - } - private Dictionary GetSearchResultControllers() { var cachArg = new CacheItemArgs(SeacrchContollersCacheKey, 120, CacheItemPriority.Default); @@ -502,11 +502,11 @@ 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; diff --git a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs index 2d644ad3cbb..2aa069dc142 100644 --- a/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/TabResultController.cs @@ -21,10 +21,10 @@ namespace DotNetNuke.Services.Search.Controllers [Serializable] public class TabResultController : BaseResultController { - private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_tab", LocalizedResxFile); - public override string LocalizedSearchTypeName => Localization.GetString("Crawler_tab", LocalizedResxFile); - public override bool HasViewPermission(SearchResult searchResult) { var viewable = true; diff --git a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs index 0ebb532542d..a46252dbe68 100644 --- a/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs +++ b/DNN Platform/Library/Services/Search/Controllers/UserResultController.cs @@ -24,17 +24,17 @@ namespace DotNetNuke.Services.Search.Controllers [Serializable] public class UserResultController : BaseResultController { - private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; - + private const string LocalizedResxFile = "~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx"; + private static readonly Regex SearchResultMatchRegex = new Regex(@"^(\d+)_", RegexOptions.Compiled); - public override string LocalizedSearchTypeName => Localization.GetString("Crawler_user", LocalizedResxFile); - + public override string LocalizedSearchTypeName => Localization.GetString("Crawler_user", LocalizedResxFile); + private PortalSettings PortalSettings { get { return PortalController.Instance.GetCurrentPortalSettings(); } - } - + } + public override bool HasViewPermission(SearchResult searchResult) { var userId = GetUserId(searchResult); @@ -102,8 +102,8 @@ 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) { if (string.IsNullOrEmpty(extendedVisibility)) @@ -140,7 +140,7 @@ private bool HasSocialReplationship(UserInfo targetUser, UserInfo accessingUser, break; } } - + // Groups/Roles if (profileVisibility.RoleVisibilities.Any(role => accessingUser.IsInRole(role.RoleName))) { diff --git a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs index 46bdccfd6d3..a03b485258c 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocument.cs @@ -17,8 +17,8 @@ public SearchDocument() { this.Tags = new string[0]; this.IsActive = true; - } - + } + /// /// Gets or sets content's Title. /// @@ -74,8 +74,8 @@ public SearchDocument() /// /// Gets or sets tags can be specified as additional information. /// - public IEnumerable Tags { get; set; } - + public IEnumerable Tags { get; set; } + 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 6e1f650d079..c66c7875ce3 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchDocumentToDelete.cs @@ -28,7 +28,7 @@ public SearchDocumentToDelete() this.TabId = this.AuthorUserId = 0; } - + /// /// Gets or sets a key to uniquely identify a document in the Index. /// diff --git a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs index 0f1853fbc06..756b274e4c6 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchQuery.cs @@ -27,8 +27,8 @@ public SearchQuery() 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. /// @@ -169,6 +169,6 @@ public SearchQuery() /// Gets or sets a value indicating whether set this to true to allow search in word. /// /// 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 bool AllowLeadingWildcard { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs index 5f345cd2d0f..22feefa7d81 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResult.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResult.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Services.Search.Entities [Serializable] public class SearchResult : SearchDocument { - /// + /// /// Initializes a new instance of the class. /// Empty Constructor. /// @@ -28,14 +28,14 @@ public SearchResult() this.Keywords = new Dictionary(); this.SearchContext = new Dictionary(); } - + /// /// Gets time when Content was last modified (in friendly format). /// - public string DisplayModifiedTime - { - get { return DateUtils.CalculateDateForDisplay(this.ModifiedTimeUtc); } - } + public string DisplayModifiedTime + { + get { return DateUtils.CalculateDateForDisplay(this.ModifiedTimeUtc); } + } /// /// Gets or sets highlighted snippet from document. @@ -64,6 +64,6 @@ public string DisplayModifiedTime /// Gets or sets context information such as the type of module that initiated the search can be stored here. /// This is key-value pair, e.g. "SearchSource","SiteSearch" /// - public IDictionary SearchContext { get; set; } + public IDictionary SearchContext { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs index c1a48fe5e0d..9071f328955 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchResults.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchResults.cs @@ -18,7 +18,7 @@ public SearchResults() { this.Results = new List(); } - + /// /// Gets or sets total Hits found in Lucene. /// diff --git a/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs b/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs index 18fa95bf5e3..5e363f1335a 100644 --- a/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs +++ b/DNN Platform/Library/Services/Search/Entities/SearchStopWords.cs @@ -10,19 +10,19 @@ namespace DotNetNuke.Services.Search.Entities public class SearchStopWords { public int StopWordsId { get; set; } - + public string StopWords { get; set; } - + public int CreatedByUserId { get; set; } - + public int LastModifiedByUserId { get; set; } - + public DateTime CreatedOnDate { get; set; } - + public DateTime LastModifiedOnDate { get; set; } - + public int PortalId { get; set; } - + public string CultureCode { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs b/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs index 6dcec0c897f..79cbfa8978c 100644 --- a/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs +++ b/DNN Platform/Library/Services/Search/Entities/SynonymsGroup.cs @@ -10,17 +10,17 @@ namespace DotNetNuke.Services.Search.Entities public class SynonymsGroup { public int SynonymsGroupId { get; set; } - + public string SynonymsTags { get; set; } - + public int CreatedByUserId { get; set; } - + public int LastModifiedByUserId { get; set; } - + public DateTime CreatedOnDate { get; set; } - + public DateTime LastModifiedOnDate { get; set; } - + public int PortalId { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/IndexingProvider.cs b/DNN Platform/Library/Services/Search/IndexingProvider.cs index 9f54a30f30b..c3b673b2404 100644 --- a/DNN Platform/Library/Services/Search/IndexingProvider.cs +++ b/DNN Platform/Library/Services/Search/IndexingProvider.cs @@ -18,13 +18,13 @@ 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. /// A delegate function to send the collection of documents to for saving/indexing. /// The number of documents indexed. - public virtual int IndexSearchDocuments( + public virtual int IndexSearchDocuments( int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { diff --git a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs index a97022931fc..7a6fae1b7a2 100644 --- a/DNN Platform/Library/Services/Search/IndexingProviderBase.cs +++ b/DNN Platform/Library/Services/Search/IndexingProviderBase.cs @@ -17,13 +17,13 @@ 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. /// A delegate function to send the collection of documents to for saving/indexing. /// The number of documents indexed. - public abstract int IndexSearchDocuments( + public abstract int IndexSearchDocuments( int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer); @@ -34,9 +34,9 @@ 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 virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) - { - return new SearchItemInfoCollection(); + public virtual SearchItemInfoCollection GetSearchIndexItems(int portalId) + { + return new SearchItemInfoCollection(); } /// Retrieves the date/time of the last item to be indexed. diff --git a/DNN Platform/Library/Services/Search/Internals/Constants.cs b/DNN Platform/Library/Services/Search/Internals/Constants.cs index 81642b88dd1..a25dd2ea371 100644 --- a/DNN Platform/Library/Services/Search/Internals/Constants.cs +++ b/DNN Platform/Library/Services/Search/Internals/Constants.cs @@ -52,8 +52,6 @@ internal static class Constants // 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; @@ -72,21 +70,6 @@ internal static class Constants // 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 = - { - TitleTag, - Tag, - DescriptionTag, - BodyTag, - ContentTag, - KeywordsPrefixTag + TitleTag, - KeywordsPrefixTag + SubjectTag, - KeywordsPrefixTag + CommentsTag, - KeywordsPrefixTag + AuthorNameTag, - }; internal const int MaximumMinLen = 10; internal const int MinimumMaxLen = 10; @@ -105,5 +88,22 @@ internal static class Constants // misc. internal const string TlsSearchInfo = "TLS_SEARCH_INFO"; - } + + internal static Version LuceneVersion = Version.LUCENE_30; + internal static readonly string[] FieldsNeedAnalysis = { TitleTag, SubjectTag, CommentsTag, AuthorNameTag, StatusTag, CategoryTag }; + + internal static readonly string[] KeyWordSearchFields = + { + TitleTag, + Tag, + DescriptionTag, + BodyTag, + ContentTag, + KeywordsPrefixTag + TitleTag, + KeywordsPrefixTag + SubjectTag, + KeywordsPrefixTag + CommentsTag, + KeywordsPrefixTag + AuthorNameTag, + }; + + } } diff --git a/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs b/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs index 13e5f397bf8..986b107d494 100644 --- a/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs +++ b/DNN Platform/Library/Services/Search/Internals/IInternalSearchController.cs @@ -16,7 +16,7 @@ public interface IInternalSearchController { /// /// Get a List of Search Content Source that participate in Search. - /// + /// /// IEnumerable GetSearchContentSourceList(int portalId); @@ -32,10 +32,10 @@ public interface IInternalSearchController /// SearchTypeId is used primarily to obtain this value. Multiple SearchTypeId can map to same Display Name, /// e.g. Tab, Module, Html/Module all map to Pages. /// For SearchTypeId=module, ModuleDefitionId is also used. Module's display name is used unless an entry is found in - /// ~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx for the Module_[MODULENAME].txt is found. + /// ~/DesktopModules/Admin/SearchResults/App_LocalResources/SearchableModules.resx for the Module_[MODULENAME].txt is found. /// - string GetSearchDocumentTypeDisplayName(SearchResult searchResult); - + string GetSearchDocumentTypeDisplayName(SearchResult searchResult); + /// /// Add a Search Document to Search Index. /// @@ -88,6 +88,6 @@ public interface IInternalSearchController /// does not interfere with ongoing search activities. /// /// True is optimization was scheduled to run in the background, false otherwise. - bool OptimizeSearchIndex(); + bool OptimizeSearchIndex(); } } diff --git a/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs b/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs index d9338e6bc2c..67e95389130 100644 --- a/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs +++ b/DNN Platform/Library/Services/Search/Internals/ISearchHelper.cs @@ -13,12 +13,12 @@ namespace DotNetNuke.Services.Search.Internals /// This is an Internal interface and should not be used outside of Core. /// public interface ISearchHelper - { - // /// - // /// Commits the added search documents into the search database - // /// - // void Commit(); - + { + // /// + // /// Commits the added search documents into the search database + // /// + // void Commit(); + /// /// Returns a list of SearchTypes defined in the system. /// @@ -29,8 +29,8 @@ public interface ISearchHelper /// Gets a SearchType Item for the given name. /// /// - SearchType GetSearchTypeByName(string searchTypeName); - + SearchType GetSearchTypeByName(string searchTypeName); + /// /// Returns a list of Synonyms for a given word. E.g. leap, hop for jump. /// @@ -72,8 +72,8 @@ public interface ISearchHelper /// /// /// culture code. - void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode); - + void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode); + /// /// Gets a search stop words. /// @@ -107,36 +107,36 @@ public interface ISearchHelper /// /// /// - void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode); - + void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode); + DateTime GetSearchReindexRequestTime(int portalId); - + DateTime SetSearchReindexRequestTime(int portalId); - + bool GetSearchCompactFlag(); - + void SetSearchReindexRequestTime(bool turnOn); - + bool IsReindexRequested(int portalId, DateTime startDate); - + IEnumerable GetPortalsToReindex(DateTime startDate); - + DateTime GetLastSuccessfulIndexingDateTime(int scheduleId); - + void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDateLocal); DateTime GetIndexerCheckpointUtcTime(int scheduleId, string indexerKey); - + void SetIndexerCheckpointUtcTime(int scheduleId, string indexerKey, DateTime lastUtcTime); string GetIndexerCheckpointData(int scheduleId, string indexerKey); - - void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData); - + + void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData); + Tuple GetSearchMinMaxLength(); - + string RephraseSearchText(string searchPhrase, bool useWildCard, bool allowLeadingWildcard = false); - - string StripTagsNoAttributes(string html, bool retainSpace); + + string StripTagsNoAttributes(string html, bool retainSpace); } } diff --git a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs index fc820ea17a1..68324397883 100644 --- a/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/InternalSearchControllerImpl.cs @@ -40,28 +40,28 @@ internal class InternalSearchControllerImpl : IInternalSearchController { 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 ILog Logger = LoggerSource.Instance.GetLogger(typeof(InternalSearchControllerImpl)); 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 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); + 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 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() { var hostController = HostController.Instance; @@ -70,7 +70,7 @@ public InternalSearchControllerImpl() this._contentBoost = hostController.GetInteger(Constants.SearchContentBoostSetting, Constants.DefaultSearchKeywordBoost); this._descriptionBoost = hostController.GetInteger(Constants.SearchDescriptionBoostSetting, Constants.DefaultSearchDescriptionBoost); this._authorBoost = hostController.GetInteger(Constants.SearchAuthorBoostSetting, Constants.DefaultSearchAuthorBoost); - } + } public IEnumerable GetSearchContentSourceList(int portalId) { @@ -92,13 +92,90 @@ public string GetSearchDocumentTypeDisplayName(SearchResult searchResult) 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); } - + + public void AddSearchDocuments(IEnumerable searchDocuments) + { + var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); + if (searchDocs.Any()) + { + 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); + } + } + + // 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.DeleteSearchDocumentInternal(searchDocument, false); + } + + 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(); + } + + public bool OptimizeSearchIndex() + { + // run optimization in background + return LuceneController.Instance.OptimizeSearchIndex(true); + } + + public SearchStatistics GetSearchStatistics() + { + return LuceneController.Instance.GetSearchStatistics(); + } + internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) { var searchTypes = CBO.FillCollection(DataProvider.GetAllSearchTypes()); @@ -118,10 +195,10 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) foreach (ModuleInfo module in modules) { - if (!modDefIds.Contains(module.ModuleDefID)) - { - modDefIds.Add(module.ModuleDefID); - } + if (!modDefIds.Contains(module.ModuleDefID)) + { + modDefIds.Add(module.ModuleDefID); + } } var list = modDefIds.Select(ModuleDefinitionController.GetModuleDefinitionByID).ToList(); @@ -133,7 +210,7 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) { text = def.FriendlyName; } - + var result = new SearchContentSource { SearchTypeId = crawler.SearchTypeId, @@ -169,60 +246,96 @@ internal virtual object SearchContentSourceCallback(CacheItemArgs cacheItem) return results; } - private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) + private static Query NumericValueQuery(string numericName, int numericVal) { - var data = new Dictionary(); - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); + } + + /// + /// Add Field to Doc when supplied fieldValue > 0. + /// + private static void AddIntField(Document doc, int fieldValue, string fieldTag) + { + if (fieldValue > 0) { - var searchContentSources = this.GetSearchContentSourceList(portal.PortalID); - foreach (var searchContentSource in searchContentSources) - { - var key = string.Format("{0}-{1}", searchContentSource.SearchTypeId, searchContentSource.ModuleDefinitionId); - if (!data.ContainsKey(key)) - { - data.Add(key, searchContentSource.LocalizedName); - } - } + doc.Add(new NumericField(fieldTag, Field.Store.YES, true).SetIntValue(fieldValue)); } - - return data; } - public void AddSearchDocuments(IEnumerable searchDocuments) + private static string StripTagsRetainAttributes(string html, IEnumerable attributes, bool decoded, bool retainSpace) { - var searchDocs = searchDocuments as IList ?? searchDocuments.ToList(); - if (searchDocs.Any()) + var attributesList = attributes as IList ?? attributes.ToList(); + var strippedString = html; + var emptySpace = retainSpace ? " " : string.Empty; + + if (!string.IsNullOrEmpty(strippedString)) { - const int commitBatchSize = 1024 * 16; - var idx = 0; - - // var added = false; - foreach (var searchDoc in searchDocs) + // Remove all opening HTML Tags with no attributes + strippedString = StripOpeningTagsRegex.Replace(strippedString, emptySpace); + + // Remove all closing HTML Tags + strippedString = StripClosingTagsRegex.Replace(strippedString, emptySpace); + } + + if (!string.IsNullOrEmpty(strippedString)) + { + var list = new List(); + + foreach (var match in HtmlTagsRegex.Matches(strippedString).Cast()) { - try + var captures = match.Groups["attr"].Captures; + foreach (var capture in captures.Cast()) { - this.AddSearchDocumentInternal(searchDoc, (++idx % commitBatchSize) == 0); - - // added = true; + var val = capture.Value.Trim(); + var pos = val.IndexOf('='); + if (pos > 0) + { + var attr = val.Substring(0, pos).Trim(); + if (attributesList.Contains(attr)) + { + var text = AttrTextRegex.Match(val).Groups["text"].Value.Trim(); + if (text.Length > 0 && !list.Contains(text)) + { + list.Add(text); + } + } + } } - catch (Exception ex) + + if (list.Count > 0) { - Logger.ErrorFormat("Search Document error: {0}{1}{2}", searchDoc, Environment.NewLine, ex); + strippedString = strippedString.Replace(match.ToString(), string.Join(" ", list)); + list.Clear(); } } + } - // 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(); - // } + // If not decoded, decode and strip again. Becareful with recursive + if (!decoded) + { + strippedString = StripTagsRetainAttributes(HttpUtility.HtmlDecode(strippedString), attributesList, true, retainSpace); } + + return strippedString; } - public void DeleteSearchDocument(SearchDocument searchDocument) + private object SearchDocumentTypeDisplayNameCallBack(CacheItemArgs cacheItem) { - this.DeleteSearchDocumentInternal(searchDocument, false); + var data = new Dictionary(); + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + var searchContentSources = this.GetSearchContentSourceList(portal.PortalID); + foreach (var searchContentSource in searchContentSources) + { + var key = string.Format("{0}-{1}", searchContentSource.SearchTypeId, searchContentSource.ModuleDefinitionId); + if (!data.ContainsKey(key)) + { + data.Add(key, searchContentSource.LocalizedName); + } + } + } + + return data; } private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) @@ -235,27 +348,27 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC if (searchDocument.SearchTypeId == this._moduleSearchTypeId) { - if (searchDocument.ModuleDefId <= 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdMustBeGreaterThanZero", "ModuleDefId must be greater than zero when SearchTypeId is for a module")); - } - - if (searchDocument.ModuleId <= 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustBeGreaterThanZero", "ModuleId must be greater than zero when SearchTypeId is for a module")); - } + if (searchDocument.ModuleDefId <= 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdMustBeGreaterThanZero", "ModuleDefId must be greater than zero when SearchTypeId is for a module")); + } + + if (searchDocument.ModuleId <= 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdMustBeGreaterThanZero", "ModuleId must be greater than zero when SearchTypeId is for a module")); + } } else { - if (searchDocument.ModuleDefId > 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdWhenSearchTypeForModule", "ModuleDefId is needed only when SearchTypeId is for a module")); - } - - if (searchDocument.ModuleId > 0) - { - throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdWhenSearchTypeForModule", "ModuleId is needed only when SearchTypeId is for a module")); - } + if (searchDocument.ModuleDefId > 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleDefIdWhenSearchTypeForModule", "ModuleDefId is needed only when SearchTypeId is for a module")); + } + + if (searchDocument.ModuleId > 0) + { + throw new ArgumentException(Localization.GetExceptionMessage("ModuleIdWhenSearchTypeForModule", "ModuleId is needed only when SearchTypeId is for a module")); + } } var doc = new Document(); @@ -275,7 +388,7 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC // Generic and Additional SearchDocument Params this.AddSearchDocumentParamters(doc, searchDocument, sb); - + // Remove the existing document from Lucene this.DeleteSearchDocumentInternal(searchDocument, false); @@ -299,124 +412,68 @@ private void AddSearchDocumentInternal(SearchDocument searchDocument, bool autoC } } - public void DeleteSearchDocumentsByModule(int portalId, int moduleId, int moduleDefId) + private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) { - Requires.NotNegative("PortalId", portalId); + var query = new BooleanQuery(); - this.DeleteSearchDocument(new SearchDocument + if (searchDocument.SearchTypeId > -1) { - PortalId = portalId, - ModuleId = moduleId, - ModuleDefId = moduleDefId, - SearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId, - }); - } + query.Add(NumericValueQuery(Constants.SearchTypeTag, searchDocument.SearchTypeId), Occur.MUST); + } - public void DeleteAllDocuments(int portalId, int searchTypeId) - { - Requires.NotNegative("SearchTypeId", searchTypeId); + if (searchDocument.PortalId > -1) + { + query.Add(NumericValueQuery(Constants.PortalIdTag, searchDocument.PortalId), Occur.MUST); + } - this.DeleteSearchDocument(new SearchDocument + if (searchDocument.RoleId > -1) { - PortalId = portalId, - SearchTypeId = searchTypeId, - }); - } + query.Add(NumericValueQuery(Constants.RoleIdTag, searchDocument.RoleId), Occur.MUST); + } - private static Query NumericValueQuery(string numericName, int numericVal) - { - return NumericRangeQuery.NewIntRange(numericName, numericVal, numericVal, true, true); - } + if (searchDocument.ModuleDefId > 0) + { + query.Add(NumericValueQuery(Constants.ModuleDefIdTag, searchDocument.ModuleDefId), Occur.MUST); + } - private void DeleteSearchDocumentInternal(SearchDocument searchDocument, bool autoCommit) - { - var query = new BooleanQuery(); + if (searchDocument.ModuleId > 0) + { + query.Add(NumericValueQuery(Constants.ModuleIdTag, searchDocument.ModuleId), Occur.MUST); + } - if (searchDocument.SearchTypeId > -1) - { - query.Add(NumericValueQuery(Constants.SearchTypeTag, searchDocument.SearchTypeId), Occur.MUST); - } - - if (searchDocument.PortalId > -1) - { - query.Add(NumericValueQuery(Constants.PortalIdTag, searchDocument.PortalId), Occur.MUST); - } - - if (searchDocument.RoleId > -1) - { - query.Add(NumericValueQuery(Constants.RoleIdTag, searchDocument.RoleId), Occur.MUST); - } - - if (searchDocument.ModuleDefId > 0) - { - query.Add(NumericValueQuery(Constants.ModuleDefIdTag, searchDocument.ModuleDefId), Occur.MUST); - } - - if (searchDocument.ModuleId > 0) - { - query.Add(NumericValueQuery(Constants.ModuleIdTag, searchDocument.ModuleId), Occur.MUST); - } - - if (searchDocument.TabId > 0) - { - query.Add(NumericValueQuery(Constants.TabIdTag, searchDocument.TabId), Occur.MUST); - } - - if (searchDocument.AuthorUserId > 0) - { - query.Add(NumericValueQuery(Constants.AuthorIdTag, searchDocument.AuthorUserId), Occur.MUST); - } - - if (!string.IsNullOrEmpty(searchDocument.UniqueKey)) - { - query.Add(new TermQuery(new Term(Constants.UniqueKeyTag, searchDocument.UniqueKey)), Occur.MUST); - } - - if (!string.IsNullOrEmpty(searchDocument.QueryString)) - { - query.Add(new TermQuery(new Term(Constants.QueryStringTag, searchDocument.QueryString)), Occur.MUST); - } - - if (!string.IsNullOrEmpty(searchDocument.CultureCode)) - { - query.Add(NumericValueQuery(Constants.LocaleTag, Localization.GetCultureLanguageID(searchDocument.CultureCode)), Occur.MUST); - } - - LuceneController.Instance.Delete(query); + if (searchDocument.TabId > 0) + { + query.Add(NumericValueQuery(Constants.TabIdTag, searchDocument.TabId), Occur.MUST); + } - if (autoCommit) + if (searchDocument.AuthorUserId > 0) { - this.Commit(); + query.Add(NumericValueQuery(Constants.AuthorIdTag, searchDocument.AuthorUserId), Occur.MUST); } - } - public void Commit() - { - LuceneController.Instance.Commit(); - } + if (!string.IsNullOrEmpty(searchDocument.UniqueKey)) + { + query.Add(new TermQuery(new Term(Constants.UniqueKeyTag, searchDocument.UniqueKey)), Occur.MUST); + } - public bool OptimizeSearchIndex() - { - // run optimization in background - return LuceneController.Instance.OptimizeSearchIndex(true); - } + if (!string.IsNullOrEmpty(searchDocument.QueryString)) + { + query.Add(new TermQuery(new Term(Constants.QueryStringTag, searchDocument.QueryString)), Occur.MUST); + } - public SearchStatistics GetSearchStatistics() - { - return LuceneController.Instance.GetSearchStatistics(); - } + if (!string.IsNullOrEmpty(searchDocument.CultureCode)) + { + query.Add(NumericValueQuery(Constants.LocaleTag, Localization.GetCultureLanguageID(searchDocument.CultureCode)), Occur.MUST); + } - /// - /// 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)); - } + LuceneController.Instance.Delete(query); + + if (autoCommit) + { + this.Commit(); + } } - + private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocument, StringBuilder sb) { // mandatory fields @@ -430,22 +487,22 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum if (!string.IsNullOrEmpty(searchDocument.Title)) { var field = new Field(Constants.TitleTag, StripTagsRetainAttributes(searchDocument.Title, HtmlAttributesToRetain, false, true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (this._titleBoost > 0 && this._titleBoost != Constants.StandardLuceneBoost) - { - field.Boost = this._titleBoost / 10f; - } - + if (this._titleBoost > 0 && this._titleBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._titleBoost / 10f; + } + doc.Add(field); } if (!string.IsNullOrEmpty(searchDocument.Description)) { var field = new Field(Constants.DescriptionTag, StripTagsRetainAttributes(searchDocument.Description, HtmlAttributesToRetain, false, true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (this._descriptionBoost > 0 && this._descriptionBoost != Constants.StandardLuceneBoost) - { - field.Boost = this._descriptionBoost / 10f; - } - + if (this._descriptionBoost > 0 && this._descriptionBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._descriptionBoost / 10f; + } + doc.Add(field); } @@ -476,28 +533,28 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum { field.Boost = this._titleBoost / 10f; } - + break; case Constants.SubjectTag: if (this._contentBoost > 0 && this._contentBoost != Constants.StandardLuceneBoost) { field.Boost = this._contentBoost / 10f; } - + break; case Constants.CommentsTag: if (this._descriptionBoost > 0 && this._descriptionBoost != Constants.StandardLuceneBoost) { field.Boost = this._descriptionBoost / 10f; } - + break; case Constants.AuthorNameTag: if (this._authorBoost > 0 && this._authorBoost != Constants.StandardLuceneBoost) { field.Boost = this._authorBoost / 10f; } - + break; } @@ -522,7 +579,7 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum tagBoostApplied = true; } } - + doc.Add(field); } @@ -538,11 +595,11 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum if (user != null && !string.IsNullOrEmpty(user.DisplayName)) { var field = new Field(Constants.AuthorNameTag, user.DisplayName, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); - if (this._authorBoost > 0 && this._authorBoost != Constants.StandardLuceneBoost) - { - field.Boost = this._authorBoost / 10f; - } - + if (this._authorBoost > 0 && this._authorBoost != Constants.StandardLuceneBoost) + { + field.Boost = this._authorBoost / 10f; + } + doc.Add(field); } } @@ -558,68 +615,11 @@ private void AddSearchDocumentParamters(Document doc, SearchDocument searchDocum { var field = new Field(Constants.ContentTag, SearchHelper.Instance.StripTagsNoAttributes(sb.ToString(), true), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS); doc.Add(field); - if (this._contentBoost > 0 && this._contentBoost != Constants.StandardLuceneBoost) - { - field.Boost = this._contentBoost / 10f; - } - } - } - - private static string StripTagsRetainAttributes(string html, IEnumerable attributes, bool decoded, bool retainSpace) - { - var attributesList = attributes as IList ?? attributes.ToList(); - var strippedString = html; - var emptySpace = retainSpace ? " " : string.Empty; - - if (!string.IsNullOrEmpty(strippedString)) - { - // Remove all opening HTML Tags with no attributes - strippedString = StripOpeningTagsRegex.Replace(strippedString, emptySpace); - - // Remove all closing HTML Tags - strippedString = StripClosingTagsRegex.Replace(strippedString, emptySpace); - } - - if (!string.IsNullOrEmpty(strippedString)) - { - var list = new List(); - - foreach (var match in HtmlTagsRegex.Matches(strippedString).Cast()) + if (this._contentBoost > 0 && this._contentBoost != Constants.StandardLuceneBoost) { - var captures = match.Groups["attr"].Captures; - foreach (var capture in captures.Cast()) - { - var val = capture.Value.Trim(); - var pos = val.IndexOf('='); - if (pos > 0) - { - var attr = val.Substring(0, pos).Trim(); - if (attributesList.Contains(attr)) - { - var text = AttrTextRegex.Match(val).Groups["text"].Value.Trim(); - if (text.Length > 0 && !list.Contains(text)) - { - list.Add(text); - } - } - } - } - - if (list.Count > 0) - { - strippedString = strippedString.Replace(match.ToString(), string.Join(" ", list)); - list.Clear(); - } + field.Boost = this._contentBoost / 10f; } } - - // If not decoded, decode and strip again. Becareful with recursive - if (!decoded) - { - strippedString = StripTagsRetainAttributes(HttpUtility.HtmlDecode(strippedString), attributesList, true, retainSpace); - } - - return strippedString; - } + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs index 39e82eccba2..02a2d1ec59a 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneControllerImpl.cs @@ -34,51 +34,51 @@ 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"; private const int DefaultSearchRetryTimes = 5; private const int DISPOSED = 1; - private const int UNDISPOSED = 0; + 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)); - private IndexWriter _writer; - private IndexReader _idxReader; - private CachedReader _reader; + private const string HtmlPreTag = ""; + private const string HtmlPostTag = ""; - internal string IndexFolder { get; private set; } - private FastVectorHighlighter _fastHighlighter; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(LuceneControllerImpl)); private readonly object _writerLock = new object(); private readonly double _readerTimeSpan; // in seconds private readonly int _searchRetryTimes; // search retry times if exception thrown during search process private readonly List _oldReaders = new List(); - private int _isDisposed = UNDISPOSED; - private const string HtmlPreTag = ""; - private const string HtmlPostTag = ""; + private IndexWriter _writer; + private IndexReader _idxReader; + private CachedReader _reader; + private FastVectorHighlighter _fastHighlighter; + private int _isDisposed = UNDISPOSED; private DateTime _lastReadTimeUtc; private DateTime _lastDirModifyTimeUtc; - + public LuceneControllerImpl() { var hostController = HostController.Instance; var folder = hostController.GetString(Constants.SearchIndexFolderKey, DefaultSearchFolder); - if (string.IsNullOrEmpty(folder)) - { - folder = DefaultSearchFolder; - } - + if (string.IsNullOrEmpty(folder)) + { + folder = DefaultSearchFolder; + } + this.IndexFolder = Path.Combine(Globals.ApplicationMapPath, folder); this._readerTimeSpan = hostController.GetDouble(Constants.SearchReaderRefreshTimeKey, DefaultRereadTimeSpan); this._searchRetryTimes = hostController.GetInteger(Constants.SearchRetryTimesKey, DefaultSearchRetryTimes); } - + + internal string IndexFolder { get; private set; } + private IndexWriter Writer { get @@ -109,7 +109,7 @@ private IndexWriter Writer } this.CheckDisposed(); - var writer = new IndexWriter( + var writer = new IndexWriter( FSDirectory.Open(this.IndexFolder), this.GetCustomAnalyzer() ?? new SynonymAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); this._idxReader = writer.GetReader(); @@ -118,7 +118,7 @@ private IndexWriter Writer } } } - + return this._writer; } } @@ -133,60 +133,6 @@ private bool MustRereadIndex } } - // made internal to be used in unit tests only; otherwise could be made private - internal IndexSearcher GetSearcher() - { - if (this._reader == null || this.MustRereadIndex) - { - this.CheckValidIndexFolder(); - this.UpdateLastAccessTimes(); - this.InstantiateReader(); - } - - 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; - if (this._idxReader != null) - { - // use the Reopen() method for better near-realtime when the _writer ins't null - var newReader = this._idxReader.Reopen(); - if (this._idxReader != newReader) - { - // _idxReader.Dispose(); -- will get disposed upon disposing the searcher - Interlocked.Exchange(ref this._idxReader, newReader); - } - - searcher = new IndexSearcher(this._idxReader); - } - else - { - // Note: disposing the IndexSearcher instance obtained from the next - // statement will not close the underlying reader on dispose. - searcher = new IndexSearcher(FSDirectory.Open(this.IndexFolder)); - } - - var reader = new CachedReader(searcher); - var cutoffTime = DateTime.Now - TimeSpan.FromSeconds(this._readerTimeSpan * 10); - lock (((ICollection)this._oldReaders).SyncRoot) - { - this.CheckDisposed(); - this._oldReaders.RemoveAll(r => r.LastUsed <= cutoffTime); - this._oldReaders.Add(reader); - Interlocked.Exchange(ref this._reader, reader); - } - } - private FastVectorHighlighter FastHighlighter { get @@ -198,11 +144,11 @@ private FastVectorHighlighter FastHighlighter new[] { HighlightPreTag }, new[] { HighlightPostTag }); this._fastHighlighter = new FastVectorHighlighter(true, true, fragListBuilder, fragmentBuilder); } - + return this._fastHighlighter; } - } - + } + public LuceneResults Search(LuceneSearchContext searchContext) { Requires.NotNull("LuceneQuery", searchContext.LuceneQuery); @@ -246,11 +192,11 @@ public LuceneResults Search(LuceneSearchContext searchContext) } // Page doesn't exist - if (luceneResults.TotalHits < minResults) - { - break; - } - + if (luceneResults.TotalHits < minResults) + { + break; + } + luceneResults.Results = searchSecurityTrimmer.ScoreDocs.Select(match => new LuceneResult { @@ -312,85 +258,6 @@ public void Delete(Query query) this.Writer.DeleteDocuments(query); } - private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, IEnumerable scoreDocs, IndexSearcher searcher) - { - var sb = new StringBuilder(); - sb.AppendLine("Query: " + luceneQuery.Query.ToString()); - foreach (var match in scoreDocs) - { - var explanation = searcher.Explain(luceneQuery.Query, match.Doc); - sb.AppendLine("-------------------"); - var doc = searcher.Doc(match.Doc); - sb.AppendLine(doc.Get(Constants.TitleTag)); - sb.AppendLine(explanation.ToString()); - } - - 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(). - /// - private string GetDisplayScoreFromMatch(string match) - { - var displayScore = string.Empty; - if (!string.IsNullOrEmpty(match)) - { - var beginPos = match.IndexOf('['); - var endPos = match.LastIndexOf(']'); - if (beginPos > 0 && endPos > 0 && endPos > beginPos) - { - displayScore = match.Substring(beginPos + 1, endPos - beginPos - 1); - } - } - - return displayScore; - } - public void Commit() { if (this._writer != null) @@ -418,7 +285,7 @@ public bool OptimizeSearchIndex(bool doWait) } this.CheckDisposed(); - + // optimize down to "> 1 segments" for better performance than down to 1 this._writer.Optimize(4, doWait); @@ -464,14 +331,14 @@ 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, }; } @@ -518,6 +385,139 @@ public Analyzer GetCustomAnalyzer() return analyzer; } + // made internal to be used in unit tests only; otherwise could be made private + internal IndexSearcher GetSearcher() + { + if (this._reader == null || this.MustRereadIndex) + { + this.CheckValidIndexFolder(); + this.UpdateLastAccessTimes(); + this.InstantiateReader(); + } + + return this._reader.GetSearcher(); + } + + private static StringBuilder GetSearcResultExplanation(LuceneQuery luceneQuery, IEnumerable scoreDocs, IndexSearcher searcher) + { + var sb = new StringBuilder(); + sb.AppendLine("Query: " + luceneQuery.Query.ToString()); + foreach (var match in scoreDocs) + { + var explanation = searcher.Explain(luceneQuery.Query, match.Doc); + sb.AppendLine("-------------------"); + var doc = searcher.Doc(match.Doc); + sb.AppendLine(doc.Get(Constants.TitleTag)); + sb.AppendLine(explanation.ToString()); + } + + return sb; + } + + 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; + if (this._idxReader != null) + { + // use the Reopen() method for better near-realtime when the _writer ins't null + var newReader = this._idxReader.Reopen(); + if (this._idxReader != newReader) + { + // _idxReader.Dispose(); -- will get disposed upon disposing the searcher + Interlocked.Exchange(ref this._idxReader, newReader); + } + + searcher = new IndexSearcher(this._idxReader); + } + else + { + // Note: disposing the IndexSearcher instance obtained from the next + // statement will not close the underlying reader on dispose. + searcher = new IndexSearcher(FSDirectory.Open(this.IndexFolder)); + } + + var reader = new CachedReader(searcher); + var cutoffTime = DateTime.Now - TimeSpan.FromSeconds(this._readerTimeSpan * 10); + lock (((ICollection)this._oldReaders).SyncRoot) + { + this.CheckDisposed(); + this._oldReaders.RemoveAll(r => r.LastUsed <= cutoffTime); + this._oldReaders.Add(reader); + Interlocked.Exchange(ref this._reader, reader); + } + } + + 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(). + /// + private string GetDisplayScoreFromMatch(string match) + { + var displayScore = string.Empty; + if (!string.IsNullOrEmpty(match)) + { + var beginPos = match.IndexOf('['); + var endPos = match.LastIndexOf(']'); + if (beginPos > 0 && endPos > 0 && endPos > beginPos) + { + displayScore = match.Substring(beginPos + 1, endPos - beginPos - 1); + } + } + + return displayScore; + } + private void DisposeWriter(bool commit = true) { if (this._writer != null) @@ -549,7 +549,7 @@ private void DisposeReaders() { rdr.Dispose(); } - + this._oldReaders.Clear(); this._reader = null; } @@ -564,7 +564,7 @@ public CachedReader(IndexSearcher searcher) this._searcher = searcher; this.UpdateLastUsed(); } - + public DateTime LastUsed { get; private set; } public IndexSearcher GetSearcher() diff --git a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs index fc0fbc1964d..5c03d877884 100644 --- a/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs +++ b/DNN Platform/Library/Services/Search/Internals/LuceneQuery.cs @@ -21,8 +21,8 @@ public LuceneQuery() this.BodySnippetLength = 100; this.PageSize = 10; this.Sort = Sort.RELEVANCE; - } - + } + /// /// Gets or sets lucene's original Query Object. /// @@ -51,6 +51,6 @@ public LuceneQuery() /// /// Gets or sets maximum length of highlighted title field in the results. /// - public int BodySnippetLength { get; set; } + public int BodySnippetLength { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs index 11e3c31b1a3..b0d68276407 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchHelperImpl.cs @@ -35,12 +35,12 @@ internal class SearchHelperImpl : ISearchHelper private const string LastIndexKeyFormat = "{0}_{1}"; private const string SearchStopWordsCacheKey = "SearchStopWords"; private const string ResourceFileRelativePathWithoutExt = "/App_GlobalResources/GlobalResources"; - private readonly IList _emptySynonums = new List(0); - + private readonly IList _emptySynonums = new List(0); + public IEnumerable GetSearchTypes() { var cachArg = new CacheItemArgs(SearchTypesCacheKey, 120, CacheItemPriority.Default); - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( cachArg, dataArgs => { @@ -51,7 +51,7 @@ public IEnumerable GetSearchTypes() public SearchType GetSearchTypeByName(string searchTypeName) { return this.GetSearchTypes().Single(t => t.SearchTypeName == searchTypeName); - } + } public IEnumerable GetSynonyms(int portalId, string cultureCode, string term) { @@ -61,7 +61,7 @@ public IEnumerable GetSynonyms(int portalId, string cultureCode, string { synonyms = this._emptySynonums; } - + return synonyms; } @@ -71,44 +71,37 @@ 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) { duplicateWord = null; - if (string.IsNullOrEmpty(synonymsTags)) - { - return 0; - } - - if (portalId < 0) - { - return 0; - } - + if (string.IsNullOrEmpty(synonymsTags)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + var userId = PortalSettings.Current.UserId; var list = this.GetSynonymsGroups(portalId, cultureCode); var tags = synonymsTags.ToLowerInvariant().Split(','); - if (!tags.Any()) - { - return 0; - } - + if (!tags.Any()) + { + return 0; + } + foreach (var group in list) { var groupTags = group.SynonymsTags.ToLowerInvariant().Split(','); duplicateWord = tags.FirstOrDefault(groupTags.Contains); - if (!string.IsNullOrEmpty(duplicateWord)) - { - return 0; - } + if (!string.IsNullOrEmpty(duplicateWord)) + { + return 0; + } } var newId = DataProvider.Instance().AddSynonymsGroup(synonymsTags, userId, portalId, cultureCode); @@ -124,35 +117,35 @@ public int AddSynonymsGroup(string synonymsTags, int portalId, string cultureCod public int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int portalId, string cultureCode, out string duplicateWord) { duplicateWord = null; - if (synonymsGroupId <= 0) - { - return 0; - } - - if (string.IsNullOrEmpty(synonymsTags)) - { - return 0; - } - + if (synonymsGroupId <= 0) + { + return 0; + } + + if (string.IsNullOrEmpty(synonymsTags)) + { + return 0; + } + var userId = PortalSettings.Current.UserId; var list = this.GetSynonymsGroups(portalId, cultureCode); var tags = synonymsTags.ToLowerInvariant().Split(','); - if (!tags.Any()) - { - return 0; - } - + if (!tags.Any()) + { + return 0; + } + foreach (var group in list) { if (group.SynonymsGroupId != synonymsGroupId) { var groupTags = group.SynonymsTags.ToLowerInvariant().Split(','); duplicateWord = tags.FirstOrDefault(groupTags.Contains); - if (!string.IsNullOrEmpty(duplicateWord)) - { - return 0; - } + if (!string.IsNullOrEmpty(duplicateWord)) + { + return 0; + } } } @@ -167,11 +160,11 @@ public int UpdateSynonymsGroup(int synonymsGroupId, string synonymsTags, int por public void DeleteSynonymsGroup(int synonymsGroupId, int portalId, string cultureCode) { - if (synonymsGroupId <= 0) - { - return; - } - + if (synonymsGroupId <= 0) + { + return; + } + DataProvider.Instance().DeleteSynonymsGroup(synonymsGroupId); var cacheKey = string.Format(CacheKeyFormat, SynonymGroupsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); @@ -190,27 +183,27 @@ public SearchStopWords GetSearchStopWords(int portalId, string cultureCode) public int AddSearchStopWords(string stopWords, int portalId, string cultureCode) { - if (string.IsNullOrEmpty(stopWords)) - { - return 0; - } - - if (portalId < 0) - { - return 0; - } - - if (string.IsNullOrEmpty(cultureCode)) - { - return 0; - } - + if (string.IsNullOrEmpty(stopWords)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + return 0; + } + var tags = stopWords.ToLowerInvariant().Split(','); - if (!tags.Any()) - { - return 0; - } - + if (!tags.Any()) + { + return 0; + } + var userId = PortalSettings.Current.UserId; var newId = DataProvider.Instance().AddSearchStopWords(stopWords, userId, portalId, cultureCode); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); @@ -220,32 +213,32 @@ public int AddSearchStopWords(string stopWords, int portalId, string cultureCode public int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId, string cultureCode) { - if (string.IsNullOrEmpty(stopWords)) - { - return 0; - } - - if (portalId < 0) - { - return 0; - } - - if (stopWordsId <= 0) - { - return 0; - } - - if (string.IsNullOrEmpty(cultureCode)) - { - return 0; - } - + if (string.IsNullOrEmpty(stopWords)) + { + return 0; + } + + if (portalId < 0) + { + return 0; + } + + if (stopWordsId <= 0) + { + return 0; + } + + if (string.IsNullOrEmpty(cultureCode)) + { + return 0; + } + var tags = stopWords.ToLowerInvariant().Split(','); - if (!tags.Any()) - { - return 0; - } - + if (!tags.Any()) + { + return 0; + } + var userId = PortalSettings.Current.UserId; DataProvider.Instance().UpdateSearchStopWords(stopWordsId, stopWords, userId); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); @@ -255,16 +248,16 @@ public int UpdateSearchStopWords(int stopWordsId, string stopWords, int portalId public void DeleteSearchStopWords(int stopWordsId, int portalId, string cultureCode) { - if (stopWordsId <= 0) - { - return; - } - + if (stopWordsId <= 0) + { + return; + } + DataProvider.Instance().DeleteSearchStopWords(stopWordsId); var cacheKey = string.Format(CacheKeyFormat, SearchStopWordsCacheKey, portalId, cultureCode); DataCache.ClearCache(cacheKey); - } - + } + public DateTime GetSearchReindexRequestTime(int portalId) { var requestedOn = SqlDateTime.MinValue.Value; @@ -312,7 +305,7 @@ public void SetSearchReindexRequestTime(bool turnOn) /// /// Determines whether there was a request to re-index the site since a specific date/time. - /// + /// /// public bool IsReindexRequested(int portalId, DateTime startDate) { @@ -344,7 +337,7 @@ public IEnumerable GetPortalsToReindex(DateTime startDate) /// Returns the last time search indexing was completed successfully. /// The returned value in local server time (not UTC). /// Beware that the value stored in teh database is converted to UTC time. - /// + /// /// public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) { @@ -364,10 +357,10 @@ public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) { // retrieves the date as UTC but returns to caller as local lastTime = FixSqlDateTime(lastTime).ToLocalTime().ToLocalTime(); - if (lastTime > DateTime.Now) - { - lastTime = DateTime.Now; - } + if (lastTime > DateTime.Now) + { + lastTime = DateTime.Now; + } } else { @@ -384,7 +377,7 @@ public DateTime GetLastSuccessfulIndexingDateTime(int scheduleId) /// public void SetLastSuccessfulIndexingDateTime(int scheduleId, DateTime startDateLocal) { - SchedulingProvider.Instance().AddScheduleItemSetting( + SchedulingProvider.Instance().AddScheduleItemSetting( scheduleId, Constants.SearchLastSuccessIndexName, startDateLocal.ToUniversalTime().ToString(Constants.ReindexDateTimeFormat)); } @@ -422,34 +415,34 @@ public string GetIndexerCheckpointData(int scheduleId, string indexerKey) public void SetIndexerCheckpointData(int scheduleId, string indexerKey, string checkPointData) { SchedulingProvider.Instance().AddScheduleItemSetting(scheduleId, indexerKey, checkPointData); - } - + } + public Tuple GetSearchMinMaxLength() { var hostController = HostController.Instance; var minWordLength = hostController.GetInteger(Constants.SearchMinLengthKey, Constants.DefaultMinLen); var maxWordLength = hostController.GetInteger(Constants.SearchMaxLengthKey, Constants.DefaultMaxLen); - if (minWordLength < Constants.MinimumMinLen) - { - minWordLength = Constants.MinimumMinLen; - } - - if (maxWordLength < Constants.MinimumMaxLen) - { - maxWordLength = Constants.MinimumMaxLen; - } - - if (minWordLength > Constants.MaximumMinLen) - { - minWordLength = Constants.MaximumMinLen; - } - - if (maxWordLength > Constants.MaximumMaxLen) - { - maxWordLength = Constants.MaximumMaxLen; - } - + if (minWordLength < Constants.MinimumMinLen) + { + minWordLength = Constants.MinimumMinLen; + } + + if (maxWordLength < Constants.MinimumMaxLen) + { + maxWordLength = Constants.MinimumMaxLen; + } + + if (minWordLength > Constants.MaximumMinLen) + { + minWordLength = Constants.MaximumMinLen; + } + + if (maxWordLength > Constants.MaximumMaxLen) + { + maxWordLength = Constants.MaximumMaxLen; + } + if (minWordLength > maxWordLength) { var exceptionMessage = Localization.GetExceptionMessage("SearchAnalyzerMinWordLength", "Search Analyzer: min word length ({0}) is greater than max word length ({1}) value"); @@ -494,7 +487,7 @@ public string RephraseSearchText(string searchPhrase, bool useWildCard, bool all newPhraseBulder.Append(currentWord + " "); currentWord.Clear(); } - + break; case ' ': if (!insideQuote && useWildCard) @@ -503,7 +496,7 @@ public string RephraseSearchText(string searchPhrase, bool useWildCard, bool all newPhraseBulder.Append(this.FixLastWord(currentWord.ToString().Trim(), allowLeadingWildcard) + " "); currentWord.Clear(); } - + break; } } @@ -534,29 +527,36 @@ public string StripTagsNoAttributes(string html, bool retainSpace) strippedString = !string.IsNullOrEmpty(strippedString) ? HtmlUtils.StripTags(html, retainSpace) : html; return strippedString; - } - + } + private static DateTime FixSqlDateTime(DateTime datim) { - if (datim <= SqlDateTime.MinValue.Value) - { - datim = SqlDateTime.MinValue.Value.AddDays(1); - } - else if (datim >= SqlDateTime.MaxValue.Value) - { - datim = SqlDateTime.MaxValue.Value.AddDays(-1); - } - + if (datim <= SqlDateTime.MinValue.Value) + { + datim = SqlDateTime.MinValue.Value.AddDays(1); + } + else if (datim >= SqlDateTime.MaxValue.Value) + { + datim = SqlDateTime.MaxValue.Value.AddDays(-1); + } + return datim; } + 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); + } + private string FixLastWord(string lastWord, bool allowLeadingWildcard) { - if (string.IsNullOrEmpty(lastWord)) - { - return string.Empty; - } - + if (string.IsNullOrEmpty(lastWord)) + { + return string.Empty; + } + if (lastWord.IndexOfAny(new[] { '~', '*' }) < 0) { var beginIsGroup = false; @@ -591,17 +591,17 @@ private string FixLastWord(string lastWord, bool allowLeadingWildcard) : string.Format("({0} OR {1}{0}*)", lastWord, allowLeadingWildcard ? "*" : string.Empty); } - if (beginIsGroup) - { - lastWord = c1 + lastWord; - } - - if (endIsGroup) - { - lastWord += c2; - } + if (beginIsGroup) + { + lastWord = c1 + lastWord; + } + + if (endIsGroup) + { + lastWord += c2; + } } - + return lastWord; } @@ -664,23 +664,23 @@ private object SynonymTermsCallBack(CacheItemArgs cacheItem) var portalId = int.Parse(parts[1]); var cultureCode = parts[2]; var groups = this.GetSynonymsGroups(portalId, cultureCode); - if (groups == null) - { - return allTerms; - } - + if (groups == null) + { + return allTerms; + } + foreach (var synonymsGroup in groups) { var terms = new Dictionary>(); var groupTags = synonymsGroup.SynonymsTags.ToLowerInvariant().Split(','); - + // add the first key first foreach (var tag in groupTags) { - if (!terms.ContainsKey(tag)) - { - terms.Add(tag, new List()); - } + if (!terms.ContainsKey(tag)) + { + terms.Add(tag, new List()); + } } // add synonyms @@ -688,10 +688,10 @@ private object SynonymTermsCallBack(CacheItemArgs cacheItem) { foreach (var syn in terms) { - if (term.Key != syn.Key) - { - term.Value.Add(syn.Key); - } + if (term.Key != syn.Key) + { + term.Value.Add(syn.Key); + } } } @@ -720,17 +720,17 @@ private void EnsurePortalDefaultsAreSet(int portalId) const string setting = "SearchAdminInitialization"; // check portal settings first - if (PortalController.GetPortalSetting(setting, portalId, "false") != "false") - { - return; - } - - // Portal may not be present, especially during installation - if (PortalController.Instance.GetPortal(portalId) == null) - { - return; - } - + if (PortalController.GetPortalSetting(setting, portalId, "false") != "false") + { + return; + } + + // Portal may not be present, especially during installation + if (PortalController.Instance.GetPortal(portalId) == null) + { + return; + } + foreach (var locale in LocaleController.Instance.GetLocales(portalId).Values) { var resourceFile = this.GetResourceFile(locale.Code); @@ -740,10 +740,10 @@ private void EnsurePortalDefaultsAreSet(int portalId) { // Add Default StopWord var defaultStopWords = Localization.GetString("DefaultStopwordGroup", resourceFile); - if (!string.IsNullOrEmpty(defaultStopWords)) - { - DataProvider.Instance().AddSearchStopWords(defaultStopWords, 1, portalId, locale.Code); - } + if (!string.IsNullOrEmpty(defaultStopWords)) + { + DataProvider.Instance().AddSearchStopWords(defaultStopWords, 1, portalId, locale.Code); + } } var currentSynonymGroups = CBO.FillCollection(DataProvider.Instance().GetAllSynonymsGroups(portalId, locale.Code)); @@ -751,13 +751,13 @@ private void EnsurePortalDefaultsAreSet(int portalId) { // Add Default Synonym var defaultSynonymsGroup = Localization.GetString("DefaultSynonymGroup", resourceFile); - if (!string.IsNullOrEmpty(defaultSynonymsGroup)) - { - DataProvider.Instance().AddSynonymsGroup(defaultSynonymsGroup, 1, portalId, locale.Code); - } + if (!string.IsNullOrEmpty(defaultSynonymsGroup)) + { + DataProvider.Instance().AddSynonymsGroup(defaultSynonymsGroup, 1, portalId, locale.Code); + } } } - + // Update Portal Settings PortalController.UpdatePortalSetting(portalId, setting, "true", true); } @@ -796,8 +796,8 @@ private string FoldToASCII(string searchPhrase) space = " "; } } - + return sb.ToString(); - } + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs b/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs index c6460c379b2..0d701850c83 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchQueryAnalyzer.cs @@ -36,11 +36,11 @@ public override TokenStream TokenStream(string fieldName, TextReader reader) new StandardTokenizer(Constants.LuceneVersion, reader)), wordLengthMinMax.Item1, wordLengthMinMax.Item2))); - if (!this._useStemmingFilter) - { - return filter; - } - + if (!this._useStemmingFilter) + { + return filter; + } + return new PorterStemFilter(filter); } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs index acbb5225a7d..6f068e9cbf3 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchQueryStringParser.cs @@ -24,11 +24,6 @@ public class SearchQueryStringParser 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. @@ -53,13 +48,13 @@ public IList GetTags(string keywords, out string outputKeywords) { tags.Add(HttpUtility.HtmlEncode(tag.Trim())); } - + m = m.NextMatch(); } outputKeywords = TagRegex.Replace(keywords, string.Empty).Trim(); } - + return tags; } @@ -129,5 +124,10 @@ public IList GetSearchTypeList(string keywords, out string outputKeyword outputKeywords = TypeRegex.Replace(keywords, string.Empty).Trim(); return typesList; } + + protected override Func GetFactory() + { + return () => new SearchQueryStringParser(); + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs index d832daa15c3..472ce680eb4 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchSecurityTrimmer.cs @@ -19,13 +19,13 @@ internal class SearchSecurityTrimmer : Collector { private readonly SecurityCheckerDelegate _securityChecker; private readonly IndexSearcher _searcher; - - private Scorer _scorer; - private int _docBase; - private int _totalHits; private readonly LuceneQuery _luceneQuery; private readonly SearchQuery _searchQuery; private readonly List _hitDocs; + + private Scorer _scorer; + private int _docBase; + private int _totalHits; private List _scoreDocs; public SearchSecurityTrimmer(SearchSecurityTrimmerContext searchContext) @@ -37,20 +37,20 @@ public SearchSecurityTrimmer(SearchSecurityTrimmerContext searchContext) this._hitDocs = new List(16); } - public override bool AcceptsDocsOutOfOrder - { - get { return false; } - } + public override bool AcceptsDocsOutOfOrder + { + get { return false; } + } public int TotalHits { get { - if (this._scoreDocs == null) - { - this.PrepareScoreDocs(); - } - + if (this._scoreDocs == null) + { + this.PrepareScoreDocs(); + } + return this._totalHits; } } @@ -59,11 +59,11 @@ public List ScoreDocs { get { - if (this._scoreDocs == null) - { - this.PrepareScoreDocs(); - } - + if (this._scoreDocs == null) + { + this.PrepareScoreDocs(); + } + return this._scoreDocs; } } @@ -92,17 +92,17 @@ private string GetStringFromField(Document doc, SortField sortField) private long GetLongFromField(Document doc, SortField sortField) { var field = doc.GetField(sortField.Field); - if (field == null) - { - return 0; - } - + if (field == null) + { + return 0; + } + long data; - if (long.TryParse(field.StringValue, out data) && data >= 0) - { - return data; - } - + if (long.TryParse(field.StringValue, out data) && data >= 0) + { + return data; + } + return 0; } @@ -133,46 +133,46 @@ private void PrepareScoreDocs() var field = fields[0]; if (field.Type == SortField.INT || field.Type == SortField.LONG) { - if (field.Reverse) - { + if (field.Reverse) + { tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) .OrderByDescending(rec => this.GetLongFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - } - else - { + .Select(rec => rec.SDoc); + } + else + { tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) .OrderBy(rec => this.GetLongFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - } + .Select(rec => rec.SDoc); + } } else { - if (field.Reverse) - { + if (field.Reverse) + { tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) .OrderByDescending(rec => this.GetStringFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - } - else - { + .Select(rec => rec.SDoc); + } + else + { tempDocs = this._hitDocs.Select(d => new { SDoc = d, Document = this._searcher.Doc(d.Doc) }) .OrderBy(rec => this.GetStringFromField(rec.Document, field)) .ThenByDescending(rec => rec.Document.Boost) - .Select(rec => rec.SDoc); - } + .Select(rec => rec.SDoc); + } } } } - if (useRelevance) - { - tempDocs = this._hitDocs.OrderByDescending(d => d.Score).ThenBy(d => d.Doc); - } - + if (useRelevance) + { + tempDocs = this._hitDocs.OrderByDescending(d => d.Score).ThenBy(d => d.Doc); + } + var scoreDocSize = Math.Min(tempDocs.Count(), pageSize); this._scoreDocs = new List(scoreDocSize); diff --git a/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs b/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs index 5fcb5f47ac2..2967401765f 100644 --- a/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs +++ b/DNN Platform/Library/Services/Search/Internals/SearchStatistics.cs @@ -12,13 +12,13 @@ namespace DotNetNuke.Services.Search.Internals public class SearchStatistics { public int TotalActiveDocuments { get; set; } - + public int TotalDeletedDocuments { get; set; } - + public string IndexLocation { get; set; } - + public DateTime LastModifiedOn { get; set; } - + public long IndexDbSize { get; set; } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs b/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs index 4c76d45eb5c..a1104cafee4 100644 --- a/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs +++ b/DNN Platform/Library/Services/Search/Internals/SynonymAnalyzer.cs @@ -32,7 +32,7 @@ public override TokenStream TokenStream(string fieldName, TextReader reader) new PorterStemFilter(// stemming filter new ASCIIFoldingFilter(// accents filter new SynonymFilter( - new StopFilter( + new StopFilter( true, new LowerCaseFilter( new LengthFilter( @@ -61,10 +61,10 @@ private static ISet GetStopWords() if (string.IsNullOrEmpty(cultureCode)) { var portalInfo = PortalController.Instance.GetPortal(portalId); - if (portalInfo != null) - { - cultureCode = portalInfo.DefaultLanguage; - } + if (portalInfo != null) + { + cultureCode = portalInfo.DefaultLanguage; + } } } diff --git a/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs b/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs index bd64fd2b398..7b015da4735 100644 --- a/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs +++ b/DNN Platform/Library/Services/Search/Internals/SynonymFilter.cs @@ -20,11 +20,11 @@ namespace DotNetNuke.Services.Search.Internals internal sealed class SynonymFilter : TokenFilter { private readonly Stack _synonymStack = new Stack(); - private State _current; private readonly TermAttribute _termAtt; private readonly PositionIncrementAttribute _posIncrAtt; + private State _current; - public SynonymFilter(TokenStream input) + public SynonymFilter(TokenStream input) : base(input) { this._termAtt = (TermAttribute)this.AddAttribute(); @@ -46,12 +46,12 @@ public override bool IncrementToken() } // read next token - if (!this.input.IncrementToken()) - { - return false; - } - - // push synonyms onto stack + if (!this.input.IncrementToken()) + { + return false; + } + + // push synonyms onto stack if (this.AddAliasesToStack()) { this._current = this.CaptureState(); // save current token @@ -72,29 +72,29 @@ private bool AddAliasesToStack() if (string.IsNullOrEmpty(cultureCode)) { var portalInfo = PortalController.Instance.GetPortal(portalId); - if (portalInfo != null) - { - cultureCode = portalInfo.DefaultLanguage; - } + if (portalInfo != null) + { + cultureCode = portalInfo.DefaultLanguage; + } } } else { cultureCode = Thread.CurrentThread.CurrentCulture.Name; } - + var synonyms = SearchHelper.Instance.GetSynonyms(portalId, cultureCode, this._termAtt.Term).ToArray(); - if (!synonyms.Any()) - { - return false; - } - + if (!synonyms.Any()) + { + return false; + } + var cultureInfo = new CultureInfo(cultureCode); foreach (var synonym in synonyms) { this._synonymStack.Push(synonym.ToLower(cultureInfo)); } - + return true; } } diff --git a/DNN Platform/Library/Services/Search/ModuleIndexer.cs b/DNN Platform/Library/Services/Search/ModuleIndexer.cs index 0fff6a693bb..b29e423247f 100644 --- a/DNN Platform/Library/Services/Search/ModuleIndexer.cs +++ b/DNN Platform/Library/Services/Search/ModuleIndexer.cs @@ -35,13 +35,13 @@ namespace DotNetNuke.Services.Search /// /// ----------------------------------------------------------------------------- public class ModuleIndexer : IndexingProviderBase - { + { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModuleIndexer)); private static readonly int ModuleSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("module").SearchTypeId; - private readonly IDictionary> _searchModules; - - public ModuleIndexer() + private readonly IDictionary> _searchModules; + + public ModuleIndexer() : this(false) { } @@ -60,8 +60,8 @@ public ModuleIndexer(bool needSearchModules) this._searchModules.Add(Null.NullInteger, this.GetModulesForIndex(Null.NullInteger)); } - } - + } + /// ----------------------------------------------------------------------------- /// /// Returns the number of indexed SearchDocuments for the portal. @@ -69,7 +69,7 @@ public ModuleIndexer(bool needSearchModules) /// This replaces "GetSearchIndexItems" as a newer implementation of search. /// /// ----------------------------------------------------------------------------- - public override int IndexSearchDocuments( + public override int IndexSearchDocuments( int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { @@ -106,7 +106,7 @@ public override int IndexSearchDocuments( if (Logger.IsTraceEnabled) { - Logger.TraceFormat( + Logger.TraceFormat( "ModuleIndexer: {0} search documents found for module [{1} mid:{2}]", searchItems.Count, module.DesktopModule.ModuleName, module.ModuleID); } @@ -182,73 +182,8 @@ public List GetModuleMetaData(int portalId, DateTime startDate) } return searchDocuments; - } - - /// ----------------------------------------------------------------------------- - /// - /// Converts a SearchItemInfo into a SearchDocument. - /// - /// SearchItemInfo object was used in the old version of search. - /// - /// - /// - /// ----------------------------------------------------------------------------- -#pragma warning disable 0618 - public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searchItem) - { - var module = ModuleController.Instance.GetModule(searchItem.ModuleId, Null.NullInteger, true); - - var searchDoc = new SearchDocument - { - // Assigns as a Search key the SearchItems' GUID, if not it creates a dummy guid. - UniqueKey = (searchItem.SearchKey.Trim() != string.Empty) ? searchItem.SearchKey : Guid.NewGuid().ToString(), - QueryString = searchItem.GUID, - Title = searchItem.Title, - Body = searchItem.Content, - Description = searchItem.Description, - ModifiedTimeUtc = searchItem.PubDate, - AuthorUserId = searchItem.Author, - TabId = searchItem.TabId, - PortalId = module.PortalID, - SearchTypeId = ModuleSearchTypeId, - CultureCode = module.CultureCode, - - // Add Module MetaData - ModuleDefId = module.ModuleDefID, - ModuleId = module.ModuleID, - }; - - 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 - /// ----------------------------------------------------------------------------- /// /// Gets a list of modules that are listed as "Searchable" from the module definition and check if they @@ -264,17 +199,17 @@ protected IEnumerable GetSearchModules(int portalId) protected IEnumerable GetSearchModules(int portalId, bool allModules) { - return from mii in this.GetModulesForIndex(portalId) - where allModules || mii.SupportSearch + return from mii in this.GetModulesForIndex(portalId) + where allModules || mii.SupportSearch select mii.ModuleInfo; - } - + } + private static void ThrowLogError(ModuleInfo module, Exception ex) { try { var message = string.Format( - Localization.GetExceptionMessage( + Localization.GetExceptionMessage( "ErrorCreatingBusinessControllerClass", "Error Creating BusinessControllerClass '{0}' of module({1}) id=({2}) in tab({3}) and portal({4})"), module.DesktopModule.BusinessControllerClass, @@ -295,7 +230,7 @@ private IEnumerable GetModulesForIndex(int portalId) var businessControllers = new Hashtable(); var searchModuleIds = new HashSet(); var searchModules = new List(); - + // Only get modules that are set to be Indexed. var modules = ModuleController.Instance.GetSearchModules(portalId).Cast().Where(m => m.TabModuleSettings["AllowIndex"] == null || bool.Parse(m.TabModuleSettings["AllowIndex"].ToString())); @@ -304,7 +239,7 @@ private IEnumerable GetModulesForIndex(int portalId) try { var tab = TabController.Instance.GetTab(module.TabID, portalId, false); - + // Only index modules on tabs that are set to be Indexed. if (tab.TabSettings["AllowIndex"] == null || (tab.TabSettings["AllowIndex"] != null && bool.Parse(tab.TabSettings["AllowIndex"].ToString()))) { @@ -334,8 +269,73 @@ private IEnumerable GetModulesForIndex(int portalId) searchModuleIds.Add(module.ModuleID); } } - + return searchModules; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Converts a SearchItemInfo into a SearchDocument. + /// + /// SearchItemInfo object was used in the old version of search. + /// + /// + /// + /// ----------------------------------------------------------------------------- +#pragma warning disable 0618 + public SearchDocument ConvertSearchItemInfoToSearchDocument(SearchItemInfo searchItem) + { + var module = ModuleController.Instance.GetModule(searchItem.ModuleId, Null.NullInteger, true); + + var searchDoc = new SearchDocument + { + // Assigns as a Search key the SearchItems' GUID, if not it creates a dummy guid. + UniqueKey = (searchItem.SearchKey.Trim() != string.Empty) ? searchItem.SearchKey : Guid.NewGuid().ToString(), + QueryString = searchItem.GUID, + Title = searchItem.Title, + Body = searchItem.Content, + Description = searchItem.Description, + ModifiedTimeUtc = searchItem.PubDate, + AuthorUserId = searchItem.Author, + TabId = searchItem.TabId, + PortalId = module.PortalID, + SearchTypeId = ModuleSearchTypeId, + CultureCode = module.CultureCode, + + // Add Module MetaData + ModuleDefId = module.ModuleDefID, + ModuleId = module.ModuleID, + }; + + 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 } } diff --git a/DNN Platform/Library/Services/Search/SearchConfig.cs b/DNN Platform/Library/Services/Search/SearchConfig.cs index 5cf8aa29a79..13919717d61 100644 --- a/DNN Platform/Library/Services/Search/SearchConfig.cs +++ b/DNN Platform/Library/Services/Search/SearchConfig.cs @@ -20,12 +20,12 @@ namespace DotNetNuke.Services.Search [Serializable] public class SearchConfig { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SearchConfig)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SearchConfig)); private readonly bool _SearchIncludeCommon; private readonly bool _SearchIncludeNumeric; private readonly int _SearchMaxWordlLength; - private readonly int _SearchMinWordlLength; - + private readonly int _SearchMinWordlLength; + public SearchConfig(int portalID) : this(PortalController.Instance.GetPortalSettings(portalID)) { @@ -37,8 +37,8 @@ public SearchConfig(Dictionary settings) this._SearchIncludeNumeric = this.GetSettingAsBoolean("SearchIncludeNumeric", settings, Host.SearchIncludeNumeric); this._SearchMaxWordlLength = this.GetSettingAsInteger("MaxSearchWordLength", settings, Host.SearchMaxWordlLength); this._SearchMinWordlLength = this.GetSettingAsInteger("MinSearchWordLength", settings, Host.SearchMinWordlLength); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether to inlcude Common Words in the Search Index. @@ -93,8 +93,8 @@ public int SearchMinWordlLength { return this._SearchMinWordlLength; } - } - + } + private bool GetSettingAsBoolean(string key, Dictionary settings, bool defaultValue) { bool retValue = Null.NullBoolean; @@ -116,7 +116,7 @@ private bool GetSettingAsBoolean(string key, Dictionary settings // we just want to trap the error as we may not be installed so there will be no Settings Logger.Error(exc); } - + return retValue; } @@ -141,8 +141,8 @@ private int GetSettingAsInteger(string key, Dictionary settings, // we just want to trap the error as we may not be installed so there will be no Settings Logger.Error(exc); } - + return retValue; - } + } } } diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs index 292ffa874fe..eb3e7af2573 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfo.cs @@ -34,7 +34,7 @@ public ISearchable ModControllerType { return this.MModControllerType; } - + set { this.MModControllerType = value; @@ -48,7 +48,7 @@ public ModuleSearchBase ModSearchBaseControllerType { return this.SearchBaseControllerType; } - + set { this.SearchBaseControllerType = value; @@ -61,7 +61,7 @@ public ModuleInfo ModInfo { return this.MModInfo; } - + set { this.MModInfo = value; diff --git a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs index 207ebef731f..b67e1b5324a 100644 --- a/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchContentModuleInfoCollection.cs @@ -18,16 +18,16 @@ namespace DotNetNuke.Services.Search /// ----------------------------------------------------------------------------- #pragma warning disable 0618 public class SearchContentModuleInfoCollection : CollectionBase - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class. /// public SearchContentModuleInfoCollection() { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class containing the elements of the specified source collection. /// @@ -35,9 +35,9 @@ public SearchContentModuleInfoCollection() public SearchContentModuleInfoCollection(SearchContentModuleInfoCollection value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchContentModuleInfoCollection class containing the specified array of SearchContentModuleInfo objects. /// @@ -45,8 +45,8 @@ public SearchContentModuleInfoCollection(SearchContentModuleInfoCollection value public SearchContentModuleInfoCollection(SearchContentModuleInfo[] value) { this.AddRange(value); - } - + } + /// /// Gets the SearchContentModuleInfoCollection at the specified index in the collection. /// @@ -59,17 +59,17 @@ public SearchContentModuleInfo this[int index] { return (SearchContentModuleInfo)this.List[index]; } - + set { this.List[index] = value; } - } - + } + /// /// Add an element of the specified SearchContentModuleInfo to the end of the collection. /// - /// An object of type SearchContentModuleInfo to add to the collection. + /// An object of type SearchContentModuleInfo to add to the collection. /// public int Add(SearchContentModuleInfo value) { @@ -159,7 +159,7 @@ public SearchContentModuleInfo[] ToArray() var arr = new SearchContentModuleInfo[this.Count]; this.CopyTo(arr, 0); return arr; - } + } } #pragma warning restore 0618 } diff --git a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs index 3c75149b3cc..6bcd46a28e7 100644 --- a/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchCriteriaCollection.cs @@ -19,16 +19,16 @@ 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 SearchCriteriaCollection : CollectionBase - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class. /// public SearchCriteriaCollection() { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the elements of the specified source collection. /// @@ -36,9 +36,9 @@ public SearchCriteriaCollection() public SearchCriteriaCollection(SearchCriteriaCollection value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the specified array of SearchCriteria objects. /// @@ -46,9 +46,9 @@ public SearchCriteriaCollection(SearchCriteriaCollection value) public SearchCriteriaCollection(SearchCriteria[] value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchCriteriaCollection class containing the elements of the specified source collection. /// @@ -57,7 +57,7 @@ public SearchCriteriaCollection(string value) { // split search criteria into words string[] words = value.Split(' '); - + // Add all criteria without modifiers foreach (string word in words) { @@ -70,7 +70,7 @@ public SearchCriteriaCollection(string value) this.Add(criterion); } } - + // Add all mandatory criteria foreach (string word in words) { @@ -83,7 +83,7 @@ public SearchCriteriaCollection(string value) this.Add(criterion); } } - + // Add all excluded criteria foreach (string word in words) { @@ -96,8 +96,8 @@ public SearchCriteriaCollection(string value) this.Add(criterion); } } - } - + } + /// /// Gets the SearchCriteriaCollection at the specified index in the collection. /// @@ -110,17 +110,17 @@ public SearchCriteria this[int index] { return (SearchCriteria)this.List[index]; } - + set { this.List[index] = value; } - } - + } + /// /// Add an element of the specified SearchCriteria to the end of the collection. /// - /// An object of type SearchCriteria to add to the collection. + /// An object of type SearchCriteria to add to the collection. /// public int Add(SearchCriteria value) { @@ -209,6 +209,6 @@ public SearchCriteria[] ToArray() var arr = new SearchCriteria[this.Count]; this.CopyTo(arr, 0); return arr; - } + } } } diff --git a/DNN Platform/Library/Services/Search/SearchDataStore.cs b/DNN Platform/Library/Services/Search/SearchDataStore.cs index 9132a15485f..a6a7d9bfa5b 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStore.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStore.cs @@ -34,7 +34,7 @@ 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 - { + { /// ----------------------------------------------------------------------------- /// /// GetSearchItems gets a collection of Search Items for a Module/Tab/Portal. @@ -43,7 +43,7 @@ public class SearchDataStore : SearchDataStoreProvider /// /// A Id of the Portal. /// A Id of the Tab. - /// A Id of the Module. + /// A Id of the Module. /// /// ----------------------------------------------------------------------------- public override SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId) @@ -58,7 +58,7 @@ public override SearchResultsInfoCollection GetSearchItems(int portalId, int tab /// /// /// A Id of the Portal. - /// The criteria string. + /// The criteria string. /// /// ----------------------------------------------------------------------------- public override SearchResultsInfoCollection GetSearchResults(int portalId, string criteria) @@ -94,7 +94,7 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin { searchResults.Add(criterion.Criteria, SearchDataStoreController.GetSearchResults(portalId, criterion.Criteria)); } - + if (searchResults.ContainsKey(criterion.Criteria)) { foreach (SearchResultsInfo result in searchResults[criterion.Criteria]) @@ -132,7 +132,7 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin } } } - + foreach (SearchCriteria criterion in searchWords) { var mandatoryResults = new Dictionary(); @@ -155,7 +155,7 @@ public override SearchResultsInfoCollection GetSearchResults(int portalId, strin } } } - + foreach (KeyValuePair> kvpResults in dicResults) { // The key of this collection is the SearchItemID, Check if the value of this collection should be processed @@ -204,42 +204,6 @@ 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; - } /// ----------------------------------------------------------------------------- /// @@ -277,6 +241,42 @@ public override void StoreSearchItems(SearchItemInfoCollection searchItems) // Index InternalSearchController.Instance.AddSearchDocuments(searchDocuments); } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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/SearchDataStoreController.cs b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs index 715a2c3f7c6..125325df261 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreController.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreController.cs @@ -69,7 +69,7 @@ public static ArrayList GetSearchItems(int PortalId, int TabId, int ModuleId) /// /// /// A Id of the Portal. - /// The word. + /// The word. /// /// ----------------------------------------------------------------------------- [Obsolete("Deprecated in DNN 7.1.2 Implementation changed to return empty result set. Scheduled removal in v10.0.0.")] @@ -92,7 +92,7 @@ public static SearchResultsInfoCollection GetSearchResults(int PortalId, int Tab /// /// /// - /// The Id of the Module. + /// The Id of the Module. /// /// ----------------------------------------------------------------------------- public static Dictionary GetSearchSettings(int ModuleId) @@ -122,7 +122,7 @@ public static Dictionary GetSearchSettings(int ModuleId) { CBO.CloseDataReader(dr, true); } - + return dicSearchSettings; } diff --git a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs index 10fa642f713..446602ab8ee 100644 --- a/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs +++ b/DNN Platform/Library/Services/Search/SearchDataStoreProvider.cs @@ -13,17 +13,17 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] public abstract class SearchDataStoreProvider - { - // return the provider + { + // return the provider public static SearchDataStoreProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + public abstract void StoreSearchItems(SearchItemInfoCollection searchItems); public abstract SearchResultsInfoCollection GetSearchResults(int portalId, string criteria); - public abstract SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId); + public abstract SearchResultsInfoCollection GetSearchItems(int portalId, int tabId, int moduleId); } } diff --git a/DNN Platform/Library/Services/Search/SearchEngine.cs b/DNN Platform/Library/Services/Search/SearchEngine.cs index 0d1aa87637c..d271dc0cde0 100644 --- a/DNN Platform/Library/Services/Search/SearchEngine.cs +++ b/DNN Platform/Library/Services/Search/SearchEngine.cs @@ -34,13 +34,13 @@ internal SearchEngine(ScheduleHistoryItem scheduler, DateTime startTime) { this.SchedulerItem = scheduler; this.IndexingStartTime = startTime; - } - + } + public ScheduleHistoryItem SchedulerItem { get; private set; } // the time from where to start indexing items - public DateTime IndexingStartTime { get; private set; } - + public DateTime IndexingStartTime { get; private set; } + /// ----------------------------------------------------------------------------- /// /// Indexes content within the given time farame. @@ -99,7 +99,7 @@ internal bool CompactSearchIndexIfNeeded(ScheduleHistoryItem scheduleItem) scheduleItem.AddLogNote(string.Format("
    Compacted Index, total time {0}", stopWatch.Elapsed)); } } - + return false; } @@ -118,11 +118,6 @@ 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. /// @@ -141,10 +136,10 @@ internal void DeleteRemovedObjects() searchController.DeleteSearchDocument(document); deletedCount += 1; } - + reader.Close(); } - + this.AddIdexingResults("Deleted Objects", deletedCount); dataProvider.DeleteProcessedSearchDeletedItems(cutoffTime); } @@ -155,8 +150,8 @@ internal void DeleteRemovedObjects() internal void Commit() { InternalSearchController.Instance.Commit(); - } - + } + /// ----------------------------------------------------------------------------- /// /// LEGACY: Deprecated in DNN 7.1. Use 'IndexSearchDocuments' instead. @@ -166,7 +161,7 @@ internal void Commit() /// /// /// - /// The Index Provider that will index the content 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.")] @@ -179,7 +174,7 @@ protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) var portal = (PortalInfo)portals[index]; searchItems.AddRange(indexer.GetSearchIndexItems(portal.PortalID)); } - + return searchItems; } @@ -193,7 +188,7 @@ protected SearchItemInfoCollection GetContent(IndexingProviderBase indexer) /// /// /// The Id of the Portal. - /// The Index Provider that will index the content 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.")] @@ -202,7 +197,7 @@ protected SearchItemInfoCollection GetContent(int portalId, IndexingProvider ind var searchItems = new SearchItemInfoCollection(); searchItems.AddRange(indexer.GetSearchIndexItems(portalId)); return searchItems; - } + } /// ----------------------------------------------------------------------------- /// @@ -222,7 +217,12 @@ private static void StoreSearchDocuments(IEnumerable searchDocs) InternalSearchController.Instance.AddSearchDocuments(searchDocumentList); } - + + private void AddIdexingResults(string description, int count) + { + this.SchedulerItem.AddLogNote(string.Format("
      {0}: {1}", description, count)); + } + /// ----------------------------------------------------------------------------- /// /// Gets all the Search Documents for the given timeframe. @@ -269,7 +269,7 @@ private int GetAndStoreSearchDocuments(IndexingProviderBase indexer) StoreSearchDocuments(searchDocs); indexedCount += searchDocs.Count(); } - + return indexedCount; } @@ -284,7 +284,7 @@ private int GetAndStoreModuleMetaData(ModuleIndexer indexer) var portals = PortalController.Instance.GetPortals(); DateTime indexSince; var indexedCount = 0; - + // DateTime startDate foreach (var portal in portals.Cast()) { @@ -316,8 +316,8 @@ private DateTime FixedIndexingStartDate(int portalId) { return SqlDateTime.MinValue.Value.AddDays(1); } - + return startDate; - } + } } } diff --git a/DNN Platform/Library/Services/Search/SearchItemInfo.cs b/DNN Platform/Library/Services/Search/SearchItemInfo.cs index ff3b046f3e2..ed0d0236549 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfo.cs @@ -82,14 +82,14 @@ public SearchItemInfo(string Title, string Description, int Author, DateTime Pub this._HitCount = 0; this._TabId = TabID; } - + public int SearchItemId { get { return this._SearchItemId; } - + set { this._SearchItemId = value; @@ -102,7 +102,7 @@ public string Title { return this._Title; } - + set { this._Title = value; @@ -115,7 +115,7 @@ public string Description { return this._Description; } - + set { this._Description = value; @@ -128,7 +128,7 @@ public int Author { return this._Author; } - + set { this._Author = value; @@ -141,7 +141,7 @@ public DateTime PubDate { return this._PubDate; } - + set { this._PubDate = value; @@ -154,7 +154,7 @@ public int ModuleId { return this._ModuleId; } - + set { this._ModuleId = value; @@ -167,7 +167,7 @@ public string SearchKey { return this._SearchKey; } - + set { this._SearchKey = value; @@ -180,7 +180,7 @@ public string Content { return this._Content; } - + set { this._Content = value; @@ -193,7 +193,7 @@ public string GUID { return this._GUID; } - + set { this._GUID = value; @@ -206,7 +206,7 @@ public int ImageFileId { return this._ImageFileId; } - + set { this._ImageFileId = value; @@ -219,7 +219,7 @@ public int HitCount { return this._HitCount; } - + set { this._HitCount = value; @@ -232,7 +232,7 @@ public int TabId { return this._TabId; } - + set { this._TabId = value; diff --git a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs index d43169bf4ba..0cd584dda8b 100644 --- a/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchItemInfoCollection.cs @@ -20,16 +20,16 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] [Serializable] public class SearchItemInfoCollection : CollectionBase - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class. /// public SearchItemInfoCollection() { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class containing the elements of the specified source collection. /// @@ -37,9 +37,9 @@ public SearchItemInfoCollection() public SearchItemInfoCollection(SearchItemInfoCollection value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollection class containing the specified array of SearchItemInfo objects. /// @@ -47,9 +47,9 @@ public SearchItemInfoCollection(SearchItemInfoCollection value) public SearchItemInfoCollection(SearchItemInfo[] value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchItemInfoCollectionSearchItemInfoCollection class containing the specified array of SearchItemInfo objects. /// @@ -57,8 +57,8 @@ public SearchItemInfoCollection(SearchItemInfo[] value) public SearchItemInfoCollection(ArrayList value) { this.AddRange(value); - } - + } + /// /// Gets the SearchItemInfoCollection at the specified index in the collection. /// @@ -71,17 +71,17 @@ public SearchItemInfo this[int index] { return (SearchItemInfo)this.List[index]; } - + set { this.List[index] = value; } - } - + } + /// /// Add an element of the specified SearchItemInfo to the end of the collection. /// - /// An object of type SearchItemInfo to add to the collection. + /// An object of type SearchItemInfo to add to the collection. /// public int Add(SearchItemInfo value) { @@ -198,8 +198,8 @@ public SearchItemInfoCollection ModuleItems(int ModuleId) retValue.Add(info); } } - + return retValue; - } + } } } diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs index 2b6026dbe5c..29c09d6bc61 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfo.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfo.cs @@ -42,7 +42,7 @@ public int SearchItemID { return this.m_SearchItemID; } - + set { this.m_SearchItemID = value; @@ -55,7 +55,7 @@ public string Title { return this.m_Title; } - + set { this.m_Title = value; @@ -68,7 +68,7 @@ public string Description { return this.m_Description; } - + set { this.m_Description = value; @@ -81,7 +81,7 @@ public string Author { return this.m_Author; } - + set { this.m_Author = value; @@ -94,7 +94,7 @@ public DateTime PubDate { return this.m_PubDate; } - + set { this.m_PubDate = value; @@ -107,7 +107,7 @@ public string Guid { return this.m_Guid; } - + set { this.m_Guid = value; @@ -120,7 +120,7 @@ public int Image { return this.m_Image; } - + set { this.m_Image = value; @@ -133,7 +133,7 @@ public int TabId { return this.m_TabId; } - + set { this.m_TabId = value; @@ -146,7 +146,7 @@ public string SearchKey { return this.m_SearchKey; } - + set { this.m_SearchKey = value; @@ -159,7 +159,7 @@ public int Occurrences { return this.m_Occurrences; } - + set { this.m_Occurrences = value; @@ -172,7 +172,7 @@ public int Relevance { return this.m_Relevance; } - + set { this.m_Relevance = value; @@ -185,7 +185,7 @@ public int ModuleId { return this.m_ModuleId; } - + set { this.m_ModuleId = value; @@ -198,7 +198,7 @@ public bool Delete { return this.m_Delete; } - + set { this.m_Delete = value; @@ -211,7 +211,7 @@ public string AuthorName { return this.m_AuthorName; } - + set { this.m_AuthorName = value; @@ -224,7 +224,7 @@ public int PortalId { return this.m_PortalId; } - + set { this.m_PortalId = value; diff --git a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs index eca03620cd9..6c285c95c21 100644 --- a/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs +++ b/DNN Platform/Library/Services/Search/SearchResultsInfoCollection.cs @@ -20,16 +20,16 @@ namespace DotNetNuke.Services.Search [Obsolete("Deprecated in DNN 7.1. No longer used in the Search infrastructure.. Scheduled removal in v10.0.0.")] [Serializable] public class SearchResultsInfoCollection : CollectionBase - { - /// + { + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class. /// public SearchResultsInfoCollection() { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the elements of the specified source collection. /// @@ -37,9 +37,9 @@ public SearchResultsInfoCollection() public SearchResultsInfoCollection(SearchResultsInfoCollection value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the specified array of SearchResultsInfo objects. /// @@ -47,9 +47,9 @@ public SearchResultsInfoCollection(SearchResultsInfoCollection value) public SearchResultsInfoCollection(SearchResultsInfo[] value) { this.AddRange(value); - } - - /// + } + + /// /// Initializes a new instance of the class. /// Initializes a new instance of the SearchResultsInfoCollection class containing the specified array of SearchResultsInfo objects. /// @@ -57,8 +57,8 @@ public SearchResultsInfoCollection(SearchResultsInfo[] value) public SearchResultsInfoCollection(ArrayList value) { this.AddRange(value); - } - + } + /// /// Gets the SearchResultsInfoCollection at the specified index in the collection. /// @@ -71,17 +71,17 @@ public SearchResultsInfo this[int index] { return (SearchResultsInfo)this.List[index]; } - + set { this.List[index] = value; } - } - + } + /// /// Add an element of the specified SearchResultsInfo to the end of the collection. /// - /// An object of type SearchResultsInfo to add to the collection. + /// An object of type SearchResultsInfo to add to the collection. /// public int Add(SearchResultsInfo value) { @@ -185,6 +185,6 @@ public SearchResultsInfo[] ToArray() var arr = new SearchResultsInfo[this.Count]; this.CopyTo(arr, 0); return arr; - } + } } } diff --git a/DNN Platform/Library/Services/Search/UserIndexer.cs b/DNN Platform/Library/Services/Search/UserIndexer.cs index 395fecfc272..111d449de38 100644 --- a/DNN Platform/Library/Services/Search/UserIndexer.cs +++ b/DNN Platform/Library/Services/Search/UserIndexer.cs @@ -40,20 +40,20 @@ public class UserIndexer : IndexingProviderBase { internal const string UserIndexResetFlag = "UserIndexer_ReIndex"; internal const string ValueSplitFlag = "$$$"; - - internal static readonly Regex UsrFirstNameSplitRx = new Regex(Regex.Escape(ValueSplitFlag), RegexOptions.Compiled); private const int BatchSize = 250; private const int ClauseMaxCount = 1024; - private static readonly int UserSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; - + internal static readonly Regex UsrFirstNameSplitRx = new Regex(Regex.Escape(ValueSplitFlag), RegexOptions.Compiled); + + private static readonly int UserSearchTypeId = SearchHelper.Instance.GetSearchTypeByName("user").SearchTypeId; + /// ----------------------------------------------------------------------------- /// /// Searches for and indexes modified users for the given portal. /// /// Count of indexed records. /// ----------------------------------------------------------------------------- - public override int IndexSearchDocuments( + public override int IndexSearchDocuments( int portalId, ScheduleHistoryItem schedule, DateTime startDateLocal, Action> indexer) { @@ -107,7 +107,7 @@ public override int IndexSearchDocuments( searchDocuments.Clear(); checkpointModified = true; } - } + } while (rowsAffected > 0); if (searchDocuments.Count > 0) @@ -136,7 +136,7 @@ public override int IndexSearchDocuments( this.SetLastCheckpointData(portalId, schedule.ScheduleID, Null.NullInteger.ToString()); this.SetLocalTimeOfLastIndexedItem(portalId, schedule.ScheduleID, DateTime.Now); } - + return totalIndexed; } @@ -151,11 +151,11 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, while (reader.Read()) { var userSearch = GetUserSearch(reader); - if (userSearch == null) - { - continue; - } - + if (userSearch == null) + { + continue; + } + AddBasicInformation(searchDocuments, indexedUsers, userSearch, portalId); // log the userid so that it can get the correct user collection next time. @@ -239,7 +239,7 @@ private static int FindModifiedUsers(int portalId, DateTime startDateLocal, rowsAffected++; } } - + return rowsAffected; } @@ -253,7 +253,7 @@ private static void AddBasicInformation(IDictionary sear { indexedUsers.Add(userSearch.UserId); } - + // if the user doesn't exist in search collection, we need add it with ALLUsers mode, // so that can make sure DisplayName will be indexed var searchDoc = new SearchDocument @@ -280,7 +280,7 @@ private static void AddBasicInformation(IDictionary sear { indexedUsers.Add(userSearch.UserId); } - + // if the user doesn't exist in search collection, we need add it with ALLUsers mode, // so that can make sure DisplayName will be indexed var searchDoc = new SearchDocument @@ -304,13 +304,6 @@ 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 @@ -340,8 +333,8 @@ private static UserSearch GetUserSearch(IDataRecord reader) Exceptions.Exceptions.LogException(ex); return null; } - } - + } + private static void DeleteDocuments(int portalId, ICollection usersList) { if (usersList == null || usersList.Count == 0) @@ -361,9 +354,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) - - // max cluaseCount is 1024, if reach the max value, perform a delete action. + if (clauseCount >= ClauseMaxCount) + + // max cluaseCount is 1024, if reach the max value, perform a delete action. { keyword.Append(")"); PerformDelete(portalId, keyword.ToString().ToLowerInvariant()); @@ -403,25 +396,32 @@ private static bool ContainsColumn(string col, IDataReader reader) { var schema = reader.GetSchemaTable(); return schema != null && schema.Select("ColumnName = '" + col + "'").Length > 0; - } + } + + 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; + } } internal class UserSearch { public int UserId { get; set; } - + public string DisplayName { get; set; } - + public string FirstName { get; set; } - + public string Email { get; set; } - + public string UserName { get; set; } - + public bool SuperUser { get; set; } - + public DateTime LastModifiedOnDate { get; set; } - + public DateTime CreatedOnDate { get; set; } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs index 7bdfa9ed702..03c578652b3 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapBuilder.cs @@ -25,14 +25,14 @@ public class SitemapBuilder 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; - - /// + private string _cacheIndexFileNameFormat; + + /// /// Initializes a new instance of the class. /// Creates an instance of the sitemap builder class. /// @@ -44,8 +44,8 @@ public SitemapBuilder(PortalSettings ps) this.PortalSettings = ps; LoadProviders(); - } - + } + public string CacheFileName { get @@ -77,7 +77,7 @@ public string CacheIndexFileNameFormat return this._cacheIndexFileNameFormat; } - } + } public List Providers { @@ -86,7 +86,7 @@ public List Providers return _providers; } } - + /// /// Builds the complete portal sitemap. /// @@ -104,7 +104,7 @@ public void BuildSiteMap(TextWriter output) } var allUrls = new List(); - + // excluded urls by priority float excludePriority = 0; excludePriority = float.Parse(PortalController.GetPortalSetting("SitemapExcludePriority", this.PortalSettings.PortalId, "0"), NumberFormatInfo.InvariantInfo); @@ -113,7 +113,7 @@ public void BuildSiteMap(TextWriter output) bool isProviderEnabled = false; bool isProviderPriorityOverrided = false; float providerPriorityValue = 0; - + foreach (SitemapProvider _provider in this.Providers) { isProviderEnabled = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Enabled", this.PortalSettings.PortalId, "True")); @@ -122,7 +122,7 @@ public void BuildSiteMap(TextWriter output) { // check if we should override the priorities isProviderPriorityOverrided = bool.Parse(PortalController.GetPortalSetting(_provider.Name + "Override", this.PortalSettings.PortalId, "False")); - + // stored as an integer (pr * 100) to prevent from translating errors with the decimal point providerPriorityValue = float.Parse(PortalController.GetPortalSetting(_provider.Name + "Value", this.PortalSettings.PortalId, "50")) / 100; @@ -134,7 +134,7 @@ public void BuildSiteMap(TextWriter output) } catch (Exception ex) { - Services.Exceptions.Exceptions.LogException(new Exception(Localization.GetExceptionMessage( + Services.Exceptions.Exceptions.LogException(new Exception(Localization.GetExceptionMessage( "SitemapProviderError", "URL sitemap provider '{0}' failed with error: {1}", _provider.Name, ex.Message))); @@ -146,7 +146,7 @@ public void BuildSiteMap(TextWriter output) { url.Priority = providerPriorityValue; } - + if (url.Priority > 0 && url.Priority >= excludePriority) // #RS# a valid sitemap needs priorities larger then 0, otherwise the sitemap will be rejected by google as invalid { allUrls.Add(url); @@ -196,7 +196,7 @@ public void BuildSiteMap(TextWriter output) // create a regular sitemap file this.WriteSitemap(cached, output, 0, allUrls); } - + if (cached) { this.WriteSitemapFileToOutput(this.CacheFileName, output); @@ -217,6 +217,27 @@ public void GetSitemapIndexFile(string index, TextWriter output) this.WriteSitemapFileToOutput(string.Format("sitemap_{0}.{1}.xml", index, currentCulture), output); } + private static void LoadProviders() + { + // Avoid claiming lock if providers are already loaded + if (_providers == null) + { + lock (_lock) + { + _providers = new List(); + + foreach (KeyValuePair comp in ComponentFactory.GetComponents()) + { + comp.Value.Name = comp.Key; + comp.Value.Description = comp.Value.Description; + _providers.Add(comp.Value); + } + + // 'ProvidersHelper.InstantiateProviders(section.Providers, _providers, GetType(SiteMapProvider)) + } + } + } + /// /// Generates a sitemap file. /// @@ -241,7 +262,7 @@ private void WriteSitemap(bool cached, TextWriter output, int index, List 0) ? string.Format(this.CacheIndexFileNameFormat, index) : this.CacheFileName; sitemapOutput = new StreamWriter(this.PortalSettings.HomeSystemDirectoryMapPath + "Sitemap\\" + cachedFile, false, Encoding.UTF8); } @@ -279,10 +300,10 @@ private void WriteSitemap(bool cached, TextWriter output, int index, List /// Adds a new url to the sitemap. /// @@ -374,7 +395,7 @@ private bool CacheIsValid() { return isValid; } - + DateTime lastmod = File.GetLastWriteTime(this.PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + this.CacheFileName); if (lastmod.AddDays(cacheDays) < DateTime.Now) { @@ -395,7 +416,7 @@ private void WriteSitemapFileToOutput(string file, TextWriter output) { return; } - + // write the cached file to output using (var reader = new StreamReader(this.PortalSettings.HomeSystemDirectoryMapPath + "/Sitemap/" + file, Encoding.UTF8)) { @@ -404,7 +425,7 @@ private void WriteSitemapFileToOutput(string file, TextWriter output) reader.Close(); } } - + private bool IsChildPortal(PortalSettings ps, HttpContext context) { bool isChild = false; @@ -420,35 +441,14 @@ private bool IsChildPortal(PortalSettings ps, HttpContext context) { portalName = PortalController.GetPortalFolder(portalAlias.HTTPAlias); } - + if (!string.IsNullOrEmpty(portalName) && Directory.Exists(serverPath + portalName)) { isChild = true; } } - + return isChild; - } - - private static void LoadProviders() - { - // Avoid claiming lock if providers are already loaded - if (_providers == null) - { - lock (_lock) - { - _providers = new List(); - - foreach (KeyValuePair comp in ComponentFactory.GetComponents()) - { - comp.Value.Name = comp.Key; - comp.Value.Description = comp.Value.Description; - _providers.Add(comp.Value); - } - - // 'ProvidersHelper.InstantiateProviders(section.Providers, _providers, GetType(SiteMapProvider)) - } - } - } + } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs b/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs index b8bf5947c2c..caf44157a8b 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapHandler.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Services.Sitemap using DotNetNuke.Entities.Portals; public class SitemapHandler : IHttpHandler - { + { public bool IsReusable { get @@ -45,6 +45,6 @@ public void ProcessRequest(HttpContext context) { Exceptions.Exceptions.LogException(exc); } - } + } } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs b/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs index f224c023101..89e039f0345 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapProvider.cs @@ -13,27 +13,27 @@ public abstract class SitemapProvider public string Name { get; set; } public string Description { get; set; } - + public bool Enabled { get { return bool.Parse(PortalController.GetPortalSetting(this.Name + "Enabled", PortalController.Instance.GetCurrentPortalSettings().PortalId, "True")); } - + set { PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Enabled", value.ToString()); } } - + public bool OverridePriority { get { return bool.Parse(PortalController.GetPortalSetting(this.Name + "Override", PortalController.Instance.GetCurrentPortalSettings().PortalId, "False")); } - + set { PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Override", value.ToString()); @@ -50,7 +50,7 @@ public float Priority // stored as an integer (pr * 100) to prevent from translating errors with the decimal point value = float.Parse(PortalController.GetPortalSetting(this.Name + "Value", PortalController.Instance.GetCurrentPortalSettings().PortalId, "0.5"), NumberFormatInfo.InvariantInfo); } - + return value; } @@ -59,7 +59,7 @@ public float Priority PortalController.UpdatePortalSetting(PortalController.Instance.GetCurrentPortalSettings().PortalId, this.Name + "Value", value.ToString(NumberFormatInfo.InvariantInfo)); } } - + public abstract List GetUrls(int portalId, PortalSettings ps, string version); } } diff --git a/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs b/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs index 9f9b9a60e35..fc838e1f853 100644 --- a/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs +++ b/DNN Platform/Library/Services/Sitemap/SitemapUrl.cs @@ -9,11 +9,11 @@ namespace DotNetNuke.Services.Sitemap public class SitemapUrl { public string Url { get; set; } - + public DateTime LastModified { get; set; } - + public SitemapChangeFrequency ChangeFrequency { get; set; } - + public float Priority { get; set; } public List AlternateUrls { get; set; } diff --git a/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs b/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs index f9507f3f202..4033c8a4c97 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Data/IDataService.cs @@ -11,87 +11,87 @@ namespace DotNetNuke.Services.Social.Messaging.Data public interface IDataService { - int SaveMessage(Message message, int portalId, int createUpdateUserId); + int SaveMessage(Message message, int portalId, int createUpdateUserId); - IDataReader GetMessage(int messageId); + IDataReader GetMessage(int messageId); - IDataReader GetMessagesBySender(int messageId, int portalId); + IDataReader GetMessagesBySender(int messageId, int portalId); - IDataReader GetLastSentMessage(int userId, int portalId); + IDataReader GetLastSentMessage(int userId, int portalId); - void DeleteMessage(int messageId); + void DeleteMessage(int messageId); - void DeleteUserFromConversation(int conversationId, int userId); - - IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus, MessageSentStatus sentStatus); + void DeleteUserFromConversation(int conversationId, int userId); - IDataReader GetSentBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); + IDataReader GetInBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, MessageReadStatus readStatus, MessageArchivedStatus archivedStatus, MessageSentStatus sentStatus); - IDataReader GetArchiveBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); + IDataReader GetSentBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); - IDataReader GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, ref int totalRecords); + IDataReader GetArchiveBoxView(int userId, int portalId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending); - void UpdateMessageReadStatus(int conversationId, int userId, bool read); + IDataReader GetMessageThread(int conversationId, int userId, int afterMessageId, int numberOfRecords, string sortColumn, bool sortAscending, ref int totalRecords); - void UpdateMessageArchivedStatus(int conversationId, int userId, bool archived); + void UpdateMessageReadStatus(int conversationId, int userId, bool read); - int CreateMessageReply(int conversationId, int portalId, string body, int senderUserId, string from, int createUpdateUserId); + void UpdateMessageArchivedStatus(int conversationId, int userId, bool archived); - int CountNewThreads(int userId, int portalId); + int CreateMessageReply(int conversationId, int portalId, string body, int senderUserId, string from, int createUpdateUserId); - int CountTotalConversations(int userId, int portalId); + int CountNewThreads(int userId, int portalId); - int CountMessagesByConversation(int conversationId); + int CountTotalConversations(int userId, int portalId); - int CountArchivedMessagesByConversation(int conversationId); + int CountMessagesByConversation(int conversationId); - int CountSentMessages(int userId, int portalId); + int CountArchivedMessagesByConversation(int conversationId); - int CountArchivedMessages(int userId, int portalId); + int CountSentMessages(int userId, int portalId); - int CountSentConversations(int userId, int portalId); + int CountArchivedMessages(int userId, int portalId); - int CountArchivedConversations(int userId, int portalId); + int CountSentConversations(int userId, int portalId); + + int CountArchivedConversations(int userId, int portalId); int CheckReplyHasRecipients(int conversationId, int userId); - int SaveMessageRecipient(MessageRecipient messageRecipient, int createUpdateUserId); + int SaveMessageRecipient(MessageRecipient messageRecipient, int createUpdateUserId); - void CreateMessageRecipientsForRole(int messageId, string roleIds, int createUpdateUserId); + void CreateMessageRecipientsForRole(int messageId, string roleIds, int createUpdateUserId); - IDataReader GetMessageRecipient(int messageRecipientId); + IDataReader GetMessageRecipient(int messageRecipientId); - IDataReader GetMessageRecipientsByUser(int userId); + IDataReader GetMessageRecipientsByUser(int userId); - IDataReader GetMessageRecipientsByMessage(int messageId); + IDataReader GetMessageRecipientsByMessage(int messageId); - IDataReader GetMessageRecipientByMessageAndUser(int messageId, int userId); + IDataReader GetMessageRecipientByMessageAndUser(int messageId, int userId); - void DeleteMessageRecipient(int messageRecipientId); + void DeleteMessageRecipient(int messageRecipientId); void DeleteMessageRecipientByMessageAndUser(int messageId, int userId); - int SaveMessageAttachment(MessageAttachment messageAttachment, int createUpdateUserId); + int SaveMessageAttachment(MessageAttachment messageAttachment, int createUpdateUserId); - IDataReader GetMessageAttachment(int messageAttachmentId); + IDataReader GetMessageAttachment(int messageAttachmentId); - IList GetMessageAttachmentsByMessage(int messageId); + IList GetMessageAttachmentsByMessage(int messageId); void DeleteMessageAttachment(int messageAttachmentId); - void ConvertLegacyMessages(int pageIndex, int pageSize); - + void ConvertLegacyMessages(int pageIndex, int pageSize); + IDataReader CountLegacyMessages(); - IDataReader GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize); + IDataReader GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize); - IDataReader GetNextMessagesForDigestDispatch(int frequecy, Guid schedulerInstance, int batchSize); + IDataReader GetNextMessagesForDigestDispatch(int frequecy, Guid schedulerInstance, int batchSize); - void MarkMessageAsDispatched(int messageId, int recipientId); + void MarkMessageAsDispatched(int messageId, int recipientId); void MarkMessageAsSent(int messageId, int recipientId); - IDataReader GetUserPreference(int portalId, int userId); + IDataReader GetUserPreference(int portalId, int userId); void SetUserPreference(int portalId, int userId, int messagesEmailFrequency, int notificationsEmailFrequency); } diff --git a/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs index 235714e5bc1..0694c77aefe 100644 --- a/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/IMessagingController.cs @@ -11,9 +11,9 @@ namespace DotNetNuke.Services.Social.Messaging using DotNetNuke.Security.Roles; public interface IMessagingController - { + { void SendMessage(Message message, IList roles, IList users, IList fileIDs); - void SendMessage(Message message, IList roles, IList users, IList fileIDs, UserInfo sender); + void SendMessage(Message message, IList roles, IList users, IList fileIDs, UserInfo sender); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs index bd71deb7d8e..219087d761b 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/IInternalMessagingController.cs @@ -12,29 +12,29 @@ namespace DotNetNuke.Services.Social.Messaging.Internal /// Interface used for Message Controller behaviors. public interface IInternalMessagingController - { + { int ReplyMessage(int conversationId, string body, IList fileIDs); - int ReplyMessage(int conversationId, string body, IList fileIDs, UserInfo sender); - + int ReplyMessage(int conversationId, string body, IList fileIDs, UserInfo sender); + Message GetMessage(int messageId); - + MessageRecipient GetMessageRecipient(int messageId, int userId); - + IList GetMessageRecipients(int messageId); - + void DeleteMessageRecipient(int messageId, int userId); - + void DeleteUserFromConversation(int conversationId, int userId); void MarkRead(int conversationId, int userId); - + void MarkUnRead(int conversationId, int userId); - + void MarkArchived(int conversationId, int userId); - - void MarkUnArchived(int conversationId, int userId); - + + void MarkUnArchived(int conversationId, int userId); + /// How long a user needs to wait before user is allowed sending the next message. /// Time in seconds. Returns zero if user has never sent a message. /// Sender's UserInfo. @@ -61,10 +61,10 @@ public interface IInternalMessagingController bool IncludeAttachments(int portalId); /// Whether disable regular users to send message to user/group, default is false. - /// Portal Id. + /// Portal Id. /// - bool DisablePrivateMessage(int portalId); - + bool DisablePrivateMessage(int portalId); + /// Converts the legacy messages. /// Index of the page. /// Size of the page. @@ -72,8 +72,8 @@ public interface IInternalMessagingController /// Counts the legacy messages. /// A count of messages. - int CountLegacyMessages(); - + int CountLegacyMessages(); + /// Gets the inbox. /// The user identifier. /// The after message identifier. @@ -168,16 +168,16 @@ public interface IInternalMessagingController /// Gets the attachments for the specified message. /// The message identifier. /// A list of . - IEnumerable GetAttachments(int messageId); - + IEnumerable GetAttachments(int messageId); + IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize); - + IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize); - + void MarkMessageAsDispatched(int messageId, int recipientId); - - void MarkMessageAsSent(int messageId, int recipientId); - + + void MarkMessageAsSent(int messageId, int recipientId); + int CheckReplyHasRecipients(int conversationId, int userId); int CountUnreadMessages(int userId, int portalId); @@ -194,6 +194,6 @@ public interface IInternalMessagingController int CountSentConversations(int userId, int portalId); - int CountArchivedConversations(int userId, int portalId); + int CountArchivedConversations(int userId, int portalId); } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs index d3e72276cd4..960b63d374c 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/InternalMessagingControllerImpl.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Services.Social.Messaging.Internal /// The Controller class for social Messaging. internal class InternalMessagingControllerImpl : IInternalMessagingController - { + { internal const int ConstMaxTo = 2000; internal const int ConstMaxSubject = 400; internal const int ConstDefaultPageIndex = 0; @@ -30,10 +30,10 @@ internal class InternalMessagingControllerImpl : IInternalMessagingController internal const string ConstSortColumnFrom = "From"; internal const string ConstSortColumnSubject = "Subject"; internal const bool ConstAscending = true; - internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. - - private readonly IDataService _dataService; - + internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. + + private readonly IDataService _dataService; + public InternalMessagingControllerImpl() : this(DataService.Instance) { @@ -45,8 +45,8 @@ public InternalMessagingControllerImpl(IDataService dataService) Requires.NotNull("dataService", dataService); this._dataService = dataService; - } - + } + public virtual void DeleteMessageRecipient(int messageId, int userId) { this._dataService.DeleteMessageRecipientByMessageAndUser(messageId, userId); @@ -90,8 +90,8 @@ public virtual void MarkUnArchived(int conversationId, int userId) public virtual void MarkUnRead(int conversationId, int userId) { this._dataService.UpdateMessageReadStatus(conversationId, userId, false); - } - + } + public virtual int ReplyMessage(int conversationId, string body, IList fileIDs) { return this.ReplyMessage(conversationId, body, fileIDs, UserController.Instance.GetCurrentUserInfo()); @@ -114,7 +114,7 @@ public virtual int ReplyMessage(int conversationId, string body, IList file { throw new AttachmentsNotAllowed(Localization.GetString("MsgAttachmentsNotAllowed", Localization.ExceptionsResourceFile)); } - + // Profanity Filter var profanityFilterSetting = this.GetPortalSetting("MessagingProfanityFilters", sender.PortalID, "NO"); if (profanityFilterSetting.Equals("YES", StringComparison.InvariantCultureIgnoreCase)) @@ -145,8 +145,8 @@ public virtual int ReplyMessage(int conversationId, string body, IList file this.MarkRead(conversationId, sender.UserID); return messageId; - } - + } + /// How long a user needs to wait before sending the next message. /// Time in seconds. Returns zero if user is Host, Admin or has never sent a message. /// Sender's UserInfo. @@ -156,7 +156,7 @@ public virtual int WaitTimeForNextMessage(UserInfo sender) Requires.NotNull("sender", sender); var waitTime = 0; - + // MessagingThrottlingInterval contains the number of MINUTES to wait before sending the next message var interval = this.GetPortalSettingAsDouble("MessagingThrottlingInterval", sender.PortalID, DefaultMessagingThrottlingInterval) * 60; if (interval > 0 && !this.IsAdminOrHost(sender)) @@ -167,7 +167,7 @@ public virtual int WaitTimeForNextMessage(UserInfo sender) waitTime = (int)(interval - this.GetDateTimeNow().Subtract(lastSentMessage.CreatedOnDate).TotalSeconds); } } - + return waitTime < 0 ? 0 : waitTime; } @@ -204,13 +204,13 @@ public virtual int RecipientLimit(int portalId) } /// Whether disable regular users to send message to user/group, default is false. - /// Portal Id. + /// Portal Id. /// public virtual bool DisablePrivateMessage(int portalId) { return this.GetPortalSetting("DisablePrivateMessage", portalId, "N") == "Y"; - } - + } + public virtual MessageBoxView GetArchivedMessages(int userId, int afterMessageId, int numberOfRecords) { var reader = this._dataService.GetArchiveBoxView(userId, PortalController.GetEffectivePortalId(this.GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, ConstSortColumnDate, !ConstAscending); @@ -251,11 +251,11 @@ public virtual MessageThreadsView GetMessageThread(int conversationId, int userI messageThreadView.Attachments = this._dataService.GetMessageAttachmentsByMessage(messageThreadView.Conversation.MessageID); } - if (messageThreadsView.Conversations == null) - { - messageThreadsView.Conversations = new List(); - } - + if (messageThreadsView.Conversations == null) + { + messageThreadsView.Conversations = new List(); + } + messageThreadsView.Conversations.Add(messageThreadView); } } @@ -296,8 +296,8 @@ public virtual MessageBoxView GetSentbox(int userId, int afterMessageId, int num { var reader = this._dataService.GetSentBoxView(userId, PortalController.GetEffectivePortalId(this.GetCurrentUserInfo().PortalID), afterMessageId, numberOfRecords, sortColumn, sortAscending); return new MessageBoxView { Conversations = CBO.FillCollection(reader) }; - } - + } + public virtual int CheckReplyHasRecipients(int conversationId, int userId) { return userId <= 0 ? 0 : @@ -316,11 +316,11 @@ public virtual int CountMessagesByConversation(int conversationId) public virtual int CountConversations(int userId, int portalId) { - if (userId <= 0) - { - return 0; - } - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNotificationsConversationCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -337,11 +337,11 @@ public virtual int CountConversations(int userId, int portalId) public virtual int CountUnreadMessages(int userId, int portalId) { - if (userId <= 0) - { - return 0; - } - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNewThreadsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -380,10 +380,10 @@ 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) { this._dataService.ConvertLegacyMessages(pageIndex, pageSize); @@ -407,8 +407,28 @@ public int CountLegacyMessages() } return totalRecords; - } - + } + + public IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize) + { + return CBO.FillCollection(this._dataService.GetNextMessagesForInstantDispatch(schedulerInstance, batchSize)); + } + + public IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize) + { + return CBO.FillCollection(this._dataService.GetNextMessagesForDigestDispatch(Convert.ToInt32(frequency), schedulerInstance, batchSize)); + } + + public virtual void MarkMessageAsDispatched(int messageId, int recipientId) + { + this._dataService.MarkMessageAsDispatched(messageId, recipientId); + } + + public virtual void MarkMessageAsSent(int messageId, int recipientId) + { + this._dataService.MarkMessageAsSent(messageId, recipientId); + } + internal virtual DateTime GetDateTimeNow() { return DateTime.UtcNow; @@ -443,26 +463,6 @@ internal virtual string InputFilter(string input) { var ps = PortalSecurity.Instance; return ps.InputFilter(input, PortalSecurity.FilterFlag.NoProfanity); - } - - public IList GetNextMessagesForInstantDispatch(Guid schedulerInstance, int batchSize) - { - return CBO.FillCollection(this._dataService.GetNextMessagesForInstantDispatch(schedulerInstance, batchSize)); - } - - public IList GetNextMessagesForDigestDispatch(Frequency frequency, Guid schedulerInstance, int batchSize) - { - return CBO.FillCollection(this._dataService.GetNextMessagesForDigestDispatch(Convert.ToInt32(frequency), schedulerInstance, batchSize)); - } - - public virtual void MarkMessageAsDispatched(int messageId, int recipientId) - { - this._dataService.MarkMessageAsDispatched(messageId, recipientId); } - - public virtual void MarkMessageAsSent(int messageId, int recipientId) - { - this._dataService.MarkMessageAsSent(messageId, recipientId); - } } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs index c172a10e8b6..e3e75e5a75e 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageConversationView.cs @@ -26,6 +26,33 @@ public class MessageConversationView : IHydratable private string _displayDate; private DateTime _createdOnDate; + /// + /// Gets a pretty printed string with the time since the message was created. + /// + public string DisplayDate + { + get + { + if (string.IsNullOrEmpty(this._displayDate)) + { + this._displayDate = DateUtils.CalculateDateForDisplay(this._createdOnDate); + } + + return this._displayDate; + } + } + + /// + /// Gets the Sender User Profile URL. + /// + public string SenderProfileUrl + { + get + { + return Globals.UserProfileURL(this.SenderUserID); + } + } + /// /// Gets or sets messageID - The primary key. /// @@ -35,7 +62,7 @@ public int MessageID { return this._messageID; } - + set { this._messageID = value; @@ -82,22 +109,6 @@ public int MessageID /// public int SenderUserID { get; set; } - /// - /// Gets a pretty printed string with the time since the message was created. - /// - public string DisplayDate - { - get - { - if (string.IsNullOrEmpty(this._displayDate)) - { - this._displayDate = DateUtils.CalculateDateForDisplay(this._createdOnDate); - } - - return this._displayDate; - } - } - /// /// Gets or sets iHydratable.KeyID. /// @@ -107,7 +118,7 @@ public int KeyID { return this.MessageID; } - + set { this.MessageID = value; @@ -134,17 +145,6 @@ public int KeyID /// public int ThreadCount { get; set; } - /// - /// Gets the Sender User Profile URL. - /// - public string SenderProfileUrl - { - get - { - return Globals.UserProfileURL(this.SenderUserID); - } - } - /// /// Fill the object with data from database. /// diff --git a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs index bc1f55c1a13..ece38b4eaf1 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Internal/Views/MessageFileView.cs @@ -31,15 +31,15 @@ public class MessageFileView public string Size { get { return this._size; } - + set { long bytes; - if (!long.TryParse(value, out bytes)) - { - return; - } - + if (!long.TryParse(value, out bytes)) + { + return; + } + const int scale = 1024; var orders = new[] { "GB", "MB", "KB", "B" }; var max = (long)Math.Pow(scale, orders.Length - 1); @@ -54,7 +54,7 @@ public string Size max /= scale; } - + this._size = "0 B"; } } diff --git a/DNN Platform/Library/Services/Social/Messaging/Message.cs b/DNN Platform/Library/Services/Social/Messaging/Message.cs index 59043428aea..996ea9e8fd4 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Message.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Message.cs @@ -27,6 +27,23 @@ public class Message : BaseEntityInfo, IHydratable private int _messageID = -1; private string _displayDate; + /// + /// Gets a pretty printed string with the time since the message was created. + /// + [XmlAttribute] + public string DisplayDate + { + get + { + if (string.IsNullOrEmpty(this._displayDate)) + { + this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); + } + + return this._displayDate; + } + } + /// /// Gets or sets messageID - The primary key. /// @@ -37,7 +54,7 @@ public int MessageID { return this._messageID; } - + set { this._messageID = value; @@ -98,23 +115,6 @@ public int MessageID [XmlAttribute] public int SenderUserID { get; set; } - /// - /// Gets a pretty printed string with the time since the message was created. - /// - [XmlAttribute] - public string DisplayDate - { - get - { - if (string.IsNullOrEmpty(this._displayDate)) - { - this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); - } - - return this._displayDate; - } - } - /// /// Gets or sets iHydratable.KeyID. /// @@ -125,7 +125,7 @@ public int KeyID { return this.MessageID; } - + set { this.MessageID = value; @@ -148,7 +148,7 @@ public void Fill(IDataReader dr) this.ReplyAllAllowed = Null.SetNullBoolean(dr["ReplyAllAllowed"]); this.SenderUserID = Convert.ToInt32(dr["SenderUserID"]); this.NotificationTypeID = Null.SetNullInteger(dr["NotificationTypeID"]); - + // add audit column data this.FillInternal(dr); } diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs index 95dd2cc7516..41c1b3da592 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageAttachment.cs @@ -35,7 +35,7 @@ public int MessageAttachmentID { return this._messageattachmentID; } - + set { this._messageattachmentID = value; @@ -53,7 +53,7 @@ public int MessageAttachmentID /// [XmlAttribute] public int FileID { get; set; } - + /// /// Gets or sets iHydratable.KeyID. /// @@ -64,7 +64,7 @@ public int KeyID { return this.MessageAttachmentID; } - + set { this.MessageAttachmentID = value; diff --git a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs index 91da96f149f..045726ef9ce 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessageRecipient.cs @@ -35,7 +35,7 @@ public int RecipientID { return this._recipientID; } - + set { this._recipientID = value; @@ -59,7 +59,7 @@ public int RecipientID /// [XmlAttribute] public bool Read { get; set; } - + /// /// Gets or sets a value indicating whether is Message archived. True: Yes, False: No. /// @@ -76,7 +76,7 @@ public int KeyID { return this.RecipientID; } - + set { this.RecipientID = value; diff --git a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs index 58c930106d3..5c089c67960 100644 --- a/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/MessagingController.cs @@ -37,21 +37,16 @@ public class MessagingController 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 ConstDefaultPageSize = 10; internal const string ConstSortColumnDate = "CreatedOnDate"; internal const string ConstSortColumnFrom = "From"; internal const string ConstSortColumnSubject = "Subject"; internal const bool ConstAscending = true; - internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. - - private readonly IDataService _dataService; - - public MessagingController() + internal const double DefaultMessagingThrottlingInterval = 0.5; // default MessagingThrottlingInterval set to 30 seconds. + + private readonly IDataService _dataService; + + public MessagingController() : this(DataService.Instance) { } @@ -62,8 +57,8 @@ public MessagingController(IDataService dataService) Requires.NotNull("dataService", dataService); this._dataService = dataService; - } - + } + public virtual void SendMessage(Message message, IList roles, IList users, IList fileIDs) { this.SendMessage(message, roles, users, fileIDs, UserController.Instance.GetCurrentUserInfo()); @@ -122,10 +117,10 @@ public virtual void SendMessage(Message message, IList roles, IList !string.IsNullOrEmpty(user.DisplayName))) - { - sbTo.Append(user.DisplayName + ","); - } + foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) + { + sbTo.Append(user.DisplayName + ","); + } } if (sbTo.Length == 0) @@ -154,16 +149,16 @@ public virtual void SendMessage(Message message, IList roles, IList InternalMessagingController.Instance.RecipientLimit(sender.PortalID)) { throw new RecipientLimitExceededException(Localization.GetString("MsgRecipientLimitExceeded", Localization.ExceptionsResourceFile)); @@ -236,8 +231,8 @@ public virtual void SendMessage(Message message, IList roles, IList GetFactory() + { + return () => new MessagingController(); + } + private bool CanViewFile(int fileId) { var file = FileManager.Instance.GetFile(fileId); diff --git a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs index c307cdad161..d9c84c45516 100644 --- a/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs +++ b/DNN Platform/Library/Services/Social/Messaging/Scheduler/CoreMessagingScheduler.cs @@ -424,7 +424,7 @@ private static string RemoveHttpUrlsIfSiteisSSLEnabled(string stringContainingHt var urlReplaceWith = $"https://{portalSettings.DefaultPortalAlias}"; stringContainingHttp = stringContainingHttp.Replace(urlToReplace, urlReplaceWith); } - + return stringContainingHttp; } diff --git a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs index fb2769ab73d..7f4faf035e8 100644 --- a/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs +++ b/DNN Platform/Library/Services/Social/Messaging/UserPreferencesController.cs @@ -13,10 +13,10 @@ namespace DotNetNuke.Services.Social.Messaging using DotNetNuke.Services.Social.Messaging.Data; public class UserPreferencesController : ServiceLocator, IUserPreferencesController - { - private readonly IDataService dataService; - - public UserPreferencesController() + { + private readonly IDataService dataService; + + public UserPreferencesController() : this(DataService.Instance) { } @@ -27,21 +27,21 @@ public UserPreferencesController(IDataService dataService) Requires.NotNull("dataService", dataService); this.dataService = dataService; - } - + } + 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) { return CBO.FillObject(this.dataService.GetUserPreference(userinfo.PortalID, userinfo.UserID)); - } + } + + protected override Func GetFactory() + { + return () => new UserPreferencesController(); + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs index 76a787d8b9e..602b650b8d5 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Data/DataService.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Services.Social.Notifications.Data internal class DataService : ComponentBase, IDataService { - private const string Prefix = "CoreMessaging_"; + private const string Prefix = "CoreMessaging_"; private readonly DataProvider _provider = DataProvider.Instance(); - + public int CreateNotificationType(string name, string description, int timeToLive, int desktopModuleId, int createUpdateUserId, bool isTask) { return this._provider.ExecuteScalar(GetFullyQualifiedName("CreateNotificationType"), name, this._provider.GetNull(description), this._provider.GetNull(timeToLive), this._provider.GetNull(desktopModuleId), createUpdateUserId, isTask); @@ -25,11 +25,6 @@ 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) { @@ -39,8 +34,8 @@ public IDataReader GetNotificationType(int notificationTypeId) public IDataReader GetNotificationTypeByName(string name) { return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeByName"), name); - } - + } + public int AddNotificationTypeAction(int notificationTypeId, string nameResourceKey, string descriptionResourceKey, string confirmResourceKey, string apiCall, int createdByUserId) { return this._provider.ExecuteScalar(GetFullyQualifiedName("AddNotificationTypeAction"), notificationTypeId, nameResourceKey, this._provider.GetNull(descriptionResourceKey), this._provider.GetNull(confirmResourceKey), apiCall, createdByUserId); @@ -64,12 +59,12 @@ public IDataReader GetNotificationTypeActionByName(int notificationTypeId, strin public IDataReader GetNotificationTypeActions(int notificationTypeId) { return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationTypeActions"), notificationTypeId); - } - + } + public int SendNotification(Notification notification, int portalId) { var createdByUserId = UserController.Instance.GetCurrentUserInfo().UserID; - return this._provider.ExecuteScalar( + return this._provider.ExecuteScalar( GetFullyQualifiedName("SendNotification"), notification.NotificationTypeID, portalId, @@ -112,11 +107,11 @@ public IDataReader GetNotification(int notificationId) public IDataReader GetNotificationByContext(int notificationTypeId, string context) { return this._provider.ExecuteReader(GetFullyQualifiedName("GetNotificationByContext"), notificationTypeId, context); - } - + } + public bool IsToastPending(int notificationId) { - return this._provider.ExecuteScalar( + return this._provider.ExecuteScalar( GetFullyQualifiedName("IsToastPending"), notificationId); } @@ -144,6 +139,11 @@ public void MarkToastSent(int notificationId, int userId) public IDataReader GetToasts(int userId, int portalId) { return this._provider.ExecuteReader(GetFullyQualifiedName("GetToasts"), userId, portalId); - } + } + + private static string GetFullyQualifiedName(string procedureName) + { + return Prefix + procedureName; + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs index b3e49ed42b3..6c9dd48b1c1 100644 --- a/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/INotificationsController.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.Social.Notifications /// Defines the methods to work with Notifications, NotificationTypes, NotificationTypeActions and NotificationActions. /// public interface INotificationsController - { + { /// /// Creates a new notification type. /// @@ -39,8 +39,8 @@ public interface INotificationsController /// /// The notification type name. /// The notification type with the provided name. - NotificationType GetNotificationType(string name); - + NotificationType GetNotificationType(string name); + /// /// Deletes an existing notification type action. /// @@ -74,8 +74,8 @@ public interface INotificationsController /// /// The actions. /// Id of the notification type. - void SetNotificationTypeActions(IList actions, int notificationTypeId); - + void SetNotificationTypeActions(IList actions, int notificationTypeId); + /// /// Creates a new notification and sets is sender as the portal administrator. /// @@ -155,8 +155,8 @@ public interface INotificationsController /// Id of the notification type. /// Context set by creator of the notification. /// The filtered list of notifications sent to the provided user in the specified portal. - IList GetNotificationByContext(int notificationTypeId, string context); - + IList GetNotificationByContext(int notificationTypeId, string context); + /// /// Is there a Toast that needs to be sent for a Notification. /// @@ -183,6 +183,6 @@ public interface INotificationsController /// /// UserInfo object. /// List of Undelivered Toasts for the user specific to the portal. - IList GetToasts(UserInfo userInfo); + IList GetToasts(UserInfo userInfo); } } diff --git a/DNN Platform/Library/Services/Social/Notifications/Notification.cs b/DNN Platform/Library/Services/Social/Notifications/Notification.cs index 1a8b4598059..66d6e259d93 100644 --- a/DNN Platform/Library/Services/Social/Notifications/Notification.cs +++ b/DNN Platform/Library/Services/Social/Notifications/Notification.cs @@ -23,19 +23,36 @@ namespace DotNetNuke.Services.Social.Notifications /// ----------------------------------------------------------------------------- [Serializable] public class Notification : BaseEntityInfo, IHydratable - { + { private int _notificationID = -1; - private string _displayDate; - - /// + private string _displayDate; + + /// /// Initializes a new instance of the class. /// Default constructor. /// public Notification() { this.SendToast = true; - } - + } + + /// + /// Gets a pretty printed string with the time since the message was created. + /// + [XmlAttribute] + public string DisplayDate + { + get + { + if (string.IsNullOrEmpty(this._displayDate)) + { + this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); + } + + return this._displayDate; + } + } + /// /// Gets or sets notificationID - The primary key. /// @@ -46,7 +63,7 @@ public int NotificationID { return this._notificationID; } - + set { this._notificationID = value; @@ -95,23 +112,6 @@ public int NotificationID [XmlAttribute] public int SenderUserID { get; set; } - /// - /// Gets a pretty printed string with the time since the message was created. - /// - [XmlAttribute] - public string DisplayDate - { - get - { - if (string.IsNullOrEmpty(this._displayDate)) - { - this._displayDate = DateUtils.CalculateDateForDisplay(this.CreatedOnDate); - } - - return this._displayDate; - } - } - /// /// Gets or sets for notifications, this field indicates when it has to be removed (or not displayed). /// @@ -128,7 +128,7 @@ public int KeyID { return this.NotificationID; } - + set { this.NotificationID = value; @@ -145,8 +145,8 @@ public int KeyID /// Gets or sets a value indicating whether the notification is displayed on the UI as a toast notification. /// [XmlAttribute] - public bool SendToast { get; set; } - + public bool SendToast { get; set; } + /// /// Fill the object with data from database. /// @@ -179,6 +179,6 @@ public void Fill(IDataReader dr) // add audit column data this.FillInternal(dr); - } + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs index 92868be7ccf..7c8f4120e8c 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationType.cs @@ -38,7 +38,7 @@ public int NotificationTypeId { return this._notificationTypeId; } - + set { this._notificationTypeId = value; @@ -79,7 +79,7 @@ public int DesktopModuleId { return this._desktopModuleId; } - + set { this._desktopModuleId = value; @@ -93,8 +93,8 @@ public int DesktopModuleId /// Tasks are primarily notifications where an action must be taken. Dismiss is usually not enough. /// [XmlAttribute] - public bool IsTask { get; set; } - + public bool IsTask { get; set; } + /// /// Gets or sets iHydratable.KeyID. /// @@ -119,12 +119,12 @@ public void Fill(IDataReader dr) { this.TimeToLive = new TimeSpan(0, timeToLive, 0); } - + this.DesktopModuleId = Null.SetNullInteger(dr["DesktopModuleID"]); this.IsTask = Null.SetNullBoolean(dr["IsTask"]); // add audit column data this.FillInternal(dr); - } + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs index 7f156add21b..e5b2892e592 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationTypeAction.cs @@ -36,7 +36,7 @@ public int NotificationTypeActionId { return this._notificationTypeActionId; } - + set { this._notificationTypeActionId = value; @@ -77,8 +77,8 @@ public int NotificationTypeActionId /// Gets or sets the Service Framework URL to be called when the action is performed. /// [XmlAttribute] - public string APICall { get; set; } - + public string APICall { get; set; } + /// /// Gets or sets iHydratable.KeyID. /// @@ -105,6 +105,6 @@ public void Fill(IDataReader dr) // add audit column data this.FillInternal(dr); - } + } } } diff --git a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs index b0e6660182e..d57b3d77522 100644 --- a/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs +++ b/DNN Platform/Library/Services/Social/Notifications/NotificationsController.cs @@ -32,25 +32,20 @@ public class NotificationsController { internal const int ConstMaxSubject = 400; internal const int ConstMaxTo = 2000; - private const string ToastsCacheKey = "GetToasts_{0}"; - - protected override Func GetFactory() - { - return () => new NotificationsController(); - } + private const string ToastsCacheKey = "GetToasts_{0}"; private readonly IDataService _dataService; - private readonly Messaging.Data.IDataService _messagingDataService; - - /// + private readonly Messaging.Data.IDataService _messagingDataService; + + /// /// Initializes a new instance of the class. /// Default constructor. /// public NotificationsController() : this(DataService.Instance, Messaging.Data.DataService.Instance) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Constructor from specifict data service. /// @@ -63,8 +58,8 @@ public NotificationsController(IDataService dataService, Messaging.Data.IDataSer this._dataService = dataService; this._messagingDataService = messagingDataService; - } - + } + public void SetNotificationTypeActions(IList actions, int notificationTypeId) { Requires.NotNull("actions", actions); @@ -86,7 +81,7 @@ public void SetNotificationTypeActions(IList actions, in foreach (var action in actions) { - action.NotificationTypeActionId = this._dataService.AddNotificationTypeAction( + action.NotificationTypeActionId = this._dataService.AddNotificationTypeAction( notificationTypeId, action.NameResourceKey, action.DescriptionResourceKey, @@ -99,11 +94,11 @@ public void SetNotificationTypeActions(IList actions, in public virtual int CountNotifications(int userId, int portalId) { - if (userId <= 0) - { - return 0; - } - + if (userId <= 0) + { + return 0; + } + var cacheKey = string.Format(DataCache.UserNotificationsCountCacheKey, portalId, userId); var cache = CachingProvider.Instance(); var cacheObject = cache.GetItem(cacheKey); @@ -159,10 +154,10 @@ public virtual void SendNotification(Notification notification, int portalId, IL if (users != null) { - foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) - { - sbTo.Append(user.DisplayName + ","); - } + foreach (var user in users.Where(user => !string.IsNullOrEmpty(user.DisplayName))) + { + sbTo.Append(user.DisplayName + ","); + } } if (sbTo.Length == 0) @@ -206,12 +201,12 @@ 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) @@ -241,7 +236,7 @@ public void CreateNotificationType(NotificationType notificationType) notificationType.DesktopModuleId = Null.NullInteger; } - notificationType.NotificationTypeId = this._dataService.CreateNotificationType( + notificationType.NotificationTypeId = this._dataService.CreateNotificationType( notificationType.Name, notificationType.Description, (int)notificationType.TimeToLive.TotalMinutes == 0 ? Null.NullInteger : (int)notificationType.TimeToLive.TotalMinutes, @@ -257,7 +252,7 @@ public virtual void DeleteNotification(int notificationId) { DataCache.RemoveCache(string.Format(ToastsCacheKey, recipient.UserID)); } - + this._dataService.DeleteNotification(notificationId); } @@ -325,7 +320,7 @@ public virtual IList GetNotifications(int userId, int portalId, in { pid = PortalController.GetEffectivePortalId(portalId); } - + return userId <= 0 ? new List(0) : CBO.FillCollection(this._dataService.GetNotifications(userId, pid, afterNotificationId, numberOfRecords)); @@ -366,8 +361,8 @@ public virtual NotificationTypeAction GetNotificationTypeAction(int notification public virtual IList GetNotificationTypeActions(int notificationTypeId) { return CBO.FillCollection(this._dataService.GetNotificationTypeActions(notificationTypeId)); - } - + } + public bool IsToastPending(int notificationId) { return this._dataService.IsToastPending(notificationId); @@ -401,15 +396,15 @@ public IList GetToasts(UserInfo userInfo) { this._dataService.MarkToastSent(message.NotificationID, userInfo.UserID); } - + // Set the cache to empty toasts object because we don't want to make calls to database everytime for empty objects. // This empty object cache would be cleared by MarkReadyForToast emthod when a new notification arrives for the user. DataCache.SetCache(cacheKey, new List()); } return toasts; - } - + } + internal virtual UserInfo GetAdminUser() { var current = PortalSettings.Current; @@ -476,6 +471,11 @@ internal virtual void RemoveNotificationTypeActionCache() internal virtual void RemoveNotificationTypeCache() { DataCache.ClearCache("NotificationTypes:"); - } + } + + protected override Func GetFactory() + { + return () => new NotificationsController(); + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs index 48337777654..873f246e93d 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/Data/DataService.cs @@ -11,14 +11,14 @@ namespace DotNetNuke.Services.Social.Subscriptions.Data using DotNetNuke.Framework; public class DataService : ServiceLocator, IDataService - { - private readonly DataProvider provider; - + { + private readonly DataProvider provider; + public DataService() { this.provider = DataProvider.Instance(); } - + public int AddSubscriptionType(string subscriptionName, string friendlyName, int desktopModuleId) { return this.provider.ExecuteScalar("CoreMessaging_AddSubscriptionType", subscriptionName, friendlyName, desktopModuleId); @@ -29,19 +29,14 @@ 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; - } - + } + public int AddSubscription(int userId, int portalId, int subscriptionTypeId, string objectKey, string description, int moduleId, int tabId, string objectData) { - return this.provider.ExecuteScalar( + return this.provider.ExecuteScalar( "CoreMessaging_AddSubscription", userId, this.provider.GetNull(portalId), @@ -65,7 +60,7 @@ public IDataReader GetSubscriptionsByContent(int portalId, int subscriptionTypeI public IDataReader IsSubscribed(int portalId, int userId, int subscriptionTypeId, string objectKey, int moduleId, int tabId) { - return this.provider.ExecuteReader( + return this.provider.ExecuteReader( "CoreMessaging_IsSubscribed", this.provider.GetNull(portalId), userId, @@ -82,7 +77,7 @@ public bool DeleteSubscription(int subscriptionId) public int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription) { - return this.provider.ExecuteScalar( + return this.provider.ExecuteScalar( "CoreMessaging_UpdateSubscriptionDescription", objectKey, portalId, @@ -92,6 +87,11 @@ public int UpdateSubscriptionDescription(string objectKey, int portalId, string public void DeleteSubscriptionsByObjectKey(int portalId, string objectKey) { this.provider.ExecuteNonQuery("CoreMessaging_DeleteSubscriptionsByObjectKey", portalId, objectKey); - } + } + + protected override Func GetFactory() + { + return () => new DataService(); + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs index ac3e51ee774..c0de8b88c26 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/ISubscriptionController.cs @@ -57,7 +57,7 @@ public interface ISubscriptionController /// /// Subscription Object Key. /// Portal Id. - /// New Subscription Description. + /// New Subscription Description. /// int UpdateSubscriptionDescription(string objectKey, int portalId, string newDescription); diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs index d78797d957b..bf911978959 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionController.cs @@ -28,7 +28,7 @@ public SubscriptionController() this.dataService = DataService.Instance; this.subscriptionSecurityController = SubscriptionSecurityController.Instance; } - + public IEnumerable GetUserSubscriptions(UserInfo user, int portalId, int subscriptionTypeId = -1) { var subscriptions = CBO.FillCollection(this.dataService.GetSubscriptionsByUser( @@ -49,11 +49,6 @@ 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( @@ -74,7 +69,7 @@ public void AddSubscription(Subscription subscription) Requires.NotNegative("subscription.SubscriptionTypeId", subscription.SubscriptionTypeId); Requires.PropertyNotNull("subscription.ObjectKey", subscription.ObjectKey); - subscription.SubscriptionId = this.dataService.AddSubscription( + subscription.SubscriptionId = this.dataService.AddSubscription( subscription.UserId, subscription.PortalId, subscription.SubscriptionTypeId, @@ -97,11 +92,11 @@ public void DeleteSubscription(Subscription subscription) subscription.ModuleId, subscription.TabId)); - if (subscriptionToDelete == null) - { - return; - } - + if (subscriptionToDelete == null) + { + return; + } + this.dataService.DeleteSubscription(subscriptionToDelete.SubscriptionId); } @@ -116,6 +111,11 @@ public int UpdateSubscriptionDescription(string objectKey, int portalId, string public void DeleteSubscriptionsByObjectKey(int portalId, string objectKey) { this.dataService.DeleteSubscriptionsByObjectKey(portalId, objectKey); - } + } + + protected override Func GetFactory() + { + return () => new SubscriptionController(); + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs index 12ccfa470ad..a9845aecb53 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionSecurityController.cs @@ -37,13 +37,13 @@ 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); @@ -69,6 +69,6 @@ private static ModuleInfo GetModuleFromSubscription(Subscription subscription) private static UserInfo GetUserFromSubscription(Subscription subscription) { return UserController.Instance.GetUser(subscription.PortalId, subscription.UserId); - } + } } } diff --git a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs index f17a76f7c3e..5ccf5e7afeb 100644 --- a/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs +++ b/DNN Platform/Library/Services/Social/Subscriptions/SubscriptionTypeController.cs @@ -25,7 +25,7 @@ public SubscriptionTypeController() { this.dataService = DataService.Instance; } - + public void AddSubscriptionType(SubscriptionType subscriptionType) { Requires.NotNull("subscriptionType", subscriptionType); @@ -45,19 +45,14 @@ public SubscriptionType GetSubscriptionType(Func predica return this.GetSubscriptionTypes().SingleOrDefault(predicate); } - protected override Func GetFactory() - { - return () => new SubscriptionTypeController(); - } - public IEnumerable GetSubscriptionTypes() { - var cacheArgs = new CacheItemArgs( + var cacheArgs = new CacheItemArgs( DataCache.SubscriptionTypesCacheKey, DataCache.SubscriptionTypesTimeOut, DataCache.SubscriptionTypesCachePriority); - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( cacheArgs, c => CBO.FillCollection(this.dataService.GetSubscriptionTypes())); } @@ -76,8 +71,13 @@ public void DeleteSubscriptionType(SubscriptionType subscriptionType) this.dataService.DeleteSubscriptionType(subscriptionType.SubscriptionTypeId); CleanCache(); - } - + } + + protected override Func GetFactory() + { + return () => new SubscriptionTypeController(); + } + private static void CleanCache() { DataCache.RemoveCache(DataCache.SubscriptionTypesCacheKey); diff --git a/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs b/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs index 0dfc2f5c966..ce077c3e15d 100644 --- a/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs +++ b/DNN Platform/Library/Services/Syndication/SyndicationHandlerBase.cs @@ -35,7 +35,7 @@ public int TabId this._tabId = Null.NullInteger; } } - + return this._tabId; } } @@ -51,7 +51,7 @@ public int ModuleId this._moduleId = Null.NullInteger; } } - + return this._moduleId; } } diff --git a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs index ada00e37b88..a9d8d78f08b 100644 --- a/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseCustomTokenReplace.cs @@ -30,8 +30,8 @@ public abstract class BaseCustomTokenReplace : BaseTokenReplace /// /// Gets or sets a value indicating whether if DebugMessages are enabled, unknown Tokens are replaced with Error Messages. /// - /// - /// If DebugMessages are enabled, unknown Tokens are replaced with Error Messages + /// + /// If DebugMessages are enabled, unknown Tokens are replaced with Error Messages /// /// /// @@ -80,7 +80,7 @@ public CacheLevel Cacheability(string sourceText) } } } - + return isSafe; } @@ -95,7 +95,7 @@ public bool ContainsTokens(string strSourceText) { return this.TokenizerRegex.Matches(strSourceText).Cast().Any(currentMatch => currentMatch.Result("${object}").Length > 0); } - + return false; } @@ -116,11 +116,11 @@ protected override string replacedTokenValue(string objectName, string propertyN { message = "Error accessing [{0}:{1}], {0} is an unknown datasource"; } - + result = string.Format(message, objectName, propertyName); } } - + if (this.DebugMessages && propertyNotFound) { string message; @@ -132,12 +132,12 @@ protected override string replacedTokenValue(string objectName, string propertyN { 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); } diff --git a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs index b811555bcb1..8e791291219 100644 --- a/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/BaseTokenReplace.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Services.Tokens public abstract class BaseTokenReplace { protected const string ObjectLessToken = "no_object"; - + private const string ExpressionDefault = "(?:(?\\[\\])|\\[(?:(?[^{}\\]\\[:]+):(?[^\\]\\[\\|]+))(?:\\|(?:(?[^\\]\\[]+)\\|(?[^\\]\\[]+))|\\|(?:(?[^\\|\\]\\[]+)))?\\])|(?\\[[^\\]\\[]+\\])|(?[^\\]\\[]+)"; @@ -32,7 +32,7 @@ public abstract class BaseTokenReplace private const string TokenReplaceCacheKeyDefault = "TokenReplaceRegEx_Default"; private const string TokenReplaceCacheKeyObjectless = "TokenReplaceRegEx_Objectless"; - + private CultureInfo _formatProvider; private string _language; @@ -46,7 +46,7 @@ public string Language { return this._language; } - + set { this._language = value; @@ -54,8 +54,6 @@ public string Language } } - protected bool UseObjectLessExpression { get; set; } - /// /// Gets the Format provider as Culture info from stored language or current culture. /// @@ -80,11 +78,13 @@ protected Regex TokenizerRegex tokenizer = RegexUtils.GetCachedRegex(this.UseObjectLessExpression ? ExpressionObjectLess : ExpressionDefault); DataCache.SetCache(cacheKey, tokenizer); } - + return tokenizer; } } + protected bool UseObjectLessExpression { get; set; } + // ReSharper disable once InconsistentNaming protected abstract string replacedTokenValue(string objectName, string propertyName, string format); @@ -94,7 +94,7 @@ protected virtual string ReplaceTokens(string sourceText) { return string.Empty; } - + var result = new StringBuilder(); foreach (Match currentMatch in this.TokenizerRegex.Matches(sourceText)) { @@ -105,7 +105,7 @@ protected virtual string ReplaceTokens(string sourceText) { objectName = ObjectLessToken; } - + string propertyName = currentMatch.Result("${property}"); string format = currentMatch.Result("${format}"); string ifEmptyReplacment = currentMatch.Result("${ifEmpty}"); @@ -114,7 +114,7 @@ protected virtual string ReplaceTokens(string sourceText) { conversion = ifEmptyReplacment; } - + result.Append(conversion); } else @@ -122,7 +122,7 @@ protected virtual string ReplaceTokens(string sourceText) result.Append(currentMatch.Result("${text}")); } } - + return result.ToString(); } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs index e97ebf69ee9..3cf7da906c5 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/ArrayListPropertyAccesss.cs @@ -16,7 +16,7 @@ public class ArrayListPropertyAccess : IPropertyAccess public ArrayListPropertyAccess(ArrayList list) { this.custom = list; - } + } public CacheLevel Cacheability { @@ -24,28 +24,28 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { if (this.custom == null) { return string.Empty; } - + object valueObject = null; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } - + int intIndex = int.Parse(propertyName); if ((this.custom != null) && this.custom.Count > intIndex) { valueObject = this.custom[intIndex].ToString(); } - + if (valueObject != null) { switch (valueObject.GetType().Name) diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs index a3df44f539c..d580073ace2 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CssPropertyAccess.cs @@ -40,12 +40,12 @@ protected override string ProcessToken(StylesheetDto model, UserInfo accessingUs { throw new ArgumentException("The Css token must specify a path or property."); } - + if (model.Priority == 0) { model.Priority = (int)FileOrder.Css.DefaultPriority; } - + if (string.IsNullOrEmpty(model.Provider)) { ClientResourceManager.RegisterStyleSheet(this._page, model.Path, model.Priority); diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs index 3a53aa65809..2c10eadc7f2 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/CulturePropertyAccess.cs @@ -10,15 +10,15 @@ namespace DotNetNuke.Services.Tokens using DotNetNuke.Services.Localization; 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; @@ -26,37 +26,37 @@ public string GetProperty(string propertyName, string format, CultureInfo format { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.EnglishName), format); } - + if (propertyName.Equals(CultureDropDownTypes.Lcid.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return ci.LCID.ToString(); } - + if (propertyName.Equals(CultureDropDownTypes.Name.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.Name, format); } - + if (propertyName.Equals(CultureDropDownTypes.NativeName.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.NativeName), format); } - + if (propertyName.Equals(CultureDropDownTypes.TwoLetterIsoCode.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.TwoLetterISOLanguageName, format); } - + if (propertyName.Equals(CultureDropDownTypes.ThreeLetterIsoCode.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.ThreeLetterISOLanguageName, format); } - + if (propertyName.Equals(CultureDropDownTypes.DisplayName.ToString(), StringComparison.InvariantCultureIgnoreCase)) { return PropertyAccess.FormatString(ci.DisplayName, format); } - + if (propertyName.Equals("languagename", StringComparison.InvariantCultureIgnoreCase)) { if (ci.IsNeutralCulture) @@ -68,7 +68,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.EnglishName), format); } } - + if (propertyName.Equals("languagenativename", StringComparison.InvariantCultureIgnoreCase)) { if (ci.IsNeutralCulture) @@ -80,7 +80,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(ci.Parent.NativeName), format); } } - + if (propertyName.Equals("countryname", StringComparison.InvariantCultureIgnoreCase)) { if (ci.IsNeutralCulture) @@ -94,7 +94,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.EnglishName), format); } } - + if (propertyName.Equals("countrynativename", StringComparison.InvariantCultureIgnoreCase)) { if (ci.IsNeutralCulture) @@ -108,7 +108,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format return PropertyAccess.FormatString(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(country.NativeName), format); } } - + PropertyNotFound = true; return string.Empty; } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs index 93dbfb2d065..2759452c429 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DataRowPropertyAccess.cs @@ -16,7 +16,7 @@ public class DataRowPropertyAccess : IPropertyAccess public DataRowPropertyAccess(DataRow row) { this.dr = row; - } + } public CacheLevel Cacheability { @@ -24,22 +24,22 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - + } + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { if (this.dr == null) { return string.Empty; } - + object valueObject = this.dr[propertyName]; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } - + if (valueObject != null) { switch (valueObject.GetType().Name) diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs index 33c70ff51f3..fe9e47c7d84 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DateTimePropertyAccess.cs @@ -9,15 +9,15 @@ namespace DotNetNuke.Services.Tokens using DotNetNuke.Entities.Users; 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; @@ -28,28 +28,28 @@ public string GetProperty(string propertyName, string format, CultureInfo format { format = "D"; } - + return TimeZoneInfo.ConvertTime(DateTime.Now, userTimeZone).ToString(format, formatProvider); case "now": if (format == string.Empty) { format = "g"; } - + return TimeZoneInfo.ConvertTime(DateTime.Now, userTimeZone).ToString(format, formatProvider); case "system": if (format == string.Empty) { format = "g"; } - + return DateTime.Now.ToString(format, formatProvider); case "utc": if (format == string.Empty) { format = "g"; } - + return DateTime.Now.ToUniversalTime().ToString(format, formatProvider); default: PropertyNotFound = true; diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs index aefa16d06a5..a0f810b35ab 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/DictionaryPropertyAccess.cs @@ -16,7 +16,7 @@ public class DictionaryPropertyAccess : IPropertyAccess public DictionaryPropertyAccess(IDictionary list) { this.NameValueCollection = list; - } + } public CacheLevel Cacheability { @@ -24,22 +24,22 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - + } + public virtual string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound) { if (this.NameValueCollection == null) { return string.Empty; } - + object valueObject = this.NameValueCollection[propertyName]; string OutputFormat = format; if (string.IsNullOrEmpty(format)) { OutputFormat = "g"; } - + if (valueObject != null) { switch (valueObject.GetType().Name) diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs index bf9ca9e1d52..3f0f08782d7 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/EmptyPropertyAccess.cs @@ -12,15 +12,15 @@ namespace DotNetNuke.Services.Tokens /// /// public class EmptyPropertyAccess : IPropertyAccess - { + { public CacheLevel Cacheability { get { 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/JavaScriptPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs index ded946edfb2..0403655a615 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/JavaScriptPropertyAccess.cs @@ -52,12 +52,12 @@ protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUs { throw new ArgumentException("If the jsname property is not specified then the JavaScript token must specify a path or property."); } - + if (model.Priority == 0) { model.Priority = (int)FileOrder.Js.DefaultPriority; } - + if (string.IsNullOrEmpty(model.Provider)) { ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority); @@ -73,7 +73,7 @@ protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUs { model.Priority = (int)FileOrder.Js.DefaultPriority; } - + if (string.IsNullOrEmpty(model.Provider)) { ClientResourceManager.RegisterScript(this._page, model.Path, model.Priority, string.Empty, model.JsName, model.Version); @@ -110,7 +110,7 @@ protected override string ProcessToken(JavaScriptDto model, UserInfo accessingUs } } } - + JavaScript.RequestRegistration(model.JsName, version, specific); } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs index a334d3622f3..03de66b4236 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/PropertyAccess.cs @@ -31,7 +31,7 @@ public static string ContentLocked { return "*******"; } - } + } public CacheLevel Cacheability { @@ -39,8 +39,8 @@ public CacheLevel Cacheability { return CacheLevel.notCacheable; } - } - + } + /// /// Boolean2LocalizedYesNo returns the translated string for "yes" or "no" against a given boolean value. /// @@ -76,16 +76,6 @@ 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. @@ -122,7 +112,7 @@ public static string GetObjectProperty(object objObject, string strPropertyName, { strFormat = "g"; } - + return ((IFormattable)propValue).ToString(strFormat, formatProvider); } } @@ -131,9 +121,19 @@ public static string GetObjectProperty(object objObject, string strPropertyName, return string.Empty; } } - + PropertyNotFound = true; 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); + } } } diff --git a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs index 5b0ee6de526..581ec04ff6d 100644 --- a/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs +++ b/DNN Platform/Library/Services/Tokens/PropertyAccess/TicksPropertyAccess.cs @@ -12,15 +12,15 @@ namespace DotNetNuke.Services.Tokens using DotNetNuke.Entities.Users; 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()) @@ -32,7 +32,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format case "ticksperday": return TimeSpan.TicksPerDay.ToString(formatProvider); } - + PropertyNotFound = true; return string.Empty; } diff --git a/DNN Platform/Library/Services/Tokens/TokenReplace.cs b/DNN Platform/Library/Services/Tokens/TokenReplace.cs index 0bfa86c1681..afeeaa4d239 100644 --- a/DNN Platform/Library/Services/Tokens/TokenReplace.cs +++ b/DNN Platform/Library/Services/Tokens/TokenReplace.cs @@ -25,49 +25,49 @@ namespace DotNetNuke.Services.Tokens /// public class TokenReplace : BaseCustomTokenReplace { - private ModuleInfo _moduleInfo; - - /// + private ModuleInfo _moduleInfo; + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for default context. /// - public TokenReplace() + public TokenReplace() : this(Scope.DefaultSettings, null, null, null, Null.NullInteger) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for default context and the current module. /// /// ID of the current module. - public TokenReplace(int moduleID) + public TokenReplace(int moduleID) : this(Scope.DefaultSettings, null, null, null, moduleID) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for custom context. /// /// Security level granted by the calling object. - public TokenReplace(Scope accessLevel) + public TokenReplace(Scope accessLevel) : this(accessLevel, null, null, null, Null.NullInteger) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for custom context. /// /// Security level granted by the calling object. /// ID of the current module. - public TokenReplace(Scope accessLevel, int moduleID) + public TokenReplace(Scope accessLevel, int moduleID) : this(accessLevel, null, null, null, moduleID) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for custom context. /// @@ -75,12 +75,12 @@ public TokenReplace(Scope accessLevel, int moduleID) /// Locale to be used for formatting etc. /// PortalSettings to be used. /// user, for which the properties shall be returned. - public TokenReplace(Scope accessLevel, string language, PortalSettings portalSettings, UserInfo user) + public TokenReplace(Scope accessLevel, string language, PortalSettings portalSettings, UserInfo user) : this(accessLevel, language, portalSettings, user, Null.NullInteger) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// creates a new TokenReplace object for custom context. /// @@ -106,7 +106,7 @@ public TokenReplace(Scope accessLevel, string language, PortalSettings portalSet { this.PortalSettings = portalSettings; } - + if (user == null) { if (HttpContext.Current != null) @@ -117,7 +117,7 @@ public TokenReplace(Scope accessLevel, string language, PortalSettings portalSet { this.User = new UserInfo(); } - + this.AccessingUser = this.User; } else @@ -132,14 +132,14 @@ public TokenReplace(Scope accessLevel, string language, PortalSettings portalSet this.AccessingUser = new UserInfo(); } } - + this.Language = string.IsNullOrEmpty(language) ? new Localization.Localization().CurrentUICulture : language; if (moduleID != Null.NullInteger) { this.ModuleId = moduleID; } } - + this.PropertySource["date"] = new DateTimePropertyAccess(); this.PropertySource["datetime"] = new DateTimePropertyAccess(); this.PropertySource["ticks"] = new TicksPropertyAccess(); @@ -170,10 +170,10 @@ public ModuleInfo ModuleInfo this._moduleInfo = ModuleController.Instance.GetModule(this.ModuleId, Null.NullInteger, true); } } - + return this._moduleInfo; } - + set { this._moduleInfo = value; @@ -216,48 +216,6 @@ public string ReplaceEnvironmentTokens(string sourceText, DataRow row) return this.ReplaceTokens(sourceText); } - /// - /// setup context by creating appropriate objects. - /// - /// - /// security is not the purpose of the initialization, this is in the responsibility of each property access class. - /// - private void InitializePropertySources() - { - // Cleanup, by default "" is returned for these objects and any property - IPropertyAccess defaultPropertyAccess = new EmptyPropertyAccess(); - this.PropertySource["portal"] = defaultPropertyAccess; - this.PropertySource["tab"] = defaultPropertyAccess; - this.PropertySource["host"] = defaultPropertyAccess; - this.PropertySource["module"] = defaultPropertyAccess; - this.PropertySource["user"] = defaultPropertyAccess; - this.PropertySource["membership"] = defaultPropertyAccess; - this.PropertySource["profile"] = defaultPropertyAccess; - - // initialization - if (this.CurrentAccessLevel >= Scope.Configuration) - { - if (this.PortalSettings != null) - { - this.PropertySource["portal"] = this.PortalSettings; - this.PropertySource["tab"] = this.PortalSettings.ActiveTab; - } - - this.PropertySource["host"] = new HostPropertyAccess(); - if (this.ModuleInfo != null) - { - this.PropertySource["module"] = this.ModuleInfo; - } - } - - if (this.CurrentAccessLevel >= Scope.DefaultSettings && !(this.User == null || this.User.UserID == -1)) - { - this.PropertySource["user"] = this.User; - this.PropertySource["membership"] = new MembershipPropertyAccess(this.User); - this.PropertySource["profile"] = new ProfilePropertyAccess(this.User); - } - } - /// /// Replaces tokens in sourceText parameter with the property values. /// @@ -297,7 +255,7 @@ public string ReplaceEnvironmentTokens(string sourceText, IDictionary custom, st { this.PropertySource[customCaption.ToLowerInvariant()] = new DictionaryPropertyAccess(custom); } - + return this.ReplaceTokens(sourceText); } @@ -328,5 +286,47 @@ protected override string ReplaceTokens(string sourceText) this.InitializePropertySources(); return base.ReplaceTokens(sourceText); } + + /// + /// setup context by creating appropriate objects. + /// + /// + /// security is not the purpose of the initialization, this is in the responsibility of each property access class. + /// + private void InitializePropertySources() + { + // Cleanup, by default "" is returned for these objects and any property + IPropertyAccess defaultPropertyAccess = new EmptyPropertyAccess(); + this.PropertySource["portal"] = defaultPropertyAccess; + this.PropertySource["tab"] = defaultPropertyAccess; + this.PropertySource["host"] = defaultPropertyAccess; + this.PropertySource["module"] = defaultPropertyAccess; + this.PropertySource["user"] = defaultPropertyAccess; + this.PropertySource["membership"] = defaultPropertyAccess; + this.PropertySource["profile"] = defaultPropertyAccess; + + // initialization + if (this.CurrentAccessLevel >= Scope.Configuration) + { + if (this.PortalSettings != null) + { + this.PropertySource["portal"] = this.PortalSettings; + this.PropertySource["tab"] = this.PortalSettings.ActiveTab; + } + + this.PropertySource["host"] = new HostPropertyAccess(); + if (this.ModuleInfo != null) + { + this.PropertySource["module"] = this.ModuleInfo; + } + } + + if (this.CurrentAccessLevel >= Scope.DefaultSettings && !(this.User == null || this.User.UserID == -1)) + { + this.PropertySource["user"] = this.User; + this.PropertySource["membership"] = new MembershipPropertyAccess(this.User); + this.PropertySource["profile"] = new ProfilePropertyAccess(this.User); + } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs b/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs index 892c04a5b40..f0c7d27626c 100644 --- a/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs +++ b/DNN Platform/Library/Services/Upgrade/DnnInstallLogger.cs @@ -33,10 +33,10 @@ private static StackFrame CallingFrame frameDepth++; reflectedType = stack[frameDepth].GetMethod().ReflectedType; } - + frame = stack[frameDepth]; } - + return frame; } } @@ -47,8 +47,8 @@ private static Type CallingType { return CallingFrame.GetMethod().DeclaringType; } - } - + } + public static void InstallLogError(object message) { LogInstaller("[ERROR]", message.ToString()); @@ -62,8 +62,8 @@ public static void InstallLogError(string message, Exception exception) public static void InstallLogInfo(object message) { LogInstaller("[INFO]", message.ToString()); - } - + } + private static void LogInstaller(string logType, string message) { var logFile = InstallController.Instance.InstallerLogName; diff --git a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs index b2078103a3a..dc7d0320bb0 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/IInstallController.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Services.Upgrade.Internals public interface IInstallController { string InstallerLogName { get; } - + bool IsValidSqlServerVersion(string connectionString); bool IsAbleToPerformDatabaseActions(string connectionString); diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs index b20518e8575..6c5660646f2 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/ConnectionConfig.cs @@ -13,21 +13,21 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration public class ConnectionConfig { public string Server { get; set; } - + public string Database { get; set; } - + public string File { get; set; } - + public bool Integrated { get; set; } - + public string User { get; set; } - + public string Password { get; set; } - + public bool RunAsDbowner { get; set; } - + public string Qualifier { get; set; } - + public string UpgradeConnectionString { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs index 27703882087..767fb05ace2 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/HostSettingConfig.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration public class HostSettingConfig { public string Name { get; set; } - + public string Value { get; set; } - + public bool IsSecure { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs index 8fb242f7e06..a74516385fc 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/InstallConfig.cs @@ -20,21 +20,21 @@ public InstallConfig() this.Scripts = new List(); this.Settings = new List(); } - + public IList Scripts { get; set; } - + public string Version { get; set; } - + public string InstallCulture { get; set; } - + public SuperUserConfig SuperUser { get; set; } - + public ConnectionConfig Connection { get; set; } - + public LicenseConfig License { get; set; } - + public IList Portals { get; set; } - + public IList Settings { get; set; } public string FolderMappingsSettings { get; set; } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs index 8500b1752f4..94f5b24a535 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/LicenseConfig.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration public class LicenseConfig { public string AccountEmail { get; set; } - + public string InvoiceNumber { get; set; } - + public string WebServer { get; set; } - + public string LicenseType { get; set; } - + public bool TrialRequest { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs index 4d48566fa4d..6bebaa21a15 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs @@ -17,29 +17,29 @@ public PortalConfig() { this.PortAliases = new List(); } - + public string PortalName { get; set; } - + public string AdminFirstName { get; set; } - + public string AdminLastName { get; set; } - + public string AdminUserName { get; set; } - + public string AdminPassword { get; set; } - + public string AdminEmail { get; set; } - + public string Description { get; set; } - + public string Keywords { get; set; } - + public string TemplateFileName { get; set; } - + public bool IsChild { get; set; } - + public string HomeDirectory { get; set; } - + public IList PortAliases { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs index c22727a1f69..6fa209edda0 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/SuperUserConfig.cs @@ -13,17 +13,17 @@ namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration public class SuperUserConfig { public string FirstName { get; set; } - + public string LastName { get; set; } - + public string UserName { get; set; } - + public string Password { get; set; } - + public string Email { get; set; } - + public string Locale { get; set; } - + public bool UpdatePassword { get; set; } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs index cdf223bc279..1d1a8b5ebf7 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/InstallControllerImpl.cs @@ -30,12 +30,12 @@ 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. /// @@ -178,7 +178,7 @@ public void SetInstallConfig(InstallConfig installConfig) { portalsNode.RemoveAll(); } - + foreach (PortalConfig portalConfig in installConfig.Portals) { XmlNode portalNode = AppendNewXmlNode(ref installTemplate, ref portalsNode, "portal", null); @@ -211,7 +211,7 @@ public void SetInstallConfig(InstallConfig installConfig) { settingsNode = AppendNewXmlNode(ref installTemplate, ref dotnetnukeNode, "settings", null); } - + // DNN-8833: for this node specifically we should append/overwrite existing but not clear all // else // { @@ -263,7 +263,7 @@ public void RemoveFromInstallConfig(string xmlNodePath) { return; } - + var installTemplate = new XmlDocument { XmlResolver = null }; Upgrade.GetInstallTemplate(installTemplate); XmlNodeList nodes = installTemplate.SelectNodes(xmlNodePath); @@ -271,7 +271,7 @@ public void RemoveFromInstallConfig(string xmlNodePath) { nodes[0].ParentNode.RemoveChild(nodes[0]); } - + Upgrade.SetInstallTemplate(installTemplate); } @@ -385,12 +385,12 @@ public InstallConfig GetInstallConfig() } } } - + installConfig.Settings.Add(new HostSettingConfig { Name = settingNode.Name, Value = settingNode.InnerText, IsSecure = settingIsSecure }); } } } - + var folderMappingsNode = installTemplate.SelectSingleNode("//dotnetnuke/" + FolderMappingsConfigController.Instance.ConfigNode); installConfig.FolderMappingsSettings = (folderMappingsNode != null) ? folderMappingsNode.InnerXml : string.Empty; @@ -414,7 +414,7 @@ public InstallConfig GetInstallConfig() portalConfig.AdminPassword = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "password"); portalConfig.AdminEmail = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "email"); } - + portalConfig.Description = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "description"); portalConfig.Keywords = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "keywords"); portalConfig.TemplateFileName = XmlUtils.GetNodeValue(portalNode.CreateNavigator(), "templatefile"); @@ -433,7 +433,7 @@ public InstallConfig GetInstallConfig() } } } - + installConfig.Portals.Add(portalConfig); } } @@ -460,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; @@ -490,7 +490,7 @@ public bool IsValidSqlServerVersion(string connectionString) { sqlConnection.Close(); } - + return isValidVersion; } @@ -499,7 +499,7 @@ public bool IsAbleToPerformDatabaseActions(string connectionString) var fakeName = "{databaseOwner}[{objectQualifier}FakeTable_" + DateTime.Now.Ticks.ToString("x16") + "]"; var databaseActions = string.Format(@"CREATE TABLE {0}([fakeColumn] [int] NULL); SELECT * FROM {0}; DROP TABLE {0};", fakeName); var strExceptions = DataProvider.Instance().ExecuteScript(connectionString, databaseActions); - + // if no exceptions we have necessary drop etc permissions return string.IsNullOrEmpty(strExceptions); } @@ -530,7 +530,7 @@ public bool IsAvailableLanguagePack(string cultureCode) string downloadUrl = UpdateService.GetLanguageDownloadUrl(cultureCode); string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); - + // no need to download english, always there if (cultureCode != "en-us" && string.IsNullOrEmpty(downloadUrl) != true) { @@ -539,7 +539,7 @@ public bool IsAvailableLanguagePack(string cultureCode) this.GetLanguagePack(downloadUrl, installFolder); return true; } - + return false; } catch (Exception) @@ -551,7 +551,7 @@ public bool IsAvailableLanguagePack(string cultureCode) public CultureInfo GetCurrentLanguage() { CultureInfo pageCulture = null; - + // 1. querystring pageCulture = this.GetCultureFromQs(); @@ -568,7 +568,7 @@ public CultureInfo GetCurrentLanguage() /// Tests the Database Connection using the database connection config. /// /// - /// + /// /// public string TestDatabaseConnection(ConnectionConfig config) { @@ -606,7 +606,7 @@ public CultureInfo GetCultureFromCookie() var culture = new CultureInfo(language); return culture; } - + public CultureInfo GetCultureFromBrowser() { CultureInfo culture = null; @@ -616,7 +616,7 @@ public CultureInfo GetCultureFromBrowser() string language = userLang.Split(';')[0]; culture = new CultureInfo(language); } - + return culture; } @@ -627,7 +627,7 @@ private static XmlNode AppendNewXmlNode(ref XmlDocument document, ref XmlNode pa { newNode.InnerText = elementValue; } - + parentNode.AppendChild(newNode); return newNode; } @@ -647,7 +647,7 @@ private CultureInfo GetCultureFromQs() private void GetLanguagePack(string downloadUrl, string installFolder) { string myfile = string.Empty; - WebResponse wr = Util.GetExternalRequest( + WebResponse wr = Util.GetExternalRequest( downloadUrl, null, null, @@ -662,7 +662,7 @@ private void GetLanguagePack(string downloadUrl, string installFolder) "wpi://2.1.0.0/Microsoft Windows NT 6.1.7600.0", out myfile, 10000); - + // use fixed name for later installation myfile = "installlanguage.resources"; Util.DeployExtension(wr, myfile, installFolder); diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs index 07a8ebb260c..81ceef07f5a 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/AddFcnModeStep.cs @@ -32,7 +32,7 @@ public override void Execute() this.Errors.Add(Localization.GetString("FcnMode", this.LocalInstallResourceFile) + ": " + strError); Logger.TraceFormat("Adding FcnMode : {0}", strError); } - + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs index a23b5d31c12..2913a345172 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/BaseInstallationStep.cs @@ -12,22 +12,22 @@ namespace DotNetNuke.Services.Upgrade.Internals.Steps /// /// ----------------------------------------------------------------------------- public abstract class BaseInstallationStep : IInstallationStep - { + { protected string LocalInstallResourceFile = "~/Install/App_LocalResources/InstallWizard.aspx.resx"; - protected string LocalUpgradeResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; - private string _details = string.Empty; - + protected string LocalUpgradeResourceFile = "~/Install/App_LocalResources/UpgradeWizard.aspx.resx"; + private string _details = string.Empty; + protected BaseInstallationStep() { this.Percentage = 0; this.Errors = new List(); - } + } /// /// This event gets fired when any activity gets recorded /// - public event ActivityEventHandler Activity; - + public event ActivityEventHandler Activity; + /// /// Gets or sets any details of the task while it's executing. /// @@ -37,15 +37,15 @@ public string Details { return this._details; } - + set { this._details = value; DnnInstallLogger.InstallLogInfo(this._details); - if (this.Activity != null) - { - this.Activity(this._details); - } + if (this.Activity != null) + { + this.Activity(this._details); + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs index 6959aa1ce05..077147d3ca5 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/FilePermissionCheckStep.cs @@ -21,8 +21,8 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// ----------------------------------------------------------------------------- public class FilePermissionCheckStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FilePermissionCheckStep)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(FilePermissionCheckStep)); + /// /// Main method to execute the step. /// @@ -43,15 +43,15 @@ public override void Execute() + Localization.GetString("FolderDeleteCheck", this.LocalInstallResourceFile); Logger.TraceFormat("FilePermissionCheck - {0}", this.Details); - if (!verifiers.All(v => v.VerifyAll())) - { - this.Errors.Add(string.Format(Localization.GetString("StepFailed", this.LocalInstallResourceFile), this.Details)); - } - + if (!verifiers.All(v => v.VerifyAll())) + { + this.Errors.Add(string.Format(Localization.GetString("StepFailed", this.LocalInstallResourceFile), this.Details)); + } + this.Percentage = 100; this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; Logger.TraceFormat("FilePermissionCheck Status - {0}", this.Status); - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs index ba644bbd198..838516738bd 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/IInstallationStep.cs @@ -16,12 +16,12 @@ namespace DotNetNuke.Services.Upgrade.Internals.Steps /// /// ----------------------------------------------------------------------------- public interface IInstallationStep - { + { /// /// This event gets fired when any activity gets recorded /// - event ActivityEventHandler Activity; - + event ActivityEventHandler Activity; + /// /// Gets any details of the task while it's executing. /// @@ -40,11 +40,11 @@ public interface IInstallationStep /// /// Gets list of Errors. /// - IList Errors { get; } - + IList Errors { get; } + /// /// Main method to execute the step. /// - void Execute(); + void Execute(); } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs index e2518f0bb4e..86b80438ec6 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InitializeHostSettingsStep.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// /// ----------------------------------------------------------------------------- public class InitializeHostSettingsStep : BaseInstallationStep - { + { /// /// Main method to execute the step. /// @@ -59,7 +59,7 @@ public override void Execute() { settingValue = domainName; } - + break; case "HostEmail": if (string.IsNullOrEmpty(settingValue)) @@ -69,7 +69,7 @@ public override void Execute() break; } - + HostController.Instance.Update(settingName, settingValue, setting.IsSecure); } @@ -77,6 +77,6 @@ public override void Execute() FolderManager.Instance.Synchronize(Null.NullInteger, string.Empty, true, true); this.Status = StepStatus.Done; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs index 995a35e940f..da7c52b2d6d 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallDatabaseStep.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// /// ----------------------------------------------------------------------------- public class InstallDatabaseStep : BaseInstallationStep - { + { /// /// Main method to execute the step. /// @@ -56,7 +56,7 @@ public override void Execute() this.Status = StepStatus.Retry; return; } - + this.Percentage += percentForMiniStep; } @@ -64,7 +64,7 @@ public override void Execute() Globals.UpdateDataBaseVersion(new Version(installConfig.Version)); this.Details = Localization.GetString("InstallingMembershipDatabaseScriptStep", this.LocalInstallResourceFile); - + // Optionally Install the memberRoleProvider var exceptions = Upgrade.InstallMemberRoleProvider(providerPath, false); if (!string.IsNullOrEmpty(exceptions)) @@ -74,7 +74,7 @@ public override void Execute() return; } } - + this.Percentage = percentForEachStep * counter++; // Step 2 - Process the Upgrade Script files @@ -107,7 +107,7 @@ public override void Execute() this.Percentage += percentForMiniStep; } } - + this.Percentage = percentForEachStep * counter++; // Step 3 - Perform version specific application upgrades @@ -122,12 +122,12 @@ public override void Execute() this.Status = StepStatus.Retry; return; } - + this.Percentage += percentForMiniStep; } - + this.Percentage = percentForEachStep * counter++; - + // Step 4 - Execute config file updates foreach (Version ver in versions) { @@ -140,10 +140,10 @@ public override void Execute() this.Status = StepStatus.Retry; return; } - + this.Percentage += percentForMiniStep; } - + this.Percentage = percentForEachStep * counter++; // Step 5 - Delete files which are no longer used @@ -158,10 +158,10 @@ public override void Execute() this.Status = StepStatus.Retry; return; } - + this.Percentage += percentForMiniStep; } - + this.Percentage = percentForEachStep * counter++; // Step 6 - Perform general application upgrades @@ -175,6 +175,6 @@ public override void Execute() this.Percentage = percentForEachStep * counter++; this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs index b717c209c6e..9e37f2d14dc 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallExtensionsStep.cs @@ -19,8 +19,8 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// ----------------------------------------------------------------------------- public class InstallExtensionsStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallExtensionsStep)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(InstallExtensionsStep)); + /// /// Main method to execute the step. /// @@ -52,11 +52,11 @@ public override void Execute() this.Errors.Add(message); break; } - + this.Percentage = percentForEachStep * counter++; } - + this.Status = this.Errors.Count > 0 ? StepStatus.Retry : StepStatus.Done; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs index 5a6c92759f7..73ca1847a36 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSiteStep.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// /// ----------------------------------------------------------------------------- public class InstallSiteStep : BaseInstallationStep - { + { /// /// Main method to execute the step. /// @@ -31,10 +31,10 @@ public override void Execute() { this.Percentage = 0; this.Status = StepStatus.Running; - + // Set Status to None Globals.SetStatus(Globals.UpgradeStatus.None); - + var installConfig = InstallController.Instance.GetInstallConfig(); var percentForEachStep = 100 / installConfig.Portals.Count; var counter = 0; @@ -51,8 +51,8 @@ public override void Execute() Globals.ResetAppStartElapseTime(); this.Status = StepStatus.Done; - } - + } + private void CreateSite(PortalConfig portal, InstallConfig installConfig) { var domain = string.Empty; @@ -65,12 +65,12 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) // Get the Portal Alias var portalAlias = domain; - if (portal.PortAliases.Count > 0) - { - portalAlias = portal.PortAliases[0]; - } - - // Verify that portal alias is not present + if (portal.PortAliases.Count > 0) + { + portalAlias = portal.PortAliases[0]; + } + + // Verify that portal alias is not present if (PortalAliasController.Instance.GetPortalAlias(portalAlias.ToLowerInvariant()) != null) { string description = Localization.GetString("SkipCreatingSite", this.LocalInstallResourceFile); @@ -83,7 +83,7 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) if (string.IsNullOrEmpty(email)) { email = "admin@" + domain.Replace("www.", string.Empty); - + // Remove any domain subfolder information ( if it exists ) if (email.IndexOf("/") != -1) { @@ -114,27 +114,27 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) var template = Upgrade.FindBestTemplate(portal.TemplateFileName, culture); UserInfo userInfo; - if (!string.IsNullOrEmpty(portal.AdminUserName)) - { - userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); - } - else - { - userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); - } - + if (!string.IsNullOrEmpty(portal.AdminUserName)) + { + userInfo = Upgrade.CreateUserInfo(portal.AdminFirstName, portal.AdminLastName, portal.AdminUserName, portal.AdminPassword, email); + } + else + { + userInfo = Upgrade.CreateUserInfo(installConfig.SuperUser.FirstName, installConfig.SuperUser.LastName, installConfig.SuperUser.UserName, installConfig.SuperUser.Password, installConfig.SuperUser.Email); + } + var childPath = string.Empty; - if (portal.IsChild) - { - childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); - } - - // Create Folder Mappings config + if (portal.IsChild) + { + childPath = portalAlias.Substring(portalAlias.LastIndexOf("/") + 1); + } + + // Create Folder Mappings config if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } - + // add item to identity install from install wizard. if (HttpContext.Current != null) { @@ -142,7 +142,7 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) } // Create Portal - var portalId = PortalController.Instance.CreatePortal( + var portalId = PortalController.Instance.CreatePortal( portal.PortalName, userInfo, portal.Description, @@ -174,15 +174,15 @@ private void CreateSite(PortalConfig portal, InstallConfig installConfig) UserController.UserLogin(portalId, userInfo.Username, installConfig.SuperUser.Password, string.Empty, string.Empty, string.Empty, ref loginStatus, false); InstallController.Instance.RemoveFromInstallConfig("//dotnetnuke/superuser/password"); - } - - // private void CreateFolderMappingConfig(string folderMappinsSettings) - // { - // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); - // if (!File.Exists(folderMappingsConfigPath)) - // { - // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); - // } - // } + } + + // private void CreateFolderMappingConfig(string folderMappinsSettings) + // { + // string folderMappingsConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DotNetNuke.folderMappings.config"); + // if (!File.Exists(folderMappingsConfigPath)) + // { + // File.AppendAllText(folderMappingsConfigPath, "" + folderMappinsSettings + ""); + // } + // } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs index d87486ba9f3..69a96d6fb0c 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/InstallSuperUserStep.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// /// ----------------------------------------------------------------------------- public class InstallSuperUserStep : BaseInstallationStep - { + { /// /// Main method to execute the step. /// @@ -45,7 +45,7 @@ public override void Execute() { adminSuperUser.IsSuperUser = true; adminSuperUser.Membership.UpdatePassword = false; - + // refresh the profile to get definitions for super user. adminSuperUser.Profile = null; adminSuperUser.Profile.PreferredLocale = installConfig.SuperUser.Locale; @@ -55,16 +55,16 @@ 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; @@ -75,15 +75,15 @@ public override void Execute() superUser.Membership.UpdatePassword = false; // Create SuperUser if not present - if (UserController.GetUserByName(superUser.PortalID, superUser.Username) == null) - { - UserController.CreateUser(ref superUser); - } + if (UserController.GetUserByName(superUser.PortalID, superUser.Username) == null) + { + UserController.CreateUser(ref superUser); + } } this.Details = Localization.GetString("CreatingSuperUser", this.LocalInstallResourceFile) + installConfig.SuperUser.UserName; this.Status = StepStatus.Done; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs index 3690dab6314..d2bd6108abc 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/SynchConnectionStringStep.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// /// ----------------------------------------------------------------------------- public class SynchConnectionStringStep : BaseInstallationStep - { + { /// /// Main method to execute the step. /// @@ -52,36 +52,36 @@ public override void Execute() var builder = DataProvider.Instance().GetConnectionStringBuilder(); - if (!string.IsNullOrEmpty(connectionConfig.Server)) - { - builder["Data Source"] = connectionConfig.Server; - } - - if (!string.IsNullOrEmpty(connectionConfig.Database)) - { - builder["Initial Catalog"] = connectionConfig.Database; - } + if (!string.IsNullOrEmpty(connectionConfig.Server)) + { + builder["Data Source"] = connectionConfig.Server; + } + + if (!string.IsNullOrEmpty(connectionConfig.Database)) + { + builder["Initial Catalog"] = connectionConfig.Database; + } else if (!string.IsNullOrEmpty(connectionConfig.File)) { builder["attachdbfilename"] = "|DataDirectory|" + connectionConfig.File; builder["user instance"] = "true"; } - if (connectionConfig.Integrated) - { - builder["integrated security"] = "true"; - } - - if (!string.IsNullOrEmpty(connectionConfig.User)) - { - builder["uid"] = connectionConfig.User; - } - - if (!string.IsNullOrEmpty(connectionConfig.Password)) - { - builder["pwd"] = connectionConfig.Password; - } - + if (connectionConfig.Integrated) + { + builder["integrated security"] = "true"; + } + + if (!string.IsNullOrEmpty(connectionConfig.User)) + { + builder["uid"] = connectionConfig.User; + } + + if (!string.IsNullOrEmpty(connectionConfig.Password)) + { + builder["pwd"] = connectionConfig.Password; + } + string dbowner; if (connectionConfig.RunAsDbowner) { @@ -100,7 +100,7 @@ public override void Execute() var appConnectionString = Config.GetConnectionString(); var modified = false; - + // save to web.config if different if (appConnectionString.ToLower() != connectionString.ToLower()) { @@ -124,8 +124,8 @@ public override void Execute() } this.Status = modified ? StepStatus.AppRestart : StepStatus.Done; - } - + } + private string GetUpgradeConnectionStringUserID() { string dbUser = string.Empty; @@ -150,8 +150,8 @@ private string GetUpgradeConnectionStringUserID() } } } - + return dbUser; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs b/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs index df952e0c1ba..6b389fcccf5 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/Steps/UpdateLanguagePackStep.cs @@ -20,8 +20,8 @@ namespace DotNetNuke.Services.Upgrade.InternalController.Steps /// ----------------------------------------------------------------------------- public class UpdateLanguagePackStep : BaseInstallationStep { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UpdateLanguagePackStep)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UpdateLanguagePackStep)); + /// /// Main method to execute the step. /// @@ -56,8 +56,8 @@ public override void Execute() Logger.Error(ex); } } - + this.Status = StepStatus.Done; - } + } } } diff --git a/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs b/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs index 039bac46d3d..9f7bb8a2a69 100644 --- a/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs +++ b/DNN Platform/Library/Services/Upgrade/Internals/UpdateService.cs @@ -29,7 +29,7 @@ private static string ApplicationName return DotNetNukeContext.Current.Application.Name; } } - + public static StreamReader GetLanguageList() { string url = DotNetNukeContext.Current.Application.UpgradeUrl + "/languages.aspx"; diff --git a/DNN Platform/Library/Services/Upgrade/Upgrade.cs b/DNN Platform/Library/Services/Upgrade/Upgrade.cs index ded5cc3b4a4..50d788edb17 100644 --- a/DNN Platform/Library/Services/Upgrade/Upgrade.cs +++ b/DNN Platform/Library/Services/Upgrade/Upgrade.cs @@ -223,6030 +223,6030 @@ public static TabInfo AddAdminPage(PortalInfo portal, string tabName, string des /// ----------------------------------------------------------------------------- /// - /// ExecuteScript executes a SQl script file. + /// AddHostPage adds a Host Tab Page. /// - /// - /// - /// The script to Execute. - /// Need to output feedback message. + /// The Name to give this new Tab. + /// + /// The Icon for this new Tab. + /// + /// A flag indicating whether the tab is visible. /// /// ----------------------------------------------------------------------------- - internal static string ExecuteScript(string scriptFile, bool writeFeedback) + public static TabInfo AddHostPage(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) { - 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); - } + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddHostPage:" + tabName); + TabInfo hostPage = TabController.Instance.GetTabByName("Host", Null.NullInteger); - if (writeFeedback) + if (hostPage != null) { - string resourcesFile = Path.GetFileName(scriptFile); - if (!string.IsNullOrEmpty(resourcesFile)) - { - HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); - } + return AddPage(hostPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, new TabPermissionCollection(), true); } - return exceptions; + return null; } /// ----------------------------------------------------------------------------- /// - /// InstallMemberRoleProvider - Installs the MemberRole Provider Db objects. + /// AddModuleControl adds a new Module Control to the system. /// /// /// - /// The Path to the Provider Directory. - /// Whether need to output feedback message. - /// + /// The Module Definition Id. + /// The key for this control in the Definition. + /// The title of this control. + /// Te source of ths control. + /// The icon file. + /// The type of control. + /// The vieworder for this module. /// ----------------------------------------------------------------------------- - internal static string InstallMemberRoleProvider(string providerPath, bool writeFeedback) + public static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder) { - 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; + // Call Overload with HelpUrl = Null.NullString + AddModuleControl(moduleDefId, controlKey, controlTitle, controlSrc, iconFile, controlType, viewOrder, Null.NullString); } /// ----------------------------------------------------------------------------- /// - /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. + /// AddModuleDefinition adds a new Core Module Definition to the system. /// - /// The Name to give this new Tab. - /// Description. - /// The Icon for this new Tab. - /// The large 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. + /// + /// This overload asumes the module is an Admin module and not a Premium Module. + /// + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. + /// The Module Definition Id of the new Module. /// ----------------------------------------------------------------------------- - private static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile) + public static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPages:" + tabName); + // Call overload with Premium=False and Admin=True + return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, false, true); + } - // Call overload with InheritPermisions=True - AddAdminPages(tabName, description, tabIconFile, tabIconFileLarge, isVisible, moduleDefId, moduleTitle, moduleIconFile, true); + /// ----------------------------------------------------------------------------- + /// + /// AddModuleToPage adds a module to a Page. + /// + /// + /// + /// The Page to add the Module to. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. + /// Inherit the Pages View Permisions. + /// + /// ----------------------------------------------------------------------------- + public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + { + return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions, true, Globals.glbDefaultPane); } - private static void AddAdminRoleToPage(string tabPath) + public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions, bool displayTitle, string paneName) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminRoleToPage:" + tabPath); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); + ModuleInfo moduleInfo; + int moduleId = Null.NullInteger; - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + if (page != null) { - int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if (tabID != Null.NullInteger) + bool isDuplicate = false; + foreach (var kvp in ModuleController.Instance.GetTabModules(page.TabID)) { - TabInfo tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); + moduleInfo = kvp.Value; + if (moduleInfo.ModuleDefID == moduleDefId) + { + isDuplicate = true; + moduleId = moduleInfo.ModuleID; + } + } - if (tab.TabPermissions.Count == 0) + if (!isDuplicate) + { + moduleInfo = new ModuleInfo { - AddPagePermission(tab.TabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); - AddPagePermission(tab.TabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); - TabPermissionController.SaveTabPermissions(tab); + ModuleID = Null.NullInteger, + PortalID = page.PortalID, + TabID = page.TabID, + ModuleOrder = -1, + ModuleTitle = moduleTitle, + PaneName = paneName, + ModuleDefID = moduleDefId, + CacheTime = 0, + IconFile = moduleIconFile, + AllTabs = false, + Visibility = VisibilityState.None, + InheritViewPermissions = inheritPermissions, + DisplayTitle = displayTitle, + }; + + ModuleController.Instance.InitialModulePermission(moduleInfo, moduleInfo.TabID, inheritPermissions ? 0 : 1); + + moduleInfo.TabModuleSettings["hideadminborder"] = "True"; + + try + { + moduleId = ModuleController.Instance.AddModule(moduleInfo); + } + catch (Exception exc) + { + Logger.Error(exc); + DnnInstallLogger.InstallLogError(exc); } } } + + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); + return moduleId; } - private static void AddConsoleModuleSettings(int moduleID) + public static int AddModuleToPage(string tabPath, int portalId, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddConsoleModuleSettings:" + moduleID); + int moduleId = Null.NullInteger; - ModuleController.Instance.UpdateModuleSetting(moduleID, "DefaultSize", "IconFileLarge"); - ModuleController.Instance.UpdateModuleSetting(moduleID, "AllowSizeChange", "False"); - ModuleController.Instance.UpdateModuleSetting(moduleID, "DefaultView", "Hide"); - ModuleController.Instance.UpdateModuleSetting(moduleID, "AllowViewChange", "False"); - ModuleController.Instance.UpdateModuleSetting(moduleID, "ShowTooltip", "True"); + int tabID = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString); + if (tabID != Null.NullInteger) + { + TabInfo tab = TabController.Instance.GetTab(tabID, portalId, true); + if (tab != null) + { + moduleId = AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); + } + } + + return moduleId; } - private static void AddEventQueueApplicationStartFirstRequest() + public static void AddModuleToPages(string tabPath, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) { - // Add new EventQueue Event - var config = EventQueueConfiguration.GetConfig(); - if (config != null) + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - if (!config.PublishedEvents.ContainsKey("Application_Start_FirstRequest")) + int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); + if (tabID != Null.NullInteger) { - foreach (SubscriberInfo subscriber in config.EventQueueSubscribers.Values) + var tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); + if (tab != null) { - EventQueueConfiguration.RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); + AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); } - - EventQueueConfiguration.SaveConfig(config, string.Format("{0}EventQueue\\EventQueue.config", Globals.HostMapPath)); } } } /// ----------------------------------------------------------------------------- /// - /// AddModuleControl adds a new Module Control to the system. + /// AddPortal manages the Installation of a new DotNetNuke Portal. /// /// /// - /// The Module Definition Id. - /// The key for this control in the Definition. - /// The title of this control. - /// Te source of ths control. - /// The icon file. - /// The type of control. - /// The vieworder for this module. - /// The Help Url. + /// /// ----------------------------------------------------------------------------- - private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL) + public static int AddPortal(XmlNode node, bool status, int indent, UserInfo superUser = null) { - AddModuleControl(moduleDefId, controlKey, controlTitle, controlSrc, iconFile, controlType, viewOrder, helpURL, false); - } + int portalId = -1; + try + { + string hostMapPath = Globals.HostMapPath; + string childPath = string.Empty; + string domain = string.Empty; - private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL, bool supportsPartialRendering) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleControl:" + moduleDefId); + if (HttpContext.Current != null) + { + domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install", string.Empty); + } - // check if module control exists - var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); - if (moduleControl == null) - { - moduleControl = new ModuleControlInfo + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPortal:" + domain); + string portalName = XmlUtils.GetNodeValue(node.CreateNavigator(), "portalname"); + if (status) { - ModuleControlID = Null.NullInteger, - ModuleDefID = moduleDefId, - ControlKey = controlKey, - ControlTitle = controlTitle, - ControlSrc = controlSrc, - ControlType = controlType, - ViewOrder = viewOrder, - IconFile = iconFile, - HelpURL = helpURL, - SupportsPartialRendering = supportsPartialRendering, - }; + if (HttpContext.Current != null) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Site: " + portalName + "
    "); + } + } - ModuleControlController.AddModuleControl(moduleControl); - } - } + XmlNode adminNode = node.SelectSingleNode("administrator"); + if (adminNode != null) + { + string firstName = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "firstname"); + string lastName = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "lastname"); + string username = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "username"); + string password = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "password"); + string email = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "email"); + string description = XmlUtils.GetNodeValue(node.CreateNavigator(), "description"); + string keyWords = XmlUtils.GetNodeValue(node.CreateNavigator(), "keywords"); + string templateFileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "templatefile"); + string serverPath = Globals.ApplicationMapPath + "\\"; + bool isChild = bool.Parse(XmlUtils.GetNodeValue(node.CreateNavigator(), "ischild")); + string homeDirectory = XmlUtils.GetNodeValue(node.CreateNavigator(), "homedirectory"); - /// ----------------------------------------------------------------------------- - /// - /// AddModuleDefinition adds a new Core Module Definition to the system. - /// - /// - /// This overload allows the caller to determine whether the module has a controller - /// class. - /// - /// The Friendly Name of the Module to Add. - /// Description of the Module. - /// The Module Definition Name. - /// A flag representing whether the module is a Premium module. - /// A flag representing whether the module is an Admin module. - /// The Module Definition Id of the new Module. - /// ----------------------------------------------------------------------------- - private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, bool premium, bool admin) - { - return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, string.Empty, false, premium, admin); - } + // Get the Portal Alias + XmlNodeList portalAliases = node.SelectNodes("portalaliases/portalalias"); + string strPortalAlias = domain; + if (portalAliases != null) + { + if (portalAliases.Count > 0) + { + if (!string.IsNullOrEmpty(portalAliases[0].InnerText)) + { + strPortalAlias = portalAliases[0].InnerText; + } + } + } - /// ----------------------------------------------------------------------------- - /// - /// AddModuleDefinition adds a new Core Module Definition to the system. - /// - /// - /// This overload allows the caller to determine whether the module has a controller - /// class. - /// - /// The Friendly Name of the Module to Add. - /// Description of the Module. - /// The Module Definition Name. - /// Business Control Class. - /// Whether the module is enable for portals. - /// A flag representing whether the module is a Premium module. - /// A flag representing whether the module is an Admin module. - /// The Module Definition Id of the new Module. - /// ----------------------------------------------------------------------------- - private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, string businessControllerClass, bool isPortable, bool premium, bool admin) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleDefinition:" + desktopModuleName); + // Create default email + if (string.IsNullOrEmpty(email)) + { + email = "admin@" + domain.Replace("www.", string.Empty); - // check if desktop module exists - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - if (desktopModule == null) - { - var package = new PackageInfo - { - Description = description, - FriendlyName = desktopModuleName, - Name = string.Concat("DotNetNuke.", desktopModuleName), - PackageType = "Module", - Owner = "DNN", - Organization = ".NET Foundation", - Url = "https://dnncommunity.org", - Email = "info@dnncommunity.org", - }; - if (desktopModuleName == "Extensions" || desktopModuleName == "Skin Designer") - { - package.IsSystemPackage = true; - } + // Remove any domain subfolder information ( if it exists ) + if (email.IndexOf("/") != -1) + { + email = email.Substring(0, email.IndexOf("/")); + } + } - package.Version = new Version(1, 0, 0); + if (isChild) + { + childPath = PortalController.GetPortalFolder(strPortalAlias); + } - PackageController.Instance.SaveExtensionPackage(package); + var template = FindBestTemplate(templateFileName); + var userInfo = superUser ?? CreateUserInfo(firstName, lastName, username, password, email); - string moduleName = desktopModuleName.Replace(" ", string.Empty); - desktopModule = new DesktopModuleInfo - { - DesktopModuleID = Null.NullInteger, - PackageID = package.PackageID, - FriendlyName = desktopModuleName, - FolderName = "Admin/" + moduleName, - ModuleName = moduleName, - Description = description, - Version = "01.00.00", - BusinessControllerClass = businessControllerClass, - IsPortable = isPortable, - SupportedFeatures = 0, - }; - if (isPortable) - { - desktopModule.SupportedFeatures = 1; - } + // Create Portal + portalId = PortalController.Instance.CreatePortal( + portalName, + userInfo, + description, + keyWords, + template, + homeDirectory, + strPortalAlias, + serverPath, + serverPath + childPath, + isChild); - desktopModule.IsPremium = premium; - desktopModule.IsAdmin = admin; + if (portalId > -1) + { + // Add Extra Aliases + if (portalAliases != null) + { + foreach (XmlNode portalAlias in portalAliases) + { + if (!string.IsNullOrEmpty(portalAlias.InnerText)) + { + if (status) + { + if (HttpContext.Current != null) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Site Alias: " + portalAlias.InnerText + "
    "); + } + } - desktopModule.DesktopModuleID = DesktopModuleController.SaveDesktopModule(desktopModule, false, false); + PortalController.Instance.AddPortalAlias(portalId, portalAlias.InnerText); + } + } + } - if (!premium) - { - DesktopModuleController.AddDesktopModuleToPortals(desktopModule.DesktopModuleID); + // 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; } } - - // check if module definition exists - var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(moduleDefinitionName, desktopModule.DesktopModuleID); - if (moduleDefinition == null) + catch (Exception ex) { - moduleDefinition = new ModuleDefinitionInfo { ModuleDefID = Null.NullInteger, DesktopModuleID = desktopModule.DesktopModuleID, FriendlyName = moduleDefinitionName }; + Logger.Error(ex); - moduleDefinition.ModuleDefID = ModuleDefinitionController.SaveModuleDefinition(moduleDefinition, false, false); + if (HttpContext.Current != null) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error! " + ex.Message + ex.StackTrace + "
    "); + DnnInstallLogger.InstallLogError(ex); + } + + // failure + portalId = -1; } - return moduleDefinition.ModuleDefID; + return portalId; } /// ----------------------------------------------------------------------------- /// - /// AddModuleToPage adds a module to a Page. + /// Obsolete, AddPortal manages the Installation of a new DotNetNuke Portal. /// /// - /// This overload assumes ModulePermissions will be inherited. /// - /// The Page to add the Module to. - /// The Module Deinition Id for the module to be aded to this tab. - /// The Module's title. - /// The Module's icon. + /// /// ----------------------------------------------------------------------------- - private static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile) + [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) { - // Call overload with InheritPermisions=True - return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, true); + return AddPortal(node, status, indent, null); } - /// ----------------------------------------------------------------------------- - /// - /// AddPage adds a Tab Page. - /// - /// - /// Adds a Tab to a parentTab. - /// - /// The Parent Tab. - /// The Name to give this new Tab. - /// Description. - /// The Icon for this new Tab. - /// The Large Icon for this new Tab. - /// A flag indicating whether the tab is visible. - /// Page Permissions Collection for this page. - /// Is an admin page. - /// ----------------------------------------------------------------------------- - private static TabInfo AddPage(TabInfo parentTab, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) + public static string BuildUserTable(IDataReader dr, string header, string message) { - int parentId = Null.NullInteger; - int portalId = Null.NullInteger; + string warnings = Null.NullString; + var stringBuilder = new StringBuilder(); + bool hasRows = false; - if (parentTab != null) + stringBuilder.Append("

    " + header + "

    "); + stringBuilder.Append("

    " + message + "

    "); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + while (dr.Read()) { - parentId = parentTab.TabID; - portalId = parentTab.PortalID; + hasRows = true; + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); + stringBuilder.Append(""); } - return AddPage(portalId, parentId, tabName, description, tabIconFile, tabIconFileLarge, isVisible, permissions, isAdmin); + stringBuilder.Append("
    IDUserNameFirst NameLast NameEmail
    " + dr.GetInt32(0) + "" + dr.GetString(1) + "" + dr.GetString(2) + "" + dr.GetString(3) + "" + dr.GetString(4) + "
    "); + + if (hasRows) + { + warnings = stringBuilder.ToString(); + } + + return warnings; } /// ----------------------------------------------------------------------------- /// - /// AddPage adds a Tab Page. + /// CheckUpgrade checks whether there are any possible upgrade issues. /// - /// The Id of the Portal. - /// The Id of the Parent Tab. - /// The Name to give this new Tab. - /// Description. - /// The Icon for this new Tab. - /// The large Icon for this new Tab. - /// A flag indicating whether the tab is visible. - /// Page Permissions Collection for this page. - /// Is and admin page. + /// /// ----------------------------------------------------------------------------- - private static TabInfo AddPage(int portalId, int parentId, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) + public static string CheckUpgrade() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPage:" + tabName); - - TabInfo tab = TabController.Instance.GetTabByName(tabName, portalId, parentId); + DataProvider dataProvider = DataProvider.Instance(); + IDataReader dr; + string warnings = Null.NullString; - if (tab == null || tab.ParentId != parentId) + try { - tab = new TabInfo + using (dr = dataProvider.ExecuteReader("CheckUpgrade")) { - TabID = Null.NullInteger, - PortalID = portalId, - TabName = tabName, - Title = string.Empty, - Description = description, - KeyWords = string.Empty, - IsVisible = isVisible, - DisableLink = false, - ParentId = parentId, - IconFile = tabIconFile, - IconFileLarge = tabIconFileLarge, - IsDeleted = false, - }; - tab.TabID = TabController.Instance.AddTab(tab, !isAdmin); + warnings = BuildUserTable(dr, "Duplicate SuperUsers", "We have detected that the following SuperUsers have duplicate entries as Portal Users. Although, no longer supported, these users may have been created in early Betas of DNN v3.0. You need to be aware that after the upgrade, these users will only be able to log in using the Super User Account's password."); - if (permissions != null) - { - foreach (TabPermissionInfo tabPermission in permissions) + if (dr.NextResult()) { - tab.TabPermissions.Add(tabPermission, true); + warnings += BuildUserTable(dr, "Duplicate Portal Users", "We have detected that the following Users have duplicate entries (they exist in more than one portal). You need to be aware that after the upgrade, the password for some of these users may have been automatically changed (as the system now only uses one password per user, rather than one password per user per portal). It is important to remember that your Users can always retrieve their password using the Password Reminder feature, which will be sent to the Email addess shown in the table."); } + } + } + catch (SqlException ex) + { + Logger.Error(ex); + warnings += ex.Message; + } + catch (Exception ex) + { + Logger.Error(ex); + warnings += ex.Message; + } - TabPermissionController.SaveTabPermissions(tab); + try + { + using (dr = dataProvider.ExecuteReader("GetUserCount")) + { + dr.Read(); + int userCount = dr.GetInt32(0); + + // ReSharper disable PossibleLossOfFraction + double time = userCount / 10834; + + // ReSharper restore PossibleLossOfFraction + if (userCount > 1000) + { + warnings += "

    More than 1000 Users

    This DotNetNuke Database has " + userCount + + " users. As the users and their profiles are transferred to a new format, it is estimated that the script will take ~" + time.ToString("F2") + + " minutes to execute.

    "; + } } } + catch (Exception ex) + { + Logger.Error(ex); + warnings += Environment.NewLine + Environment.NewLine + ex.Message; + } - return tab; + return warnings; } /// ----------------------------------------------------------------------------- /// - /// AddPagePermission adds a TabPermission to a TabPermission Collection. + /// DeleteInstallerFiles - clean up install config and installwizard files + /// If installwizard is ran again this will be recreated via the dotnetnuke.install.config.resources file. /// - /// Page Permissions Collection for this page. - /// The Permission key. - /// The role given the permission. + /// + /// uses FileSystemUtils.DeleteFile as it checks for readonly attribute status + /// and changes it if required, as well as verifying file exists. + /// /// ----------------------------------------------------------------------------- - private static void AddPagePermission(TabPermissionCollection permissions, string key, int roleId) + public static void DeleteInstallerFiles() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPagePermission:" + key); - var permissionController = new PermissionController(); - var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", key)[0]; - - var tabPermission = new TabPermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; + var files = new List + { + "DotNetNuke.install.config", + "DotNetNuke.install.config.resources", + "InstallWizard.aspx", + "InstallWizard.aspx.cs", + "InstallWizard.aspx.designer.cs", + "UpgradeWizard.aspx", + "UpgradeWizard.aspx.cs", + "UpgradeWizard.aspx.designer.cs", + "Install.aspx", + "Install.aspx.cs", + "Install.aspx.designer.cs", + }; - permissions.Add(tabPermission); + foreach (var file in files) + { + try + { + FileSystemUtils.DeleteFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", file)); + } + catch (Exception ex) + { + Logger.Error("File deletion failed for [Install\\" + file + "]. PLEASE REMOVE THIS MANUALLY." + ex); + } + } } /// ----------------------------------------------------------------------------- /// - /// AddSearchResults adds a top level Hidden Search Results Page. + /// DeleteFiles - clean up deprecated files and folders. /// - /// The Module Deinition Id for the Search Results Module. + /// + /// + /// Path to provider. + /// The Version being Upgraded. + /// Display status in UI?. + /// /// ----------------------------------------------------------------------------- - private static void AddSearchResults(int moduleDefId) + public static string DeleteFiles(string providerPath, Version version, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSearchResults:" + moduleDefId); - var portals = PortalController.Instance.GetPortals(); - int intPortal; + var stringVersion = GetStringVersionWithRevision(version); - // Add Page to Admin Menu of all configured Portals - for (intPortal = 0; intPortal <= portals.Count - 1; intPortal++) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "DeleteFiles:" + stringVersion); + string exceptions = string.Empty; + if (writeFeedback) { - var tabPermissions = new TabPermissionCollection(); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Cleaning Up Files: " + stringVersion); + } - var portal = (PortalInfo)portals[intPortal]; + string listFile = Globals.InstallMapPath + "Cleanup\\" + stringVersion + ".txt"; + try + { + if (File.Exists(listFile)) + { + exceptions = FileSystemUtils.DeleteFiles(File.ReadAllLines(listFile)); + } + } + catch (Exception ex) + { + Logger.Error("Error cleanup file " + listFile, ex); - AddPagePermission(tabPermissions, "View", Convert.ToInt32(Globals.glbRoleAllUsers)); - AddPagePermission(tabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); - AddPagePermission(tabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); + exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; - // Create New Page (or get existing one) - var tab = AddPage(portal.PortalID, Null.NullInteger, "Search Results", string.Empty, string.Empty, string.Empty, false, tabPermissions, false); + // log the results + DnnInstallLogger.InstallLogError(exceptions); + try + { + using (StreamWriter streamWriter = File.CreateText(providerPath + stringVersion + "_Config.log")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); + } + } + catch (Exception exc) + { + Logger.Error(exc); + } + } - // Add Module To Page - AddModuleToPage(tab, moduleDefId, "Search Results", string.Empty); + if (writeFeedback) + { + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); } + + return exceptions; } /// ----------------------------------------------------------------------------- /// - /// AddSkinControl adds a new Module Control to the system. + /// ExecuteScripts manages the Execution of Scripts from the Install/Scripts folder. + /// It is also triggered by InstallDNN and UpgradeDNN. /// /// /// - /// The key for this control in the Definition. - /// Package Name. - /// Te source of ths control. + /// The path to the Data Provider. /// ----------------------------------------------------------------------------- - private static void AddSkinControl(string controlKey, string packageName, string controlSrc) + public static void ExecuteScripts(string strProviderPath) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSkinControl:" + controlKey); - - // check if skin control exists - SkinControlInfo skinControl = SkinControlController.GetSkinControlByKey(controlKey); - if (skinControl == null) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScripts:" + strProviderPath); + string scriptPath = Globals.ApplicationMapPath + "\\Install\\Scripts\\"; + if (Directory.Exists(scriptPath)) { - var package = new PackageInfo { Name = packageName, FriendlyName = string.Concat(controlKey, "SkinObject"), PackageType = "SkinObject", Version = new Version(1, 0, 0) }; - LegacyUtil.ParsePackageName(package); - - PackageController.Instance.SaveExtensionPackage(package); - - skinControl = new SkinControlInfo { PackageID = package.PackageID, ControlKey = controlKey, ControlSrc = controlSrc, SupportsPartialRendering = false }; + string[] files = Directory.GetFiles(scriptPath); + foreach (string file in files) + { + // Execute if script is a provider script + if (file.IndexOf("." + DefaultProvider) != -1) + { + ExecuteScript(file, true); - SkinControlController.SaveSkinControl(skinControl); + // delete the file + try + { + File.SetAttributes(file, FileAttributes.Normal); + File.Delete(file); + } + catch (Exception exc) + { + Logger.Error(exc); + } + } + } } } - private static void AddDefaultModuleIcons() + /// ----------------------------------------------------------------------------- + /// + /// ExecuteScript executes a special script. + /// + /// + /// + /// The script file to execute. + /// ----------------------------------------------------------------------------- + public static void ExecuteScript(string file) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddDefaultModuleIcons"); - var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Google Analytics"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/Analytics"; - pkg.IconFile = "~/DesktopModules/Admin/Analytics/analytics.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } - - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Configuration Manager"); - if (pkg != null) + // Execute if script is a provider script + if (file.IndexOf("." + DefaultProvider) != -1) { - pkg.FolderName = "DesktopModules/Admin/XmlMerge"; - pkg.IconFile = "~/DesktopModules/Admin/XmlMerge/xmlMerge.png"; - PackageController.Instance.SaveExtensionPackage(pkg); + ExecuteScript(file, true); } + } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Console"); - if (pkg != null) + /// ----------------------------------------------------------------------------- + /// + /// GetInstallTemplate retrieves the Installation Template as specifeid in web.config. + /// + /// + /// + /// The Xml Document to load. + /// A string which contains the error message - if appropriate. + /// ----------------------------------------------------------------------------- + public static string GetInstallTemplate(XmlDocument xmlDoc) + { + string errorMessage = Null.NullString; + string installTemplate = Config.GetSetting("InstallTemplate"); + try { - pkg.FolderName = "DesktopModules/Admin/Console"; - pkg.IconFile = "~/DesktopModules/Admin/Console/console.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); + xmlDoc.Load(Globals.ApplicationMapPath + "\\Install\\" + installTemplate); } - - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ContentList"); - if (pkg != null) + catch { - pkg.FolderName = "DesktopModules/Admin/ContentList"; - pkg.IconFile = "~/DesktopModules/Admin/ContentList/contentList.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); + // error + errorMessage = "Failed to load Install template.

    "; } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Dashboard"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/Dashboard"; - pkg.IconFile = "~/DesktopModules/Admin/Dashboard/dashboard.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } + return errorMessage; + } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Languages"); - if (pkg != null) + /// + /// SetInstalltemplate saves the XmlDocument back to Installation Template specified in web.config. + /// + /// The Xml Document to save. + /// A string which contains the error massage - if appropriate. + public static string SetInstallTemplate(XmlDocument xmlDoc) + { + string errorMessage = Null.NullString; + string installTemplate = Config.GetSetting("InstallTemplate"); + string filePath = Globals.ApplicationMapPath + "\\Install\\" + installTemplate; + try { - pkg.FolderName = "DesktopModules/Admin/Languages"; - pkg.IconFile = "~/DesktopModules/Admin/Languages/languages.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } + // ensure the file is not read-only + var attributes = File.GetAttributes(filePath); + if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + // file is readonly, then remove it + attributes = attributes & ~FileAttributes.ReadOnly; + File.SetAttributes(filePath, attributes); + } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Marketplace"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/Marketplace"; - pkg.IconFile = "~/DesktopModules/Admin/Marketplace/marketplace.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); + xmlDoc.Save(filePath); } - - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Sitemap"); - if (pkg != null) + catch { - pkg.FolderName = "DesktopModules/Admin/Sitemap"; - pkg.IconFile = "~/DesktopModules/Admin/Sitemap/sitemap.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); + // error + errorMessage = "Failed to save Install template.

    "; } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Skin Designer"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/SkinDesigner"; - pkg.IconFile = "~/DesktopModules/Admin/SkinDesigner/skinDesigner.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } + return errorMessage; + } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Skins"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/Skins"; - pkg.IconFile = "~/DesktopModules/Admin/Skins/skins.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } + /// ----------------------------------------------------------------------------- + /// + /// GetInstallVersion retrieves the Base Instal Version as specifeid in the install + /// template. + /// + /// + /// + /// The Install Template. + /// + /// ----------------------------------------------------------------------------- + public static Version GetInstallVersion(XmlDocument xmlDoc) + { + string version = Null.NullString; - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ViewProfile"); - if (pkg != null) + // get base version + XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke"); + if (node != null) { - pkg.FolderName = "DesktopModules/Admin/ViewProfile"; - pkg.IconFile = "~/DesktopModules/Admin/ViewProfile/viewProfile.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); + version = XmlUtils.GetNodeValue(node.CreateNavigator(), "version"); } - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ProfessionalPreview"); - if (pkg != null) - { - pkg.FolderName = "DesktopModules/Admin/ProfessionalPreview"; - pkg.IconFile = "~/DesktopModules/Admin/ProfessionalPreview/professionalPreview.gif"; - PackageController.Instance.SaveExtensionPackage(pkg); - } + return new Version(version); } - private static void AddModuleCategories() + /// ----------------------------------------------------------------------------- + /// + /// GetLogFile gets the filename for the version's log file. + /// + /// + /// + /// The path to the Data Provider. + /// The Version. + /// + /// ----------------------------------------------------------------------------- + public static string GetLogFile(string providerPath, Version version) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleCategories"); - DesktopModuleController.AddModuleCategory("< None >"); - DesktopModuleController.AddModuleCategory("Admin"); - DesktopModuleController.AddModuleCategory("Common"); - - foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) - { - bool update = false; - switch (desktopModuleInfo.Value.ModuleName) - { - case "Portals": - case "SQL": - case "HostSettings": - case "Scheduler": - case "SearchAdmin": - case "Lists": - case "Extensions": - case "WhatsNew": - case "Dashboard": - case "Marketplace": - case "ConfigurationManager": - case "Security": - case "Tabs": - case "Vendors": - case "Banners": - case "FileManager": - case "SiteLog": - case "Newsletters": - case "RecycleBin": - case "LogViewer": - case "SiteWizard": - case "Languages": - case "Skins": - case "SkinDesigner": - case "GoogleAnalytics": - case "Sitemap": - case "DotNetNuke.Taxonomy": - desktopModuleInfo.Value.Category = "Admin"; - update = true; - break; - default: - break; - } - - if (update) - { - if (desktopModuleInfo.Value.PackageID == Null.NullInteger) - { - LegacyUtil.ProcessLegacyModule(desktopModuleInfo.Value); - } - - DesktopModuleController.SaveDesktopModule(desktopModuleInfo.Value, false, false); - } - } + return providerPath + GetStringVersion(version) + ".log.resources"; } /// ----------------------------------------------------------------------------- /// - /// CoreModuleExists determines whether a Core Module exists on the system. + /// GetScriptFile gets the filename for the version. /// /// /// - /// The Friendly Name of the Module. - /// True if the Module exists, otherwise False. + /// The path to the Data Provider. + /// The Version. + /// /// ----------------------------------------------------------------------------- - private static bool CoreModuleExists(string desktopModuleName) + public static string GetScriptFile(string providerPath, Version version) { - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - - return desktopModule != null; - } - - private static void EnableModalPopUps() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "EnableModalPopUps"); - foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) - { - switch (desktopModuleInfo.Value.ModuleName) - { - case "Portals": - case "SQL": - case "HostSettings": - case "Scheduler": - case "SearchAdmin": - case "Lists": - case "Extensions": - case "WhatsNew": - case "Dashboard": - case "Marketplace": - case "ConfigurationManager": - case "Security": - case "Tabs": - case "Vendors": - case "Banners": - case "FileManager": - case "SiteLog": - case "Newsletters": - case "RecycleBin": - case "LogViewer": - case "SiteWizard": - case "Languages": - case "Skins": - case "SkinDesigner": - case "GoogleAnalytics": - case "Sitemap": - case "DotNetNuke.Taxonomy": - foreach (ModuleDefinitionInfo definition in desktopModuleInfo.Value.ModuleDefinitions.Values) - { - foreach (ModuleControlInfo control in definition.ModuleControls.Values) - { - if (!string.IsNullOrEmpty(control.ControlKey)) - { - control.SupportsPopUps = true; - ModuleControlController.SaveModuleControl(control, false); - } - } - } - - break; - default: - break; - } - } - - foreach (ModuleControlInfo control in ModuleControlController.GetModuleControlsByModuleDefinitionID(Null.NullInteger).Values) - { - control.SupportsPopUps = true; - ModuleControlController.SaveModuleControl(control, false); - } + return providerPath + GetStringVersion(version) + "." + DefaultProvider; } /// ----------------------------------------------------------------------------- /// - /// GetModuleDefinition gets the Module Definition Id of a module. + /// GetStringVersion gets the Version String (xx.xx.xx) from the Version. /// - /// The Friendly Name of the Module to Add. - /// The Module Definition Name. - /// The Module Definition Id of the Module (-1 if no module definition). + /// + /// + /// The Version. + /// /// ----------------------------------------------------------------------------- - private static int GetModuleDefinition(string desktopModuleName, string moduleDefinitionName) + public static string GetStringVersion(Version version) { - // get desktop module - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - if (desktopModule == null) + var versionArray = new int[3]; + versionArray[0] = version.Major; + versionArray[1] = version.Minor; + versionArray[2] = version.Build; + string stringVersion = Null.NullString; + for (int i = 0; i <= 2; i++) { - return -1; - } + if (versionArray[i] == 0) + { + stringVersion += "00"; + } + else if (versionArray[i] >= 1 && versionArray[i] <= 9) + { + stringVersion += "0" + versionArray[i]; + } + else + { + stringVersion += versionArray[i].ToString(); + } - // get module definition - ModuleDefinitionInfo objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(moduleDefinitionName, desktopModule.DesktopModuleID); - if (objModuleDefinition == null) - { - return -1; + if (i < 2) + { + stringVersion += "."; + } } - return objModuleDefinition.ModuleDefID; + return stringVersion; } /// ----------------------------------------------------------------------------- /// - /// HostTabExists determines whether a tab of a given name exists under the Host tab. + /// GetSuperUser gets the superuser from the Install Template. /// /// /// - /// The Name of the Tab. - /// True if the Tab exists, otherwise False. + /// The install Templae. + /// a flag to determine whether to output feedback. + /// /// ----------------------------------------------------------------------------- - private static bool HostTabExists(string tabName) + public static UserInfo GetSuperUser(XmlDocument xmlTemplate, bool writeFeedback) { - bool tabExists = false; - var hostTab = TabController.Instance.GetTabByName("Host", Null.NullInteger); - - var tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, hostTab.TabID); - if (tab != null) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "GetSuperUser"); + XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/superuser"); + UserInfo superUser = null; + if (node != null) { - tabExists = true; - } + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Configuring SuperUser:
    "); + } - return tabExists; - } + // Parse the SuperUsers nodes + string firstName = XmlUtils.GetNodeValue(node.CreateNavigator(), "firstname"); + string lastName = XmlUtils.GetNodeValue(node.CreateNavigator(), "lastname"); + string username = XmlUtils.GetNodeValue(node.CreateNavigator(), "username"); + string password = XmlUtils.GetNodeValue(node.CreateNavigator(), "password"); + string email = XmlUtils.GetNodeValue(node.CreateNavigator(), "email"); + string locale = XmlUtils.GetNodeValue(node.CreateNavigator(), "locale"); + string updatePassword = XmlUtils.GetNodeValue(node.CreateNavigator(), "updatepassword"); - /// ----------------------------------------------------------------------------- - /// - /// InstallMemberRoleProviderScript - Installs a specific MemberRole Provider script. - /// - /// - /// - /// The Path to the Provider Directory. - /// The Name of the Script File. - /// Whether or not to echo results. - private static string InstallMemberRoleProviderScript(string providerPath, string scriptFile, bool writeFeedback) - { - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Executing Script: " + scriptFile + "
    "); - } + superUser = new UserInfo + { + PortalID = -1, + FirstName = firstName, + LastName = lastName, + Username = username, + DisplayName = firstName + " " + lastName, + Membership = { Password = password }, + Email = email, + IsSuperUser = true, + }; + superUser.Membership.Approved = true; - string exceptions = DataProvider.Instance().ExecuteScript(FileSystemUtils.ReadFile(providerPath + scriptFile + ".sql")); + superUser.Profile.FirstName = firstName; + superUser.Profile.LastName = lastName; + superUser.Profile.PreferredLocale = locale; + superUser.Profile.PreferredTimeZone = TimeZoneInfo.Local; - // log the results - try - { - using (StreamWriter streamWriter = File.CreateText(providerPath + scriptFile + ".log.resources")) + if (updatePassword.ToLowerInvariant() == "true") { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); + superUser.Membership.UpdatePassword = true; } } - catch (Exception exc) - { - // does not have permission to create the log file - Logger.Error(exc); - } - return exceptions; + return superUser; } /// ----------------------------------------------------------------------------- /// - /// ParseFiles parses the Host Template's Files node. + /// GetUpgradeScripts gets an ArrayList of the Scripts required to Upgrade to the + /// current Assembly Version. /// /// /// - /// The Files node. - /// The PortalId (-1 for Host Files). + /// The path to the Data Provider. + /// The current Database Version. + /// /// ----------------------------------------------------------------------------- - private static void ParseFiles(XmlNode node, int portalId) + public static ArrayList GetUpgradeScripts(string providerPath, Version databaseVersion) { - // Parse the File nodes - if (node != null) + var scriptFiles = new ArrayList(); + string[] files = Directory.GetFiles(providerPath, "*." + DefaultProvider); + Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. + + Logger.TraceFormat("GetUpgradedScripts databaseVersion:{0} applicationVersion:{1}", databaseVersion, ApplicationVersion); + + foreach (string file in files) { - XmlNodeList nodes = node.SelectNodes("file"); - if (nodes != null) + // script file name must conform to ##.##.##.DefaultProviderName + if (file != null) { - var folderManager = FolderManager.Instance; - var fileManager = FileManager.Instance; - - foreach (XmlNode fileNode in nodes) + if (GetFileName(file).Length == 9 + DefaultProvider.Length) { - string fileName = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "filename"); - string extension = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "extension"); - long size = long.Parse(XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "size")); - int width = XmlUtils.GetNodeValueInt(fileNode, "width"); - int height = XmlUtils.GetNodeValueInt(fileNode, "height"); - string contentType = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "contentType"); - string folder = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "folder"); + var version = new Version(GetFileNameWithoutExtension(file)); - var folderInfo = folderManager.GetFolder(portalId, folder); - var file = new FileInfo(portalId, fileName, extension, (int)size, width, height, contentType, folder, folderInfo.FolderID, folderInfo.StorageLocation, true); + // check if script file is relevant for upgrade + if (version > databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) + { + scriptFiles.Add(file); - using (var fileContent = fileManager.GetFileContent(file)) + // check if any incrementals exist + var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); + if (incrementalfiles != null) + { + scriptFiles.AddRange(incrementalfiles); + } + + Logger.TraceFormat("GetUpgradedScripts including {0}", file); + } + + if (version == databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) { - var addedFile = fileManager.AddFile(folderInfo, file.FileName, fileContent, false); + var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); + if (incrementalfiles != null) + { + scriptFiles.AddRange(incrementalfiles); + } - file.FileId = addedFile.FileId; - file.EnablePublishPeriod = addedFile.EnablePublishPeriod; - file.EndDate = addedFile.EndDate; - file.StartDate = addedFile.StartDate; + Logger.TraceFormat("GetUpgradedScripts including {0}", file); } - fileManager.UpdateFile(file); + // else + // { + // Logger.TraceFormat("GetUpgradedScripts excluding {0}", file); + // } } } } + + return scriptFiles; } /// ----------------------------------------------------------------------------- /// - /// RemoveCoreModule removes a Core Module from the system. + /// InitialiseHostSettings gets the Host Settings from the Install Template. /// /// /// - /// The Friendly Name of the Module to Remove. - /// The Name of the parent Tab/Page for this module. - /// The Name to tab that contains the Module. - /// A flag to determine whether to remove the Tab if it has no - /// other modules. + /// The install Templae. + /// a flag to determine whether to output feedback. /// ----------------------------------------------------------------------------- - private static void RemoveCoreModule(string desktopModuleName, string parentTabName, string tabName, bool removeTab) + public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveCoreModule:" + desktopModuleName); - - int moduleDefId = Null.NullInteger; - int desktopModuleId = 0; - - // Find and remove the Module from the Tab - switch (parentTabName) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InitialiseHostSettings"); + XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/settings"); + if (node != null) { - case "Host": - var tab = TabController.Instance.GetTabByName("Host", Null.NullInteger, Null.NullInteger); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Settings:
    "); + } - if (tab != null) + // Need to clear the cache to pick up new HostSettings from the SQLDataProvider script + DataCache.RemoveCache(DataCache.HostSettingsCacheKey); + + // Parse the Settings nodes + foreach (XmlNode settingNode in node.ChildNodes) + { + string settingName = settingNode.Name; + string settingValue = settingNode.InnerText; + if (settingNode.Attributes != null) { - moduleDefId = RemoveModule(desktopModuleName, tabName, tab.TabID, removeTab); - } + XmlAttribute secureAttrib = settingNode.Attributes["Secure"]; + bool settingIsSecure = false; + if (secureAttrib != null) + { + if (secureAttrib.Value.ToLowerInvariant() == "true") + { + settingIsSecure = true; + } + } - break; - case "Admin": - var portals = PortalController.Instance.GetPortals(); + string domainName = Globals.GetDomainName(HttpContext.Current.Request); - // Iterate through the Portals to remove the Module from the Tab - for (int intPortal = 0; intPortal <= portals.Count - 1; intPortal++) - { - var portal = (PortalInfo)portals[intPortal]; - moduleDefId = RemoveModule(desktopModuleName, tabName, portal.AdminTabId, removeTab); - } + switch (settingName) + { + case "HostURL": + if (string.IsNullOrEmpty(settingValue)) + { + settingValue = domainName; + } - break; - } + break; + case "HostEmail": + if (string.IsNullOrEmpty(settingValue)) + { + settingValue = "support@" + domainName; - DesktopModuleInfo desktopModule = null; - if (moduleDefId == Null.NullInteger) - { - desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - desktopModuleId = desktopModule.DesktopModuleID; - } - else - { - // Get the Module Definition - ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId); - if (moduleDefinition != null) - { - desktopModuleId = moduleDefinition.DesktopModuleID; - desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); - } - } + // Remove any folders + settingValue = settingValue.Substring(0, settingValue.IndexOf("/")); - if (desktopModule != null) - { - // Delete the Desktop Module - var desktopModuleController = new DesktopModuleController(); - desktopModuleController.DeleteDesktopModule(desktopModuleId); + // Remove port number + if (settingValue.IndexOf(":") != -1) + { + settingValue = settingValue.Substring(0, settingValue.IndexOf(":")); + } + } - // Delete the Package - PackageController.Instance.DeleteExtensionPackage(PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID)); + break; + } + + HostController.Instance.Update(settingName, settingValue, settingIsSecure); + } + } } } - private static void RemoveModuleControl(int moduleDefId, string controlKey) + /// ----------------------------------------------------------------------------- + /// + /// InstallDatabase runs all the "scripts" identifed in the Install Template to + /// install the base version. + /// + /// + /// + /// + /// The Xml Document to load. + /// A flag that determines whether to output feedback to the Response Stream. + /// + /// A string which contains the error message - if appropriate. + /// ----------------------------------------------------------------------------- + public static string InstallDatabase(Version version, string providerPath, XmlDocument xmlDoc, bool writeFeedback) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleControl:" + moduleDefId); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDatabase:" + Globals.FormatVersion(version)); + string defaultProvider = Config.GetDefaultProvider("data").Name; + string message = Null.NullString; - // get Module Control - var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); - if (moduleControl != null) + // Output feedback line + if (writeFeedback) { - ModuleControlController.DeleteModuleControl(moduleControl.ModuleControlID); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Version: " + Globals.FormatVersion(version) + "
    "); } - } - private static void RemoveModuleFromPortals(string friendlyName) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleFromPortals:" + friendlyName); - DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); - if (desktopModule != null) + // Parse the script nodes + XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/scripts"); + if (node != null) { - // Module was incorrectly assigned as "IsPremium=False" - if (desktopModule.PackageID > Null.NullInteger) - { - desktopModule.IsPremium = true; - DesktopModuleController.SaveDesktopModule(desktopModule, false, true); - } - - // Remove the module from Portals - DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); + // Loop through the available scripts + message = (from XmlNode scriptNode in node.SelectNodes("script") select scriptNode.InnerText + "." + defaultProvider).Aggregate(message, (current, script) => current + ExecuteScript(providerPath + script, writeFeedback)); } - } - private static bool TabPermissionExists(TabPermissionInfo tabPermission, int portalID) - { - return TabPermissionController.GetTabPermissions(tabPermission.TabID, portalID).Cast().Any(permission => permission.TabID == tabPermission.TabID && permission.RoleID == tabPermission.RoleID && permission.PermissionID == tabPermission.PermissionID); + // update the version + Globals.UpdateDataBaseVersion(version); + + // Optionally Install the memberRoleProvider + message += InstallMemberRoleProvider(providerPath, writeFeedback); + + return message; } - private static void FavIconsToPortalSettings() + /// ----------------------------------------------------------------------------- + /// + /// InstallDNN manages the Installation of a new DotNetNuke Application. + /// + /// + /// + /// The path to the Data Provider. + /// ----------------------------------------------------------------------------- + public static void InstallDNN(string strProviderPath) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "FavIconsToPortalSettings"); - const string fileName = "favicon.ico"; - var portals = PortalController.Instance.GetPortals().Cast(); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDNN:" + strProviderPath); + var xmlDoc = new XmlDocument { XmlResolver = null }; - foreach (var portalInfo in portals) + // open the Install Template XML file + string errorMessage = GetInstallTemplate(xmlDoc); + + if (string.IsNullOrEmpty(errorMessage)) { - string localPath = Path.Combine(portalInfo.HomeDirectoryMapPath, fileName); + // get base version + Version baseVersion = GetInstallVersion(xmlDoc); - if (File.Exists(localPath)) - { - try - { - int fileId; - var folder = FolderManager.Instance.GetFolder(portalInfo.PortalID, string.Empty); - if (!FileManager.Instance.FileExists(folder, fileName)) - { - using (var stream = File.OpenRead(localPath)) - { - FileManager.Instance.AddFile(folder, fileName, stream, /*overwrite*/ false); - } - } + // Install Base Version + InstallDatabase(baseVersion, strProviderPath, xmlDoc, true); - fileId = FileManager.Instance.GetFile(folder, fileName).FileId; + // Call Upgrade with the current DB Version to carry out any incremental upgrades + UpgradeDNN(strProviderPath, baseVersion); - new FavIcon(portalInfo.PortalID).Update(fileId); - } - catch (Exception e) - { - string message = string.Format("Unable to setup Favicon for Portal: {0}", portalInfo.PortalName); - var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; - log.AddProperty("Issue", message); - log.AddProperty("ExceptionMessage", e.Message); - log.AddProperty("StackTrace", e.StackTrace); - LogController.Instance.AddLog(log); + // parse Host Settings if available + InitialiseHostSettings(xmlDoc, true); - Logger.Warn(message, e); - } + // Create SuperUser only when it's not there (even soft deleted) + var superUsers = UserController.GetUsers(true, true, Null.NullInteger); + if (superUsers == null || superUsers.Count == 0) + { + // parse SuperUser if Available + UserInfo superUser = GetSuperUser(xmlDoc, true); + UserController.CreateUser(ref superUser); + superUsers.Add(superUser); } - } - } - private static void AddIconToAllowedFiles() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddIconToAllowedFiles"); - var toAdd = new List { ".ico" }; - HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); - } + // parse File List if available + InstallFiles(xmlDoc, true); - private static void UpgradeToVersion323() - { - // add new SecurityException - string configFile = Globals.HostMapPath + "Logs\\LogConfig\\SecurityExceptionTemplate.xml.resources"; - LogController.Instance.AddLogType(configFile, Null.NullString); - } + // Run any addition scripts in the Scripts folder + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing Additional Scripts:
    "); + ExecuteScripts(strProviderPath); - private static void UpgradeToVersion440() - { - // remove module cache files with *.htm extension ( they are now securely named *.resources ) - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo objPortal in portals) - { - if (Directory.Exists(Globals.ApplicationMapPath + "\\Portals\\" + objPortal.PortalID + "\\Cache\\")) - { - string[] files = Directory.GetFiles(Globals.ApplicationMapPath + "\\Portals\\" + objPortal.PortalID + "\\Cache\\", "*.htm"); - foreach (string file in files) - { - File.Delete(file); - } + // Install optional resources if present + var packages = GetInstallPackages(); + foreach (var package in packages) + { + InstallPackage(package.Key, package.Value.PackageType, true); } - } - } - private static void UpgradeToVersion470() - { - string hostTemplateFile = Globals.HostMapPath + "Templates\\Default.page.template"; - if (File.Exists(hostTemplateFile)) - { - ArrayList portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + // Set Status to None + Globals.SetStatus(Globals.UpgradeStatus.None); + + // download LP (and templates) if not using en-us + IInstallationStep ensureLpAndTemplate = new UpdateLanguagePackStep(); + ensureLpAndTemplate.Execute(); + + // install LP that contains templates if installing in a different language + var installConfig = InstallController.Instance.GetInstallConfig(); + string culture = installConfig.InstallCulture; + if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { - string portalTemplateFolder = portal.HomeDirectoryMapPath + "Templates\\"; + string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); + string lpAndTemplates = installFolder + "\\installlanguage.resources"; - if (!Directory.Exists(portalTemplateFolder)) + if (File.Exists(lpAndTemplates)) { - // Create Portal Templates folder - Directory.CreateDirectory(portalTemplateFolder); + InstallPackage(lpAndTemplates, "Language", false); } + } - string portalTemplateFile = portalTemplateFolder + "Default.page.template"; - if (!File.Exists(portalTemplateFile)) + // parse portal(s) if available + XmlNodeList nodes = xmlDoc.SelectNodes("//dotnetnuke/portals/portal"); + if (nodes != null) + { + foreach (XmlNode node in nodes) { - File.Copy(hostTemplateFile, portalTemplateFile); + if (node != null) + { + // add item to identity install from install wizard. + if (HttpContext.Current != null) + { + HttpContext.Current.Items.Add("InstallFromWizard", true); + } - // Synchronize the Templates folder to ensure the templates are accessible - FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); + var portalHost = superUsers[0] as UserInfo; + int portalId = AddPortal(node, true, 2, portalHost); + if (portalId > -1) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Successfully Installed Site " + portalId + ":
    "); + } + else + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Site failed to install:Error!
    "); + } + } } } } + else + { + // 500 Error - Redirect to ErrorPage + if (HttpContext.Current != null) + { + string url = "~/ErrorPage.aspx?status=500&error=" + errorMessage; + HttpContext.Current.Response.Clear(); + HttpContext.Current.Server.Transfer(url); + } + } } - private static void UpgradeToVersion482() - { - // checks for the very rare case where the default validationkey prior to 4.08.02 - // is still being used and updates it - Config.UpdateValidationKey(); - } - - private static void UpgradeToVersion500() + /// ----------------------------------------------------------------------------- + /// + /// InstallFiles intsalls any files listed in the Host Install Configuration file. + /// + /// + /// + /// The Xml Document to load. + /// A flag that determines whether to output feedback to the Response Stream. + /// ----------------------------------------------------------------------------- + public static void InstallFiles(XmlDocument xmlDoc, bool writeFeedback) { - ArrayList portals = PortalController.Instance.GetPortals(); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallFiles"); - // Add Edit Permissions for Admin Tabs to legacy portals - var permissionController = new PermissionController(); - ArrayList permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT"); - int permissionId = -1; - if (permissions.Count == 1) + // Parse the file nodes + XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/files"); + if (node != null) { - var permission = permissions[0] as PermissionInfo; - if (permission != null) + if (writeFeedback) { - permissionId = permission.PermissionID; + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Files:
    "); } - foreach (PortalInfo portal in portals) - { - var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, true); - if (adminTab != null) - { - var tabPermission = new TabPermissionInfo { TabID = adminTab.TabID, PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; - if (!TabPermissionExists(tabPermission, portal.PortalID)) - { - adminTab.TabPermissions.Add(tabPermission); - } + ParseFiles(node, Null.NullInteger); + } - // Save Tab Permissions to Data Base - TabPermissionController.SaveTabPermissions(adminTab); + // Synchronise Host Folder + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Synchronizing Host Files:
    "); + } - foreach (var childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) - { - tabPermission = new TabPermissionInfo { TabID = childTab.TabID, PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; - if (!TabPermissionExists(tabPermission, portal.PortalID)) - { - childTab.TabPermissions.Add(tabPermission); - } + FolderManager.Instance.Synchronize(Null.NullInteger, string.Empty, true, true); + } - // Save Tab Permissions to Data Base - TabPermissionController.SaveTabPermissions(childTab); - } - } - } + public static bool InstallPackage(string file, string packageType, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackage:" + file); + bool success = Null.NullBoolean; + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Installing Package File " + Path.GetFileNameWithoutExtension(file) + ": "); } - // Update Host/Admin modules Visibility setting - bool superTabProcessed = Null.NullBoolean; - foreach (PortalInfo portal in portals) + bool deleteTempFolder = true; + if (packageType == "Skin" || packageType == "Container") { - if (!superTabProcessed) + deleteTempFolder = Null.NullBoolean; + } + + var installer = new Installer(new FileStream(file, FileMode.Open, FileAccess.Read), Globals.ApplicationMapPath, true, deleteTempFolder); + + // Check if manifest is valid + if (installer.IsValid) + { + installer.InstallerInfo.RepairInstall = true; + success = installer.Install(); + } + else + { + if (installer.InstallerInfo.ManifestFile == null) { - // Process Host Tabs - foreach (TabInfo childTab in TabController.GetTabsByParent(portal.SuperTabId, Null.NullInteger)) + // Missing manifest + if (packageType == "Skin" || packageType == "Container") { - foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) + // Legacy Skin/Container + string tempInstallFolder = installer.TempInstallFolder; + string manifestFile = Path.Combine(tempInstallFolder, Path.GetFileNameWithoutExtension(file) + ".dnn"); + using (var manifestWriter = new StreamWriter(manifestFile)) { - tabModule.Visibility = VisibilityState.None; - ModuleController.Instance.UpdateModule(tabModule); + manifestWriter.Write(LegacyUtil.CreateSkinManifest(file, packageType, tempInstallFolder)); } + + installer = new Installer(tempInstallFolder, manifestFile, HttpContext.Current.Request.MapPath("."), true); + + // Set the Repair flag to true for Batch Install + installer.InstallerInfo.RepairInstall = true; + + success = installer.Install(); + } + else if (Globals.Status != Globals.UpgradeStatus.None) + { + var message = string.Format(Localization.GetString("InstallPackageError", Localization.ExceptionsResourceFile), file, "Manifest file missing"); + DnnInstallLogger.InstallLogError(message); } } - - // Process Portal Tabs - foreach (TabInfo childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) + else { - foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) + // log the failure log when installer is invalid and not caught by mainfest file missing. + foreach (var log in installer.InstallerInfo.Log.Logs + .Where(l => l.Type == LogType.Failure)) { - tabModule.Visibility = VisibilityState.None; - ModuleController.Instance.UpdateModule(tabModule); + Logger.Error(log.Description); + DnnInstallLogger.InstallLogError(log.Description); } + + success = false; } } - // Upgrade PortalDesktopModules to support new "model" - permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_DESKTOPMODULE", "DEPLOY"); - if (permissions.Count == 1) + if (writeFeedback) { - var permission = permissions[0] as PermissionInfo; - if (permission != null) + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, success); + } + + if (success) + { + // delete file + try { - permissionId = permission.PermissionID; + File.SetAttributes(file, FileAttributes.Normal); + File.Delete(file); } - - foreach (PortalInfo portal in portals) + catch (Exception exc) { - foreach (DesktopModuleInfo desktopModule in DesktopModuleController.GetDesktopModules(Null.NullInteger).Values) - { - if (!desktopModule.IsPremium) - { - // Parse the permissions - var deployPermissions = new DesktopModulePermissionCollection(); - DesktopModulePermissionInfo deployPermission; - - // if Not IsAdmin add Registered Users - if (!desktopModule.IsAdmin) - { - deployPermission = new DesktopModulePermissionInfo { PermissionID = permissionId, AllowAccess = true, RoleID = portal.RegisteredRoleId }; - deployPermissions.Add(deployPermission); - } + Logger.Error(exc); + } + } - // if Not a Host Module add Administrators - const string hostModules = "Portals, SQL, HostSettings, Scheduler, SearchAdmin, Lists, SkinDesigner, Extensions"; - if (!hostModules.Contains(desktopModule.ModuleName)) - { - deployPermission = new DesktopModulePermissionInfo { PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; - deployPermissions.Add(deployPermission); - } + return success; + } - // Add Portal/Module to PortalDesktopModules - DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, false); - } - } + /// + /// Gets a ist of installable extensions sorted to ensure dependencies are installed first. + /// + /// + public static IDictionary GetInstallPackages() + { + var packageTypes = new string[] { "Library", "Module", "Skin", "Container", "JavaScriptLibrary", "Language", "Provider", "AuthSystem", "Package" }; + var invalidPackages = new List(); - DataCache.ClearPortalCache(portal.PortalID, true); - } - } + var packages = new Dictionary(); - LegacyUtil.ProcessLegacyModules(); - LegacyUtil.ProcessLegacyLanguages(); - LegacyUtil.ProcessLegacySkins(); - LegacyUtil.ProcessLegacySkinControls(); - } + ParsePackagesFromApplicationPath(packageTypes, packages, invalidPackages); - private static void UpgradeToVersion501() - { - // add new Cache Error Event Type - string configFile = string.Format("{0}Logs\\LogConfig\\CacheErrorTemplate.xml.resources", Globals.HostMapPath); - LogController.Instance.AddLogType(configFile, Null.NullString); - } + // Add packages with no dependency requirements + var sortedPackages = packages.Where(p => p.Value.Dependencies.Count == 0).ToDictionary(p => p.Key, p => p.Value); - private static void UpgradeToVersion510() - { - int moduleDefId; + var prevDependentCount = -1; - // add Dashboard module and tab - if (HostTabExists("Dashboard") == false) + var dependentPackages = packages.Where(p => p.Value.Dependencies.Count > 0).ToDictionary(p => p.Key, p => p.Value); + var dependentCount = dependentPackages.Count; + while (dependentCount != prevDependentCount) { - moduleDefId = AddModuleDefinition("Dashboard", "Provides a snapshot of your DotNetNuke Application.", "Dashboard", true, true); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Dashboard/Dashboard.ascx", "icon_dashboard_32px.gif", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Export", string.Empty, "DesktopModules/Admin/Dashboard/Export.ascx", string.Empty, SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); + 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); + } + } - // Create New Host Page (or get existing one) - TabInfo dashboardPage = AddHostPage("Dashboard", "Summary view of application and site settings.", "~/images/icon_dashboard_16px.gif", "~/images/icon_dashboard_32px.gif", true); + foreach (var packageKey in addedPackages) + { + dependentPackages.Remove(packageKey); + } - // Add Module To Page - AddModuleToPage(dashboardPage, moduleDefId, "Dashboard", "~/images/icon_dashboard_32px.gif"); + dependentCount = dependentPackages.Count; } - else - { - // Module was incorrectly assigned as "IsPremium=False" - RemoveModuleFromPortals("Dashboard"); - // fix path for dashboarcontrols - moduleDefId = GetModuleDefinition("Dashboard", "Dashboard"); - RemoveModuleControl(moduleDefId, "DashboardControls"); - AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); + // Add any packages whose dependency cannot be resolved + foreach (var package in dependentPackages) + { + sortedPackages.Add(package.Key, package.Value); } - // Add the Extensions Module - if (CoreModuleExists("Extensions") == false) + return sortedPackages; + } + + public static void InstallPackages(string packageType, bool writeFeedback) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackages:" + packageType); + if (writeFeedback) { - moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Extensions/Extensions.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.View, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Feature", "DesktopModules/Admin/Extensions/EditExtension.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Edit, 0); - AddModuleControl(moduleDefId, "PackageWriter", "Package Writer", "DesktopModules/Admin/Extensions/PackageWriter.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "EditControl", "Edit Control", "DesktopModules/Admin/Extensions/Editors/EditModuleControl.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "ImportModuleDefinition", "Import Module Definition", "DesktopModules/Admin/Extensions/Editors/ImportModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "BatchInstall", "Batch Install", "DesktopModules/Admin/Extensions/BatchInstall.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "NewExtension", "New Extension Wizard", "DesktopModules/Admin/Extensions/ExtensionWizard.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
    "); } - else - { - moduleDefId = GetModuleDefinition("Extensions", "Extensions"); - RemoveModuleControl(moduleDefId, "EditLanguage"); - RemoveModuleControl(moduleDefId, "TimeZone"); - RemoveModuleControl(moduleDefId, "Verify"); - RemoveModuleControl(moduleDefId, "LanguageSettings"); - RemoveModuleControl(moduleDefId, "EditResourceKey"); - RemoveModuleControl(moduleDefId, "EditSkins"); - AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); - // Module was incorrectly assigned as "IsPremium=False" - RemoveModuleFromPortals("Extensions"); + 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); + } + } } + } - // Remove Module Definitions Module from Host Page (if present) - RemoveCoreModule("Module Definitions", "Host", "Module Definitions", false); - - // Remove old Module Definition DynamicContentValidator module - DesktopModuleController.DeleteDesktopModule("Module Definition DynamicContentValidator"); - - // Get Module Definitions - TabInfo definitionsPage = TabController.Instance.GetTabByName("Module Definitions", Null.NullInteger); + 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; + } - // Add Module To Page if not present - int moduleId = AddModuleToPage(definitionsPage, moduleDefId, "Module Definitions", "~/images/icon_moduledefinitions_32px.gif"); - ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "Module"); + 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; + } - // Add Extensions Host Page - TabInfo extensionsPage = AddHostPage("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true); + break; + case "4.5": + // Try and instantiate a 4.5 Class + if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) + { + isCurrent = true; + } - moduleId = AddModuleToPage(extensionsPage, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); - ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "All"); + break; + } - // Add Extensions Module to Admin Page for all Portals - AddAdminPages("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); + return isCurrent; + } - // Remove Host Languages Page - RemoveHostPage("Languages"); + public static void RemoveAdminPages(string tabPath) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveAdminPages:" + tabPath); - // Remove Admin > Authentication Pages - RemoveAdminPages("//Admin//Authentication"); + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) + { + var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); + if (tabID != Null.NullInteger) + { + TabController.Instance.DeleteTab(tabID, portal.PortalID); + } + } + } - // Remove old Languages module - DesktopModuleController.DeleteDesktopModule("Languages"); + public static void RemoveHostPage(string pageName) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveHostPage:" + pageName); + TabInfo skinsTab = TabController.Instance.GetTabByName(pageName, Null.NullInteger); + if (skinsTab != null) + { + TabController.Instance.DeleteTab(skinsTab.TabID, Null.NullInteger); + } + } - // Add new Languages module - moduleDefId = AddModuleDefinition("Languages", string.Empty, "Languages", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Language", "DesktopModules/Admin/Languages/EditLanguage.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); - AddModuleControl(moduleDefId, "EditResourceKey", "Full Language Editor", "DesktopModules/Admin/Languages/languageeditorext.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); - AddModuleControl(moduleDefId, "LanguageSettings", "Language Settings", "DesktopModules/Admin/Languages/LanguageSettings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); - AddModuleControl(moduleDefId, "TimeZone", "TimeZone Editor", "DesktopModules/Admin/Languages/timezoneeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Verify", "Resource File Verifier", "DesktopModules/Admin/Languages/resourceverifier.ascx", string.Empty, SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "PackageWriter", "Language Pack Writer", "DesktopModules/Admin/Languages/LanguagePackWriter.ascx", string.Empty, SecurityAccessLevel.Host, 0); + public static void StartTimer() + { + // Start Upgrade Timer + _startTime = DateTime.Now; + } - // Add Module to Admin Page for all Portals - AddAdminPages("Languages", "Manage Language Resources.", "~/images/icon_language_16px.gif", "~/images/icon_language_32px.gif", true, moduleDefId, "Language Editor", "~/images/icon_language_32px.gif"); + public static void TryUpgradeNETFramework() + { + switch (Globals.NETFrameworkVersion.ToString(2)) + { + case "3.5": + if (!IsNETFrameworkCurrent("3.5")) + { + // Upgrade to .NET 3.5 + string upgradeFile = string.Format("{0}\\Config\\Net35.config", Globals.InstallMapPath); + string message = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 3.5 Upgrade"); + if (string.IsNullOrEmpty(message)) + { + // Remove old AJAX file + FileSystemUtils.DeleteFile(Path.Combine(Globals.ApplicationMapPath, "bin\\System.Web.Extensions.dll")); - // Remove Host Skins Page - RemoveHostPage("Skins"); + // Log Upgrade + EventLogController.Instance.AddLog("UpgradeNet", "Upgraded Site to .NET 3.5", PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); + } + else + { + // Log Failed Upgrade + EventLogController.Instance.AddLog("UpgradeNet", string.Format("Upgrade to .NET 3.5 failed. Error reported during attempt to update:{0}", message), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); + } + } - // Remove old Skins module - DesktopModuleController.DeleteDesktopModule("Skins"); + break; + case "4.0": + if (!IsNETFrameworkCurrent("4.0")) + { + // Upgrade to .NET 4.0 + string upgradeFile = string.Format("{0}\\Config\\Net40.config", Globals.InstallMapPath); + string strMessage = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 4.0 Upgrade"); + EventLogController.Instance.AddLog( + "UpgradeNet", + string.IsNullOrEmpty(strMessage) + ? "Upgraded Site to .NET 4.0" + : string.Format("Upgrade to .NET 4.0 failed. Error reported during attempt to update:{0}", strMessage), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.HOST_ALERT); + } - // Add new Skins module - moduleDefId = AddModuleDefinition("Skins", string.Empty, "Skins", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Skins/editskins.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.View, 0); + break; + } + } - // Add Module to Admin Page for all Portals - AddAdminPages("Skins", "Manage Skin Resources.", "~/images/icon_skins_16px.gif", "~/images/icon_skins_32px.gif", true, moduleDefId, "Skin Editor", "~/images/icon_skins_32px.gif"); - - // Remove old Skin Designer module - DesktopModuleController.DeleteDesktopModule("Skin Designer"); - DesktopModuleController.DeleteDesktopModule("SkinDesigner"); - - // Add new Skin Designer module - moduleDefId = AddModuleDefinition("Skin Designer", "Allows you to modify skin attributes.", "Skin Designer", true, true); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SkinDesigner/Attributes.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.Host, 0); - - // Add new Skin Designer to every Admin Skins Tab - AddModuleToPages("//Admin//Skins", moduleDefId, "Skin Designer", "~/images/icon_skins_32px.gif", true); - - // Remove Admin Whats New Page - RemoveAdminPages("//Admin//WhatsNew"); - - // WhatsNew needs to be set to IsPremium and removed from all portals - RemoveModuleFromPortals("WhatsNew"); - - // Create New WhatsNew Host Page (or get existing one) - TabInfo newPage = AddHostPage("What's New", "Provides a summary of the major features for each release.", "~/images/icon_whatsnew_16px.gif", "~/images/icon_whatsnew_32px.gif", true); - - // Add WhatsNew Module To Page - moduleDefId = GetModuleDefinition("WhatsNew", "WhatsNew"); - AddModuleToPage(newPage, moduleDefId, "What's New", "~/images/icon_whatsnew_32px.gif"); - - // add console module - moduleDefId = AddModuleDefinition("Console", "Display children pages as icon links for navigation.", "Console", "DotNetNuke.Modules.Console.Components.ConsoleController", true, false, false); - AddModuleControl(moduleDefId, string.Empty, "Console", "DesktopModules/Admin/Console/ViewConsole.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Console Settings", "DesktopModules/Admin/Console/Settings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - - // add console module to host page - moduleId = AddModuleToPage("//Host", Null.NullInteger, moduleDefId, "Basic Features", string.Empty, true); - int tabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host", Null.NullString); - TabInfo tab; - - // add console settings for host page - if (tabId != Null.NullInteger) - { - tab = TabController.Instance.GetTab(tabId, Null.NullInteger, true); - if (tab != null) - { - AddConsoleModuleSettings(moduleId); - } - } - - // add module to all admin pages - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + /// ----------------------------------------------------------------------------- + /// + /// UpgradeApplication - This overload is used for general application upgrade operations. + /// + /// + /// Since it is not version specific and is invoked whenever the application is + /// restarted, the operations must be re-executable. + /// + /// ----------------------------------------------------------------------------- + public static void UpgradeApplication() + { + try { - tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); - if (tabId != Null.NullInteger) - { - tab = TabController.Instance.GetTab(tabId, portal.PortalID, true); - if (tab != null) - { - moduleId = AddModuleToPage(tab, moduleDefId, "Basic Features", string.Empty, true); - AddConsoleModuleSettings(moduleId); - } - } - } - - // Add Google Analytics module - moduleDefId = AddModuleDefinition("Google Analytics", "Configure Site Google Analytics settings.", "GoogleAnalytics", false, false); - AddModuleControl(moduleDefId, string.Empty, "Google Analytics", "DesktopModules/Admin/Analytics/GoogleAnalyticsSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddAdminPages("Google Analytics", "Configure Site Google Analytics settings.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Google Analytics", "~/images/icon_analytics_32px.gif"); - } + // Remove UpdatePanel from Login Control - not neccessary in popup. + var loginControl = ModuleControlController.GetModuleControlByControlKey("Login", -1); + loginControl.SupportsPartialRendering = false; - private static void UpgradeToVersion511() - { - // New Admin pages may not have administrator permission - // Add Admin role if it does not exist for google analytics or extensions - AddAdminRoleToPage("//Admin//Extensions"); - AddAdminRoleToPage("//Admin//GoogleAnalytics"); - } + ModuleControlController.SaveModuleControl(loginControl, true); - private static void UpgradeToVersion513() - { - // Ensure that default language is present (not neccessarily enabled) - var defaultLanguage = LocaleController.Instance.GetLocale("en-US") ?? new Locale(); - defaultLanguage.Code = "en-US"; - defaultLanguage.Text = "English (United States)"; - Localization.SaveLanguage(defaultLanguage); + // Upgrade to .NET 3.5/4.0 + TryUpgradeNETFramework(); - // Ensure that there is a Default Authorization System - var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DefaultAuthentication"); - if (package == null) + // Update the version of the client resources - so the cache is cleared + DataCache.ClearHostCache(false); + HostController.Instance.IncrementCrmVersion(true); + } + catch (Exception ex) { - package = new PackageInfo + Logger.Error(ex); + var log = new LogInfo { - Name = "DefaultAuthentication", - FriendlyName = "Default Authentication", - Description = "The Default UserName/Password Authentication System for DotNetNuke.", - PackageType = "Auth_System", - Version = new Version(1, 0, 0), - Owner = "DNN", - License = Localization.GetString("License", Localization.GlobalResourceFile), - Organization = ".NET Foundation", - Url = "https://dnncommunity.org", - Email = "info@dnncommunity.org", - ReleaseNotes = "There are no release notes for this version.", - IsSystemPackage = true, + LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), + BypassBuffering = true, }; - PackageController.Instance.SaveExtensionPackage(package); - - // Add Authentication System - var authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN") ?? new AuthenticationInfo(); - authSystem.PackageID = package.PackageID; - authSystem.AuthenticationType = "DNN"; - authSystem.SettingsControlSrc = "DesktopModules/AuthenticationServices/DNN/Settings.ascx"; - authSystem.LoginControlSrc = "DesktopModules/AuthenticationServices/DNN/Login.ascx"; - authSystem.IsEnabled = true; - - if (authSystem.AuthenticationID == Null.NullInteger) + log.AddProperty("Upgraded DotNetNuke", "General"); + log.AddProperty("Warnings", "Error: " + ex.Message + Environment.NewLine); + LogController.Instance.AddLog(log); + try { - AuthenticationController.AddAuthentication(authSystem); + Exceptions.Exceptions.LogException(ex); } - else + catch (Exception exc) { - AuthenticationController.UpdateAuthentication(authSystem); + Logger.Error(exc); } } - } - private static void UpgradeToVersion520() - { - // Add new ViewSource control - AddModuleControl(Null.NullInteger, "ViewSource", "View Module Source", "Admin/Modules/ViewSource.ascx", "~/images/icon_source_32px.gif", SecurityAccessLevel.Host, 0, string.Empty, true); - - // Add Marketplace module definition - int moduleDefId = AddModuleDefinition("Marketplace", "Search for DotNetNuke modules, extension and skins.", "Marketplace"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Marketplace/Marketplace.ascx", "~/images/icon_marketplace_32px.gif", SecurityAccessLevel.Host, 0); - - // Add marketplace Module To Page - TabInfo newPage = AddHostPage("Marketplace", "Search for DotNetNuke modules, extension and skins.", "~/images/icon_marketplace_16px.gif", "~/images/icon_marketplace_32px.gif", true); - moduleDefId = GetModuleDefinition("Marketplace", "Marketplace"); - AddModuleToPage(newPage, moduleDefId, "Marketplace", "~/images/icon_marketplace_32px.gif"); - } - - private static void UpgradeToVersion521() - { - // UpgradeDefaultLanguages is a temporary procedure containing code that - // needed to execute after the 5.1.3 application upgrade code above - DataProvider.Instance().ExecuteNonQuery("UpgradeDefaultLanguages"); + // Remove any .txt and .config files that may exist in the Install folder + foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.txt") + .Concat(Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.??.txt"))) + { + FileSystemUtils.DeleteFile(file); + } - // This procedure is not intended to be part of the database schema - // and is therefore dropped once it has been executed. - using (DataProvider.Instance().ExecuteSQL("DROP PROCEDURE {databaseOwner}{objectQualifier}UpgradeDefaultLanguages")) + foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.config") + .Concat(Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.??.config"))) { + FileSystemUtils.DeleteFile(file); } } - private static void UpgradeToVersion530() + /// ----------------------------------------------------------------------------- + /// + /// UpgradeApplication - This overload is used for version specific application upgrade operations. + /// + /// + /// This should be used for file system modifications or upgrade operations which + /// should only happen once. Database references are not recommended because future + /// versions of the application may result in code incompatibilties. + /// + /// + /// ----------------------------------------------------------------------------- + public static string UpgradeApplication(string providerPath, Version version, bool writeFeedback) { - // update languages module - int moduleDefId = GetModuleDefinition("Languages", "Languages"); - RemoveModuleControl(moduleDefId, string.Empty); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageEnabler.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0, string.Empty, true); - AddModuleControl(moduleDefId, "Editor", string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); - - // Add new View Profile module - moduleDefId = AddModuleDefinition("ViewProfile", string.Empty, "ViewProfile", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ViewProfile/ViewProfile.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.View, 0); - AddModuleControl(moduleDefId, "Settings", "Settings", "DesktopModules/Admin/ViewProfile/Settings.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.Edit, 0); - - // Add new Sitemap settings module - moduleDefId = AddModuleDefinition("Sitemap", string.Empty, "Sitemap", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Sitemap/SitemapSettings.ascx", "~/images/icon_analytics_32px.gif", SecurityAccessLevel.View, 0); - AddAdminPages("Search Engine Sitemap", "Configure the sitemap for submission to common search engines.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Search Engine Sitemap", "~/images/icon_analytics_32px.gif"); - - // Add new Photo Profile field to Host - var listController = new ListController(); - Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - - var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); - ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); - - string installTemplateFile = string.Format("{0}Template\\UserProfile.page.template", Globals.InstallMapPath); - string hostTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.HostMapPath); - if (File.Exists(installTemplateFile)) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); + string exceptions = string.Empty; + if (writeFeedback) { - if (!File.Exists(hostTemplateFile)) - { - File.Copy(installTemplateFile, hostTemplateFile); - } + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + " : " + GetStringVersionWithRevision(version)); } - if (File.Exists(hostTemplateFile)) + try { - ArrayList portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + if (version.Revision == -1) { - properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID); - - // Add new Photo Profile field to Portal - ProfileController.AddDefaultDefinition(portal.PortalID, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); - - // Rename old Default Page template - string defaultPageTemplatePath = string.Format("{0}Templates\\Default.page.template", portal.HomeDirectoryMapPath); - if (File.Exists(defaultPageTemplatePath)) - { - File.Move(defaultPageTemplatePath, string.Format("{0}Templates\\Default_old.page.template", portal.HomeDirectoryMapPath)); - } - - // Update Default profile template in every portal - PortalController.Instance.CopyPageTemplate("Default.page.template", portal.HomeDirectoryMapPath); - - // Add User profile template to every portal - PortalController.Instance.CopyPageTemplate("UserProfile.page.template", portal.HomeDirectoryMapPath); - - // Synchronize the Templates folder to ensure the templates are accessible - FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); - - var xmlDoc = new XmlDocument { XmlResolver = null }; - try + switch (version.ToString(3)) { - // open the XML file - xmlDoc.Load(hostTemplateFile); - } - catch (Exception ex) + case "3.2.3": + UpgradeToVersion323(); + break; + case "4.4.0": + UpgradeToVersion440(); + break; + case "4.7.0": + UpgradeToVersion470(); + break; + case "4.8.2": + UpgradeToVersion482(); + break; + case "5.0.0": + UpgradeToVersion500(); + break; + case "5.0.1": + UpgradeToVersion501(); + break; + case "5.1.0": + UpgradeToVersion510(); + break; + case "5.1.1.0": + UpgradeToVersion511(); + break; + case "5.1.3": + UpgradeToVersion513(); + break; + case "5.2.0": + UpgradeToVersion520(); + break; + case "5.2.1": + UpgradeToVersion521(); + break; + case "5.3.0": + UpgradeToVersion530(); + break; + case "5.4.0": + UpgradeToVersion540(); + break; + case "5.4.3": + UpgradeToVersion543(); + break; + case "5.5.0": + UpgradeToVersion550(); + break; + case "5.6.0": + UpgradeToVersion560(); + break; + case "5.6.2": + UpgradeToVersion562(); + break; + case "6.0.0": + UpgradeToVersion600(); + break; + case "6.0.1": + UpgradeToVersion601(); + break; + case "6.0.2": + UpgradeToVersion602(); + break; + case "6.1.0": + UpgradeToVersion610(); + break; + case "6.1.2": + UpgradeToVersion612(); + break; + case "6.1.3": + UpgradeToVersion613(); + break; + case "6.2.0": + UpgradeToVersion620(); + break; + case "6.2.1": + UpgradeToVersion621(); + break; + case "6.2.3": + UpgradeToVersion623(); + break; + case "6.2.4": + UpgradeToVersion624(); + break; + case "7.0.0": + UpgradeToVersion700(); + break; + case "7.1.0": + UpgradeToVersion710(); + break; + case "7.1.1": + UpgradeToVersion711(); + break; + case "7.1.2": + UpgradeToVersion712(); + break; + case "7.2.0": + UpgradeToVersion720(); + break; + case "7.2.1": + UpgradeToVersion721(); + break; + case "7.2.2": + UpgradeToVersion722(); + break; + case "7.3.0": + UpgradeToVersion730(); + break; + case "7.3.2": + UpgradeToVersion732(); + break; + case "7.3.3": + UpgradeToVersion733(); + break; + case "7.4.0": + UpgradeToVersion740(); + break; + case "7.4.2": + UpgradeToVersion742(); + break; + case "9.1.0": + UpgradeToVersion910(); + break; + case "9.2.0": + UpgradeToVersion920(); + break; + case "9.2.1": + UpgradeToVersion921(); + break; + case "9.3.0": + UpgradeToVersion930(); + break; + case "9.4.1": + UpgradeToVersion941(); + break; + case "9.6.0": + UpgradeToVersion960(); + break; + } + } + else + { + // Incremental + switch (version.ToString(4)) { - Exceptions.Exceptions.LogException(ex); + case "8.0.0.6": + UpgradeToVersion8006(); + break; + case "8.0.0.7": + UpgradeToVersion8007(); + break; + case "8.0.0.13": + UpgradeToVersion80013(); + break; + case "8.0.0.16": + UpgradeToVersion80016(); + break; + case "8.0.0.26": + UpgradeToVersion80026(); + break; + case "8.0.0.27": + UpgradeToVersion80027(); + break; + } + } + } + catch (Exception ex) + { + Logger.Error(ex); + exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + + // log the results + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); + } + + try + { + using (StreamWriter streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Application.log.resources")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); } + } + catch (Exception exc) + { + Logger.Error(exc); + } + } + + if (writeFeedback) + { + HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); + } + + 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; + } + + public static string UpdateConfig(string providerPath, 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) + { + Logger.Error(ex); + exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + + // log the results + try + { + using (StreamWriter streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Config.log")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); + } + } + catch (Exception exc) + { + Logger.Error(exc); + } + } + 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; + } + + /// ----------------------------------------------------------------------------- + /// + /// UpgradeDNN manages the Upgrade of an exisiting DotNetNuke Application. + /// + /// + /// + /// The path to the Data Provider. + /// The current Database Version. + /// ----------------------------------------------------------------------------- + public static void UpgradeDNN(string providerPath, Version dataBaseVersion) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeDNN:" + Globals.FormatVersion(ApplicationVersion)); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Upgrading to Version: " + Globals.FormatVersion(ApplicationVersion) + "
    "); + + // Process the Upgrade Script files + var versions = new List(); + foreach (string scriptFile in GetUpgradeScripts(providerPath, dataBaseVersion)) + { + var version = new Version(GetFileNameWithoutExtension(scriptFile)); + bool scriptExecuted; + UpgradeVersion(scriptFile, true, out scriptExecuted); + if (scriptExecuted) + { + versions.Add(version); + } + } + + foreach (Version ver in versions) + { + // ' perform version specific application upgrades + UpgradeApplication(providerPath, ver, true); + } + + foreach (Version ver in versions) + { + // delete files which are no longer used + DeleteFiles(providerPath, ver, true); + } - XmlNode userTabNode = xmlDoc.SelectSingleNode("//portal/tabs/tab"); - if (userTabNode != null) - { - string tabName = XmlUtils.GetNodeValue(userTabNode.CreateNavigator(), "name"); + foreach (Version ver in versions) + { + // execute config file updates + UpdateConfig(providerPath, ver, true); + } - var userTab = TabController.Instance.GetTabByName(tabName, portal.PortalID) ?? TabController.DeserializeTab(userTabNode, null, portal.PortalID, PortalTemplateModuleAction.Merge); + DataProvider.Instance().SetCorePackageVersions(); - // Update SiteSettings to point to the new page - if (portal.UserTabId > Null.NullInteger) - { - portal.RegisterTabId = portal.UserTabId; - } - else - { - portal.UserTabId = userTab.TabID; - } - } + // perform general application upgrades + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Performing General Upgrades
    "); + DnnInstallLogger.InstallLogInfo(Localization.GetString("GeneralUpgrades", Localization.GlobalResourceFile)); + UpgradeApplication(); - PortalController.Instance.UpdatePortalInfo(portal); + DataCache.ClearHostCache(true); + } - // Add Users folder to every portal - string usersFolder = string.Format("{0}Users\\", portal.HomeDirectoryMapPath); + 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); + } - if (!Directory.Exists(usersFolder)) + public static string UpgradeIndicator(Version version, string packageType, string packageName, string culture, bool isLocal, bool isSecureConnection) + { + string url = string.Empty; + if (Host.CheckUpgrade && version != new Version(0, 0, 0)) + { + url = DotNetNukeContext.Current.Application.UpgradeUrl + "/update.aspx"; + + // use network path reference so it works in ssl-offload scenarios + url = url.Replace("http://", "//"); + url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); + url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); + url += "&type=" + packageType; + url += "&name=" + packageName; + if (packageType.ToLowerInvariant() == "module") + { + var moduleType = (from m in InstalledModulesController.GetInstalledModules() where m.ModuleName == packageName select m).SingleOrDefault(); + if (moduleType != null) { - // Create Users folder - Directory.CreateDirectory(usersFolder); + url += "&no=" + moduleType.Instances; + } + } - // Synchronize the Users folder to ensure the user folder is accessible - FolderManager.Instance.Synchronize(portal.PortalID, "Users/", false, true); + url += "&id=" + Host.GUID; + if (packageType.Equals(DotNetNukeContext.Current.Application.Type, StringComparison.OrdinalIgnoreCase)) + { + if (!string.IsNullOrEmpty(HostController.Instance.GetString("NewsletterSubscribeEmail"))) + { + url += "&email=" + HttpUtility.UrlEncode(HostController.Instance.GetString("NewsletterSubscribeEmail")); + } + + var portals = PortalController.Instance.GetPortals(); + url += "&no=" + portals.Count; + url += "&os=" + Globals.FormatVersion(Globals.OperatingSystemVersion, "00", 2, string.Empty); + url += "&net=" + Globals.FormatVersion(Globals.NETFrameworkVersion, "00", 2, string.Empty); + url += "&db=" + Globals.FormatVersion(Globals.DatabaseEngineVersion, "00", 2, string.Empty); + var source = Config.GetSetting("Source"); + if (!string.IsNullOrEmpty(source)) + { + url += "&src=" + source; } } - } - AddEventQueueApplicationStartFirstRequest(); + if (!string.IsNullOrEmpty(culture)) + { + url += "&culture=" + culture; + } + } - // Change Key for Module Defintions; - moduleDefId = GetModuleDefinition("Extensions", "Extensions"); - RemoveModuleControl(moduleDefId, "ImportModuleDefinition"); - AddModuleControl(moduleDefId, "EditModuleDefinition", "Edit Module Definition", "DesktopModules/Admin/Extensions/Editors/EditModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + return url; + } - // Module was incorrectly assigned as "IsPremium=False" - RemoveModuleFromPortals("Users And Roles"); + public static string UpgradeRedirect() + { + return UpgradeRedirect(ApplicationVersion, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty); } - private static void UpgradeToVersion540() + public static string UpgradeRedirect(Version version, string packageType, string packageName, string culture) { - var configDoc = Config.Load(); - var configNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/system.web.extensions"); - if (configNavigator == null) + string url; + if (!string.IsNullOrEmpty(Config.GetSetting("UpdateServiceRedirect"))) { - // attempt to remove "System.Web.Extensions" configuration section - string upgradeFile = string.Format("{0}\\Config\\SystemWebExtensions.config", Globals.InstallMapPath); - string message = UpdateConfig(upgradeFile, ApplicationVersion, "Remove System.Web.Extensions"); - EventLogController.Instance.AddLog( - "UpgradeConfig", - string.IsNullOrEmpty(message) - ? "Remove System Web Extensions" - : string.Format("Remove System Web Extensions failed. Error reported during attempt to update:{0}", message), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.HOST_ALERT); + url = Config.GetSetting("UpdateServiceRedirect"); } - - // Add Styles Skin Object - AddSkinControl("TAGS", "DotNetNuke.TagsSkinObject", "Admin/Skins/Tags.ascx"); - - // Add Content List module definition - int moduleDefId = AddModuleDefinition("ContentList", "This module displays a list of content by tag.", "Content List"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ContentList/ContentList.ascx", string.Empty, SecurityAccessLevel.View, 0); - - // Update registration page - ArrayList portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + else { - // objPortal.RegisterTabId = objPortal.UserTabId; - PortalController.Instance.UpdatePortalInfo(portal); - - // Add ContentList to Search Results Page - int tabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", Null.NullString); - TabInfo searchPage = TabController.Instance.GetTab(tabId, portal.PortalID, false); - AddModuleToPage(searchPage, moduleDefId, "Results", string.Empty); + url = DotNetNukeContext.Current.Application.UpgradeUrl + "/redirect.aspx"; + url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); + url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); + url += "&type=" + packageType; + url += "&name=" + packageName; + if (!string.IsNullOrEmpty(culture)) + { + url += "&culture=" + culture; + } } + + return url; } - private static void UpgradeToVersion543() + /// ----------------------------------------------------------------------------- + /// + /// UpgradeVersion upgrades a single version. + /// + /// + /// + /// The upgrade script file. + /// Write status to Response Stream?. + /// + /// ----------------------------------------------------------------------------- + public static string UpgradeVersion(string scriptFile, bool writeFeedback) { - // get log file path - string logFilePath = DataProvider.Instance().GetProviderPath(); - if (Directory.Exists(logFilePath)) + bool scriptExecuted; + return UpgradeVersion(scriptFile, writeFeedback, out scriptExecuted); + } + + /// ----------------------------------------------------------------------------- + /// + /// UpgradeVersion upgrades a single version. + /// + /// + /// + /// The upgrade script file. + /// Write status to Response Stream?. + /// Identity whether the script file executed. + /// + /// ----------------------------------------------------------------------------- + public static string UpgradeVersion(string scriptFile, bool writeFeedback, out bool scriptExecuted) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); + var version = new Version(GetFileNameWithoutExtension(scriptFile)); + string exceptions = Null.NullString; + scriptExecuted = false; + + // verify script has not already been run + if (!Globals.FindDatabaseVersion(version.Major, version.Minor, version.Build)) { - // get log files - foreach (string fileName in Directory.GetFiles(logFilePath, "*.log")) - { - if (File.Exists(fileName + ".resources")) - { - File.Delete(fileName + ".resources"); - } + // execute script file (and version upgrades) for version + exceptions = ExecuteScript(scriptFile, writeFeedback); + scriptExecuted = true; - // copy requires use of move - File.Move(fileName, fileName + ".resources"); + // update the version + Globals.UpdateDataBaseVersion(version); + + var log = new LogInfo + { + LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), + BypassBuffering = true, + }; + log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version)); + if (exceptions.Length > 0) + { + log.AddProperty("Warnings", exceptions); + } + else + { + log.AddProperty("No Warnings", string.Empty); } + + LogController.Instance.AddLog(log); } - } - private static void UpgradeToVersion550() - { - // update languages module - int moduleDefId = GetModuleDefinition("Languages", "Languages"); - AddModuleControl(moduleDefId, "TranslationStatus", string.Empty, "DesktopModules/Admin/Languages/TranslationStatus.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); + if (version.Revision > 0 && + version.Revision > Globals.GetLastAppliedIteration(version)) + { + // execute script file (and version upgrades) for version + exceptions = ExecuteScript(scriptFile, writeFeedback); + scriptExecuted = true; - // due to an error in 5.3.0 we need to recheck and readd Application_Start_FirstRequest - AddEventQueueApplicationStartFirstRequest(); + // update the increment + Globals.UpdateDataBaseVersionIncrement(version, version.Revision); - // check if UserProfile page template exists in Host folder and if not, copy it from Install folder - string installTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.InstallMapPath); - if (File.Exists(installTemplateFile)) - { - string hostTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.HostMapPath); - if (!File.Exists(hostTemplateFile)) + var log = new LogInfo { - File.Copy(installTemplateFile, hostTemplateFile); + LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), + BypassBuffering = true, + }; + log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version) + ", Iteration:" + version.Revision); + if (exceptions.Length > 0) + { + log.AddProperty("Warnings", exceptions); + } + else + { + log.AddProperty("No Warnings", string.Empty); } + + LogController.Instance.AddLog(log); + } + + if (string.IsNullOrEmpty(exceptions)) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); + } + else + { + DnnInstallLogger.InstallLogError(exceptions); } - // Fix the permission for User Folders - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + return exceptions; + } + + public static bool UpdateNewtonsoftVersion() + { + try { - foreach (FolderInfo folder in FolderManager.Instance.GetFolders(portal.PortalID)) + // check whether current binding already specific to correct version. + if (NewtonsoftNeedUpdate()) { - if (folder.FolderPath.StartsWith("Users/")) + lock (_threadLocker) { - foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) + if (NewtonsoftNeedUpdate()) { - if (permission.PermissionKey.Equals("READ", StringComparison.InvariantCultureIgnoreCase)) + var matchedFiles = Directory.GetFiles(Path.Combine(Globals.ApplicationMapPath, "Install\\Module"), "Newtonsoft.Json_*_Install.zip"); + if (matchedFiles.Length > 0) { - // Add All Users Read Access to the folder - int roleId = int.Parse(Globals.glbRoleAllUsers); - if (!folder.FolderPermissions.Contains(permission.PermissionKey, folder.FolderID, roleId, Null.NullInteger)) - { - var folderPermission = new FolderPermissionInfo(permission) { FolderID = folder.FolderID, UserID = Null.NullInteger, RoleID = roleId, AllowAccess = true }; - - folder.FolderPermissions.Add(folderPermission); - } + return InstallPackage(matchedFiles[0], "Library", false); } } - - FolderPermissionController.SaveFolderPermissions(folder); } } - - // Remove user page template from portal if it exists (from 5.3) - if (File.Exists(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath))) - { - File.Delete(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath)); - } } - - // DNN-12894 - Country Code for "United Kingdom" is incorrect - var listController = new ListController(); - var listItem = listController.GetListEntryInfo("Country", "UK"); - if (listItem != null) + catch (Exception ex) { - listItem.Value = "GB"; - listController.UpdateListEntry(listItem); + Logger.Error(ex); } - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + return false; + } + + public static string ActivateLicense() + { + var isLicensable = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")); + var activationResult = string.Empty; + + if (isLicensable) { - // fix issue where portal default language may be disabled - string defaultLanguage = portal.DefaultLanguage; - if (!IsLanguageEnabled(portal.PortalID, defaultLanguage)) - { - Locale language = LocaleController.Instance.GetLocale(defaultLanguage); - Localization.AddLanguageToPortal(portal.PortalID, language.LanguageId, true); - } + var sku = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")) ? "DNNENT" : "DNNPRO"; + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ActivatingLicense", Localization.GlobalResourceFile)); - // preemptively create any missing localization records rather than relying on dynamic creation - foreach (Locale locale in LocaleController.Instance.GetLocales(portal.PortalID).Values) + var installConfig = InstallController.Instance.GetInstallConfig(); + var licenseConfig = (installConfig != null) ? installConfig.License : null; + + if (licenseConfig != null) { - DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, locale.Code); + dynamic licenseActivation = Reflection.CreateObject(Reflection.CreateType("DotNetNuke.Professional.LicenseActivation.ViewLicx")); + licenseActivation.AutoActivation(licenseConfig.AccountEmail, licenseConfig.InvoiceNumber, licenseConfig.WebServer, licenseConfig.LicenseType, sku); + activationResult = licenseActivation.LicenseResult; + + // Log Event to Event Log + EventLogController.Instance.AddLog( + "License Activation", + "License Activated during install for: " + licenseConfig.AccountEmail + " | invoice: " + licenseConfig.InvoiceNumber, + EventLogController.EventLogType.HOST_ALERT); } } + + return activationResult; } - private static void UpgradeToVersion560() + public static bool RemoveInvalidAntiForgeryCookie() { - // Add .htmtemplate file extension - var toAdd = new List { ".htmtemplate" }; - HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); - - // Add new Xml Merge module - int moduleDefId = AddModuleDefinition("Configuration Manager", string.Empty, "Configuration Manager", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/XmlMerge/XmlMerge.ascx", "~/images/icon_configuration_32px.png", SecurityAccessLevel.Host, 0); - - // Add Module To Page - TabInfo hostPage = AddHostPage("Configuration Manager", "Modify configuration settings for your site", "~/images/icon_configuration_16px.png", "~/images/icon_configuration_32px.png", true); - AddModuleToPage(hostPage, moduleDefId, "Configuration Manager", "~/images/icon_configuration_32px.png"); + // DNN-9394: when upgrade from old version which use MVC version below than 5, it may saved antiforgery cookie + // with a different cookie name which join the root path even equals to "/", then it will cause API request failed. + // we need remove the cookie during upgrade process. + var appPath = HttpRuntime.AppDomainAppVirtualPath; + if (appPath == "/" && HttpContext.Current != null) + { + var cookieSuffix = Convert.ToBase64String(Encoding.UTF8.GetBytes(appPath)).Replace('+', '.').Replace('/', '-').Replace('=', '_'); + var cookieName = $"__RequestVerificationToken_{cookieSuffix}"; + var invalidCookie = HttpContext.Current.Request.Cookies[cookieName]; + if (invalidCookie != null) + { + invalidCookie.Expires = DateTime.Now.AddYears(-1); + HttpContext.Current.Response.Cookies.Add(invalidCookie); - // Update Google Analytics Script in SiteAnalysis.config - var googleAnalyticsController = new GoogleAnalyticsController(); - googleAnalyticsController.UpgradeModule("05.06.00"); + return true; + } + } - // Updated LanguageSettings.ascx control to be a Settings control - ModuleDefinitionInfo languageModule = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Languages"); - ModuleControlInfo moduleControl = ModuleControlController.GetModuleControlsByModuleDefinitionID(languageModule.ModuleDefID)["LanguageSettings"]; - moduleControl.ControlKey = "Settings"; - ModuleControlController.UpdateModuleControl(moduleControl); + return false; } - private static void UpgradeToVersion562() + /// ----------------------------------------------------------------------------- + /// + /// ExecuteScript executes a SQl script file. + /// + /// + /// + /// The script to Execute. + /// Need to output feedback message. + /// + /// ----------------------------------------------------------------------------- + internal static string ExecuteScript(string scriptFile, bool writeFeedback) { - // Add new Photo Profile field to Host - var listController = new ListController(); - Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); + 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)); + } - var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); - ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); + // read script file for installation + string script = FileSystemUtils.ReadFile(scriptFile); - HostController.Instance.Update("AutoAddPortalAlias", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); + // execute SQL installation script + string exceptions = DataProvider.Instance().ExecuteScript(script); - // remove the system message module from the admin tab - // System Messages are now managed through Localization - if (CoreModuleExists("System Messages")) + // add installer logging + if (string.IsNullOrEmpty(exceptions)) { - RemoveCoreModule("System Messages", "Admin", "Site Settings", false); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "ExecuteScript:" + scriptFile); } - - // remove portal alias module - if (CoreModuleExists("PortalAliases")) + else { - RemoveCoreModule("PortalAliases", "Admin", "Site Settings", false); + DnnInstallLogger.InstallLogError(exceptions); } - // add the log viewer module to the admin tab - int moduleDefId; - if (CoreModuleExists("LogViewer") == false) + // log the results + try { - moduleDefId = AddModuleDefinition("LogViewer", "Allows you to view log entries for site events.", "Log Viewer"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/LogViewer/LogViewer.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Log Settings", "DesktopModules/Admin/LogViewer/EditLogTypes.ascx", string.Empty, SecurityAccessLevel.Host, 0); - - // Add the Module/Page to all configured portals - AddAdminPages("Log Viewer", "View a historical log of database events such as event schedules, exceptions, account logins, module and page changes, user account activities, security role activities, etc.", "icon_viewstats_16px.gif", "icon_viewstats_32px.gif", true, moduleDefId, "Log Viewer", "icon_viewstats_16px.gif"); + using (var streamWriter = File.CreateText(scriptFile.Replace("." + DefaultProvider, string.Empty) + ".log.resources")) + { + streamWriter.WriteLine(exceptions); + streamWriter.Close(); + } } - - // add the schedule module to the host tab - TabInfo newPage; - if (CoreModuleExists("Scheduler") == false) + catch (Exception exc) { - moduleDefId = AddModuleDefinition("Scheduler", "Allows you to schedule tasks to be run at specified intervals.", "Scheduler"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Scheduler/ViewSchedule.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddModuleControl(moduleDefId, "Edit", "Edit Schedule", "DesktopModules/Admin/Scheduler/EditSchedule.ascx", string.Empty, SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "History", "Schedule History", "DesktopModules/Admin/Scheduler/ViewScheduleHistory.ascx", string.Empty, SecurityAccessLevel.Host, 0); - AddModuleControl(moduleDefId, "Status", "Schedule Status", "DesktopModules/Admin/Scheduler/ViewScheduleStatus.ascx", string.Empty, SecurityAccessLevel.Host, 0); - - // Create New Host Page (or get existing one) - newPage = AddHostPage("Schedule", "Add, modify and delete scheduled tasks to be run at specified intervals.", "icon_scheduler_16px.gif", "icon_scheduler_32px.gif", true); - - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, "Schedule", "icon_scheduler_16px.gif"); + // does not have permission to create the log file + Logger.Error(exc); } - // add the Search Admin module to the host tab - if (CoreModuleExists("SearchAdmin") == false) + if (writeFeedback) { - moduleDefId = AddModuleDefinition("SearchAdmin", "The Search Admininstrator provides the ability to manage search settings.", "Search Admin"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchAdmin/SearchAdmin.ascx", string.Empty, SecurityAccessLevel.Host, 0); + string resourcesFile = Path.GetFileName(scriptFile); + if (!string.IsNullOrEmpty(resourcesFile)) + { + HtmlUtils.WriteScriptSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions), resourcesFile.Replace("." + DefaultProvider, ".log.resources")); + } + } - // Create New Host Page (or get existing one) - newPage = AddHostPage("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "icon_search_16px.gif", "icon_search_32px.gif", true); + return exceptions; + } - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, "Search Admin", "icon_search_16px.gif"); - } + /// ----------------------------------------------------------------------------- + /// + /// 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"); - // add the Search Input module - if (CoreModuleExists("SearchInput") == false) + string exceptions = string.Empty; + + bool installMemberRole = true; + if (Config.GetSetting("InstallMemberRole") != null) { - moduleDefId = AddModuleDefinition("SearchInput", "The Search Input module provides the ability to submit a search to a given search results module.", "Search Input", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchInput/SearchInput.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Search Input Settings", "DesktopModules/Admin/SearchInput/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); + installMemberRole = bool.Parse(Config.GetSetting("InstallMemberRole")); } - // add the Search Results module - if (CoreModuleExists("SearchResults") == false) + if (installMemberRole) { - moduleDefId = AddModuleDefinition("SearchResults", "The Search Reasults module provides the ability to display search results.", "Search Results", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchResults/SearchResults.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); - AddModuleControl(moduleDefId, "Settings", "Search Results Settings", "DesktopModules/Admin/SearchResults/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); + if (writeFeedback) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing MemberRole Provider:
    "); + } - // Add the Search Module/Page to all configured portals - AddSearchResults(moduleDefId); + // 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); } - // add the site wizard module to the admin tab - if (CoreModuleExists("SiteWizard") == false) + if (string.IsNullOrEmpty(exceptions)) { - moduleDefId = AddModuleDefinition("SiteWizard", "The Administrator can use this user-friendly wizard to set up the common Extensions of the Portal/Site.", "Site Wizard"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SiteWizard/Sitewizard.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddAdminPages("Site Wizard", "Configure portal settings, page design and apply a site template using a step-by-step wizard.", "icon_wizard_16px.gif", "icon_wizard_32px.gif", true, moduleDefId, "Site Wizard", "icon_wizard_16px.gif"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "InstallMemberRoleProvider"); } - - // add Lists module and tab - if (HostTabExists("Lists") == false) + else { - moduleDefId = AddModuleDefinition("Lists", "Allows you to edit common lists.", "Lists"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Lists/ListEditor.ascx", string.Empty, SecurityAccessLevel.Host, 0); - - // Create New Host Page (or get existing one) - newPage = AddHostPage("Lists", "Manage common lists.", "icon_lists_16px.gif", "icon_lists_32px.gif", true); - - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, "Lists", "icon_lists_16px.gif"); + DnnInstallLogger.InstallLogError(exceptions); } - if (HostTabExists("Superuser Accounts") == false) - { - // add SuperUser Accounts module and tab - DesktopModuleInfo objDesktopModuleInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); - moduleDefId = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", objDesktopModuleInfo.DesktopModuleID).ModuleDefID; + return exceptions; + } - // Create New Host Page (or get existing one) - newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", "icon_users_16px.gif", "icon_users_32px.gif", true); + 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; + } - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "icon_users_32px.gif"); + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) + { + if (string.IsNullOrEmpty(currentCulture)) + { + currentCulture = Localization.SystemLocale; } - // Add Edit Role Groups - moduleDefId = GetModuleDefinition("Security", "Security Roles"); - AddModuleControl(moduleDefId, "EditGroup", "Edit Role Groups", "DesktopModules/Admin/Security/EditGroups.ascx", "icon_securityroles_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); - AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); - - // Add User Accounts Controls - moduleDefId = GetModuleDefinition("Security", "User Accounts"); - AddModuleControl(moduleDefId, "ManageProfile", "Manage Profile Definition", "DesktopModules/Admin/Security/ProfileDefinitions.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); - AddModuleControl(moduleDefId, "EditProfileProperty", "Edit Profile Property Definition", "DesktopModules/Admin/Security/EditProfileDefinition.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); - AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); - AddModuleControl(Null.NullInteger, "Profile", "Profile", "DesktopModules/Admin/Security/ManageUsers.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); - AddModuleControl(Null.NullInteger, "SendPassword", "Send Password", "DesktopModules/Admin/Security/SendPassword.ascx", string.Empty, SecurityAccessLevel.Anonymous, Null.NullInteger); - AddModuleControl(Null.NullInteger, "ViewProfile", "View Profile", "DesktopModules/Admin/Security/ViewProfile.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); + var templates = PortalController.Instance.GetAvailablePortalTemplates(); - // Update Child Portal subHost.aspx - UpdateChildPortalsDefaultPage(); + var defaultTemplates = + templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); - // add the solutions explorer module to the admin tab - if (CoreModuleExists("Solutions") == false) + var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); + if (match == null) { - moduleDefId = AddModuleDefinition("Solutions", "Browse additional solutions for your application.", "Solutions", false, false); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Solutions/Solutions.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddAdminPages("Solutions", "DotNetNuke Solutions Explorer page provides easy access to locate free and commercial DotNetNuke modules, skin and more.", "icon_solutions_16px.gif", "icon_solutions_32px.gif", true, moduleDefId, "Solutions Explorer", "icon_solutions_32px.gif"); + match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); } - // Add Search Skin Object - AddSkinControl("SEARCH", "DotNetNuke.SearchSkinObject", "Admin/Skins/Search.ascx"); - - // Add TreeView Skin Object - AddSkinControl("TREEVIEW", "DotNetNuke.TreeViewSkinObject", "Admin/Skins/TreeViewMenu.ascx"); + if (match == null) + { + match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); + } - // Add Text Skin Object - AddSkinControl("TEXT", "DotNetNuke.TextSkinObject", "Admin/Skins/Text.ascx"); + if (match == null) + { + throw new Exception("Unable to locate specified portal template: " + templateFileName); + } - // Add Styles Skin Object - AddSkinControl("STYLES", "DotNetNuke.StylesSkinObject", "Admin/Skins/Styles.ascx"); + return match; } - private static void UpgradeToVersion600() + internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) { - var hostPages = TabController.Instance.GetTabsByPortal(Null.NullInteger); + // Load Template + var installTemplate = new XmlDocument { XmlResolver = null }; + Upgrade.GetInstallTemplate(installTemplate); - // This ensures that all host pages have a tab path. - // so they can be found later. (DNNPRO-17129) - foreach (var hostPage in hostPages.Values) + // Parse the root node + XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); + string currentCulture = string.Empty; + if (rootNode != null) { - hostPage.TabPath = Globals.GenerateTabPath(hostPage.ParentId, hostPage.TabName); - TabController.Instance.UpdateTab(hostPage); + currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); } - var settings = PortalController.Instance.GetCurrentPortalSettings(); - - if (settings != null) + if (string.IsNullOrEmpty(currentCulture)) { - var hostTab = TabController.Instance.GetTab(settings.SuperTabId, Null.NullInteger, false); - hostTab.IsVisible = false; - TabController.Instance.UpdateTab(hostTab); - foreach (var module in ModuleController.Instance.GetTabModules(settings.SuperTabId).Values) - { - ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "hideadminborder", "true"); - } + currentCulture = Localization.SystemLocale; } - // remove timezone editor - int moduleDefId = GetModuleDefinition("Languages", "Languages"); - RemoveModuleControl(moduleDefId, "TimeZone"); + currentCulture = currentCulture.ToLowerInvariant(); - // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Host - ProfilePropertyDefinition ppdHostTimeZone = ProfileController.GetPropertyDefinitionByName(Null.NullInteger, "TimeZone"); - if (ppdHostTimeZone != null) - { - ProfileController.DeletePropertyDefinition(ppdHostTimeZone); - } + return FindBestTemplate(templateFileName, currentCulture); + } - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - // update timezoneinfo -#pragma warning disable 612,618 - TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(portal.TimeZoneOffset); -#pragma warning restore 612,618 - PortalController.UpdatePortalSetting(portal.PortalID, "TimeZone", timeZoneInfo.Id, false); + internal static string GetFileNameWithoutExtension(string scriptFile) + { + return Path.GetFileNameWithoutExtension(scriptFile); + } - // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Portals - ProfilePropertyDefinition ppdTimeZone = ProfileController.GetPropertyDefinitionByName(portal.PortalID, "TimeZone"); - if (ppdTimeZone != null) + internal static void CheckFipsCompilanceAssemblies() + { + var currentVersion = Globals.FormatVersion(DotNetNukeContext.Current.Application.Version); + if (CryptoConfig.AllowOnlyFipsAlgorithms && HostController.Instance.GetString(FipsCompilanceAssembliesCheckedKey) != currentVersion) + { + var assemblyFolder = Path.Combine(Globals.ApplicationMapPath, FipsCompilanceAssembliesFolder); + var assemblyFiles = Directory.GetFiles(assemblyFolder, "*.dll", SearchOption.TopDirectoryOnly); + foreach (var assemblyFile in assemblyFiles) { - ProfileController.DeletePropertyDefinition(ppdTimeZone); + FixFipsCompilanceAssembly(assemblyFile); } - var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); - - adminTab.IsVisible = false; - TabController.Instance.UpdateTab(adminTab); + HostController.Instance.Update(FipsCompilanceAssembliesCheckedKey, currentVersion); - foreach (var module in ModuleController.Instance.GetTabModules(portal.AdminTabId).Values) + if (HttpContext.Current != null) { - ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "hideadminborder", "true"); + Globals.Redirect(HttpContext.Current.Request.RawUrl, true); } } + } - // Ensure that Display Beta Notice setting is present - var displayBetaNotice = Host.DisplayBetaNotice; - HostController.Instance.Update("DisplayBetaNotice", displayBetaNotice ? "Y" : "N"); - - moduleDefId = GetModuleDefinition("Languages", "Languages"); - AddModuleControl(moduleDefId, "EnableContent", "Enable Localized Content", "DesktopModules/Admin/Languages/EnableLocalizedContent.ascx", string.Empty, SecurityAccessLevel.Host, 0, null, false); - - AddDefaultModuleIcons(); - - AddIconToAllowedFiles(); - - FavIconsToPortalSettings(); + protected static bool IsLanguageEnabled(int portalid, string code) + { + Locale enabledLanguage; + return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); + } - var tab = TabController.Instance.GetTabByName("Host", Null.NullInteger, Null.NullInteger); + /// ----------------------------------------------------------------------------- + /// + /// AddAdminPages adds an Admin Page and an associated Module to all configured Portals. + /// + /// The Name to give this new Tab. + /// Description. + /// The Icon for this new Tab. + /// The large 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. + /// ----------------------------------------------------------------------------- + private static void AddAdminPages(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, int moduleDefId, string moduleTitle, string moduleIconFile) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminPages:" + tabName); - if (tab != null) - { - RemoveModule("Extensions", "Module Definitions", tab.TabID, true); - RemoveModule("Marketplace", "Marketplace", tab.TabID, true); - } + // Call overload with InheritPermisions=True + AddAdminPages(tabName, description, tabIconFile, tabIconFileLarge, isVisible, moduleDefId, moduleTitle, moduleIconFile, true); } - private static void UpgradeToVersion601() + private static void AddAdminRoleToPage(string tabPath) { - // List module needs to be available to Portals also - var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Lists"); - if (pkg != null) - { - // List package is no longer a system package - pkg.IsSystemPackage = false; - PackageController.Instance.SaveExtensionPackage(pkg); - - // List desktop module is no longer premium or admin module - var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(pkg.PackageID); - desktopModule.IsAdmin = false; - desktopModule.IsPremium = false; - DesktopModuleController.SaveDesktopModule(desktopModule, false, true); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddAdminRoleToPage:" + tabPath); - var permissionController = new PermissionController(); - ArrayList permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_DESKTOPMODULE", "DEPLOY"); - if (permissions.Count == 1) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); + if (tabID != Null.NullInteger) { - var permission = permissions[0] as PermissionInfo; - if (permission != null) - { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - // ensure desktop module is not present in the portal - var pdmi = DesktopModuleController.GetPortalDesktopModule(portal.PortalID, desktopModule.DesktopModuleID); - if (pdmi == null) - { - // Parse the permissions - var deployPermissions = new DesktopModulePermissionCollection(); - var deployPermission = new DesktopModulePermissionInfo { PermissionID = permission.PermissionID, AllowAccess = true, RoleID = portal.AdministratorRoleId }; - deployPermissions.Add(deployPermission); + TabInfo tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); - // Add Portal/Module to PortalDesktopModules - DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, true); - } - } + if (tab.TabPermissions.Count == 0) + { + AddPagePermission(tab.TabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); + AddPagePermission(tab.TabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); + TabPermissionController.SaveTabPermissions(tab); } } } } - private static void UpgradeToVersion602() + private static void AddConsoleModuleSettings(int moduleID) { - // Add avi,mpg,mpeg,mp3,wmv,mov,wav extensions - var exts = new List { ".avi", ".mpg", ".mpeg", ".mp3", ".wmv", ".mov", ".wav" }; - HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(exts)); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddConsoleModuleSettings:" + moduleID); - // Fix the icons for SiteMap page - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - var siteMap = TabController.Instance.GetTabByName("Search Engine SiteMap", portal.PortalID); + ModuleController.Instance.UpdateModuleSetting(moduleID, "DefaultSize", "IconFileLarge"); + ModuleController.Instance.UpdateModuleSetting(moduleID, "AllowSizeChange", "False"); + ModuleController.Instance.UpdateModuleSetting(moduleID, "DefaultView", "Hide"); + ModuleController.Instance.UpdateModuleSetting(moduleID, "AllowViewChange", "False"); + ModuleController.Instance.UpdateModuleSetting(moduleID, "ShowTooltip", "True"); + } - if (siteMap != null) + private static void AddEventQueueApplicationStartFirstRequest() + { + // Add new EventQueue Event + var config = EventQueueConfiguration.GetConfig(); + if (config != null) + { + if (!config.PublishedEvents.ContainsKey("Application_Start_FirstRequest")) { - siteMap.IconFile = "~/Icons/Sigma/Sitemap_16X16_Standard.png"; - siteMap.IconFileLarge = "~/Icons/Sigma/Sitemap_32X32_Standard.png"; - TabController.Instance.UpdateTab(siteMap); + foreach (SubscriberInfo subscriber in config.EventQueueSubscribers.Values) + { + EventQueueConfiguration.RegisterEventSubscription(config, "Application_Start_FirstRequest", subscriber); + } + + EventQueueConfiguration.SaveConfig(config, string.Format("{0}EventQueue\\EventQueue.config", Globals.HostMapPath)); } } } - private static void UpgradeToVersion610() + /// ----------------------------------------------------------------------------- + /// + /// AddModuleControl adds a new Module Control to the system. + /// + /// + /// + /// The Module Definition Id. + /// The key for this control in the Definition. + /// The title of this control. + /// Te source of ths control. + /// The icon file. + /// The type of control. + /// The vieworder for this module. + /// The Help Url. + /// ----------------------------------------------------------------------------- + private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL) { - AddModuleCategories(); - - // update languages module - int moduleDefId = GetModuleDefinition("Languages", "Languages"); - AddModuleControl(moduleDefId, "LocalizePages", "Localize Pages", "DesktopModules/Admin/Languages/LocalizePages.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0, Null.NullString, true); - - // add store control - moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); - AddModuleControl(moduleDefId, "Store", "Store Details", "DesktopModules/Admin/Extensions/Store.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - - EnableModalPopUps(); + AddModuleControl(moduleDefId, controlKey, controlTitle, controlSrc, iconFile, controlType, viewOrder, helpURL, false); + } - var tab = TabController.Instance.GetTabByName("Portals", Null.NullInteger); - tab.TabName = "Site Management"; - TabController.Instance.UpdateTab(tab); + private static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder, string helpURL, bool supportsPartialRendering) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleControl:" + moduleDefId); - foreach (var module in ModuleController.Instance.GetTabModules(tab.TabID).Values) + // check if module control exists + var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); + if (moduleControl == null) { - if (module.ModuleTitle == "Portals") + moduleControl = new ModuleControlInfo { - module.ModuleTitle = "Site Management"; - ModuleController.Instance.UpdateModule(module); - } - } - - // Add List module to Admin page of every portal - ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Lists"); - if (mDef != null) - { - AddAdminPages( - "Lists", - "Manage common lists", - "~/Icons/Sigma/Lists_16X16_Standard.png", - "~/Icons/Sigma/Lists_32X32_Standard.png", - true, - mDef.ModuleDefID, - "Lists", - "~/Icons/Sigma/Lists_16X16_Standard.png", - true); - } + ModuleControlID = Null.NullInteger, + ModuleDefID = moduleDefId, + ControlKey = controlKey, + ControlTitle = controlTitle, + ControlSrc = controlSrc, + ControlType = controlType, + ViewOrder = viewOrder, + IconFile = iconFile, + HelpURL = helpURL, + SupportsPartialRendering = supportsPartialRendering, + }; - // update DotNetNuke.Portals' friend name to 'Sites'. - var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); - if (portalPackage != null) - { - portalPackage.FriendlyName = "Sites"; - PackageController.Instance.SaveExtensionPackage(portalPackage); + ModuleControlController.AddModuleControl(moduleControl); } + } - // add mobile preview control - AddModuleControl(Null.NullInteger, "MobilePreview", "Mobile Preview", "DesktopModules/Admin/MobilePreview/Preview.ascx", string.Empty, SecurityAccessLevel.Admin, Null.NullInteger); + /// ----------------------------------------------------------------------------- + /// + /// AddModuleDefinition adds a new Core Module Definition to the system. + /// + /// + /// This overload allows the caller to determine whether the module has a controller + /// class. + /// + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. + /// A flag representing whether the module is a Premium module. + /// A flag representing whether the module is an Admin module. + /// The Module Definition Id of the new Module. + /// ----------------------------------------------------------------------------- + private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, bool premium, bool admin) + { + return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, string.Empty, false, premium, admin); } - private static void UpgradeToVersion612() + /// ----------------------------------------------------------------------------- + /// + /// AddModuleDefinition adds a new Core Module Definition to the system. + /// + /// + /// This overload allows the caller to determine whether the module has a controller + /// class. + /// + /// The Friendly Name of the Module to Add. + /// Description of the Module. + /// The Module Definition Name. + /// Business Control Class. + /// Whether the module is enable for portals. + /// A flag representing whether the module is a Premium module. + /// A flag representing whether the module is an Admin module. + /// The Module Definition Id of the new Module. + /// ----------------------------------------------------------------------------- + private static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName, string businessControllerClass, bool isPortable, bool premium, bool admin) { - // update DotNetNuke.Portals' friend name to 'Sites'. - var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); - if (portalPackage != null) - { - portalPackage.FriendlyName = "Site Management"; - portalPackage.Description = - "The Super User can manage the various parent and child sites within the install instance. This module allows you to add a new site, modify an existing site, and delete a site."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleDefinition:" + desktopModuleName); - // update 'Portal' to 'Sites' in package description. - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Tabs"); - if (portalPackage != null) + // check if desktop module exists + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); + if (desktopModule == null) { - portalPackage.Description = - "Administrators can manage the Pages within the site. This module allows you to create a new page, modify an existing page, delete pages, change the page order, and change the hierarchical page level."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + var package = new PackageInfo + { + Description = description, + FriendlyName = desktopModuleName, + Name = string.Concat("DotNetNuke.", desktopModuleName), + PackageType = "Module", + Owner = "DNN", + Organization = ".NET Foundation", + Url = "https://dnncommunity.org", + Email = "info@dnncommunity.org", + }; + if (desktopModuleName == "Extensions" || desktopModuleName == "Skin Designer") + { + package.IsSystemPackage = true; + } - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Vendors"); - if (portalPackage != null) - { - portalPackage.Description = - "Administrators can manage the Vendors and Banners associated to the site. This module allows you to add a new vendor, modify an existing vendor, and delete a vendor."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + package.Version = new Version(1, 0, 0); - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteLog"); - if (portalPackage != null) - { - portalPackage.Description = - "Administrators can view the details of visitors using their site. There are a variety of reports available to display information regarding site usage, membership, and volumes."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + PackageController.Instance.SaveExtensionPackage(package); - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteWizard"); - if (portalPackage != null) - { - portalPackage.Description = - "The Administrator can use this user-friendly wizard to set up the common features of the site."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + string moduleName = desktopModuleName.Replace(" ", string.Empty); + desktopModule = new DesktopModuleInfo + { + DesktopModuleID = Null.NullInteger, + PackageID = package.PackageID, + FriendlyName = desktopModuleName, + FolderName = "Admin/" + moduleName, + ModuleName = moduleName, + Description = description, + Version = "01.00.00", + BusinessControllerClass = businessControllerClass, + IsPortable = isPortable, + SupportedFeatures = 0, + }; + if (isPortable) + { + desktopModule.SupportedFeatures = 1; + } - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Security"); - if (portalPackage != null) - { - portalPackage.Description = - "Administrators can manage the security roles defined for their site. The module allows you to add new security roles, modify existing security roles, delete security roles, and manage the users assigned to security roles."; - PackageController.Instance.SaveExtensionPackage(portalPackage); - } + desktopModule.IsPremium = premium; + desktopModule.IsAdmin = admin; - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.LogViewer"); - if (portalPackage != null) + desktopModule.DesktopModuleID = DesktopModuleController.SaveDesktopModule(desktopModule, false, false); + + if (!premium) + { + DesktopModuleController.AddDesktopModuleToPortals(desktopModule.DesktopModuleID); + } + } + + // check if module definition exists + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(moduleDefinitionName, desktopModule.DesktopModuleID); + if (moduleDefinition == null) { - portalPackage.Description = - "Allows you to view log entries for site events."; - PackageController.Instance.SaveExtensionPackage(portalPackage); + moduleDefinition = new ModuleDefinitionInfo { ModuleDefID = Null.NullInteger, DesktopModuleID = desktopModule.DesktopModuleID, FriendlyName = moduleDefinitionName }; + + moduleDefinition.ModuleDefID = ModuleDefinitionController.SaveModuleDefinition(moduleDefinition, false, false); } - portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Google Analytics"); - if (portalPackage != null) + return moduleDefinition.ModuleDefID; + } + + /// ----------------------------------------------------------------------------- + /// + /// AddModuleToPage adds a module to a Page. + /// + /// + /// This overload assumes ModulePermissions will be inherited. + /// + /// The Page to add the Module to. + /// The Module Deinition Id for the module to be aded to this tab. + /// The Module's title. + /// The Module's icon. + /// ----------------------------------------------------------------------------- + private static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile) + { + // Call overload with InheritPermisions=True + return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, true); + } + + /// ----------------------------------------------------------------------------- + /// + /// AddPage adds a Tab Page. + /// + /// + /// Adds a Tab to a parentTab. + /// + /// The Parent Tab. + /// The Name to give this new Tab. + /// Description. + /// The Icon for this new Tab. + /// The Large Icon for this new Tab. + /// A flag indicating whether the tab is visible. + /// Page Permissions Collection for this page. + /// Is an admin page. + /// ----------------------------------------------------------------------------- + private static TabInfo AddPage(TabInfo parentTab, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) + { + int parentId = Null.NullInteger; + int portalId = Null.NullInteger; + + if (parentTab != null) { - portalPackage.Description = - "Configure Site Google Analytics settings."; - PackageController.Instance.SaveExtensionPackage(portalPackage); + parentId = parentTab.TabID; + portalId = parentTab.PortalID; } + + return AddPage(portalId, parentId, tabName, description, tabIconFile, tabIconFileLarge, isVisible, permissions, isAdmin); } - private static void UpgradeToVersion613() + /// ----------------------------------------------------------------------------- + /// + /// AddPage adds a Tab Page. + /// + /// The Id of the Portal. + /// The Id of the Parent Tab. + /// The Name to give this new Tab. + /// Description. + /// The Icon for this new Tab. + /// The large Icon for this new Tab. + /// A flag indicating whether the tab is visible. + /// Page Permissions Collection for this page. + /// Is and admin page. + /// ----------------------------------------------------------------------------- + private static TabInfo AddPage(int portalId, int parentId, string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible, TabPermissionCollection permissions, bool isAdmin) { - // Rename admin pages page's title to 'Page Management'. - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPage:" + tabName); + + TabInfo tab = TabController.Instance.GetTabByName(tabName, portalId, parentId); + + if (tab == null || tab.ParentId != parentId) { - var pagesTabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin//Pages", Null.NullString); + tab = new TabInfo + { + TabID = Null.NullInteger, + PortalID = portalId, + TabName = tabName, + Title = string.Empty, + Description = description, + KeyWords = string.Empty, + IsVisible = isVisible, + DisableLink = false, + ParentId = parentId, + IconFile = tabIconFile, + IconFileLarge = tabIconFileLarge, + IsDeleted = false, + }; + tab.TabID = TabController.Instance.AddTab(tab, !isAdmin); - if (pagesTabId != Null.NullInteger) + if (permissions != null) { - var pagesTab = TabController.Instance.GetTab(pagesTabId, portal.PortalID, false); - if (pagesTab != null && pagesTab.Title == "Pages") + foreach (TabPermissionInfo tabPermission in permissions) { - pagesTab.Title = "Page Management"; - TabController.Instance.UpdateTab(pagesTab); + tab.TabPermissions.Add(tabPermission, true); } + + TabPermissionController.SaveTabPermissions(tab); } } + + return tab; } - private static void UpgradeToVersion620() + /// ----------------------------------------------------------------------------- + /// + /// AddPagePermission adds a TabPermission to a TabPermission Collection. + /// + /// Page Permissions Collection for this page. + /// The Permission key. + /// The role given the permission. + /// ----------------------------------------------------------------------------- + private static void AddPagePermission(TabPermissionCollection permissions, string key, int roleId) { - // add host (system) profanityfilter list - const string listName = "ProfanityFilter"; - var listController = new ListController(); - var entry = new ListEntryInfo(); - { - entry.DefinitionID = Null.NullInteger; - entry.PortalID = Null.NullInteger; - entry.ListName = listName; - entry.Value = "ReplaceWithNothing"; - entry.Text = "FindThisText"; - entry.SystemList = true; - } - - listController.AddListEntry(entry); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPagePermission:" + key); + var permissionController = new PermissionController(); + var permission = (PermissionInfo)permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", key)[0]; - // add same list to each portal - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - entry.PortalID = portal.PortalID; - entry.SystemList = false; - entry.ListName = listName + "-" + portal.PortalID; - listController.AddListEntry(entry); + var tabPermission = new TabPermissionInfo { PermissionID = permission.PermissionID, RoleID = roleId, AllowAccess = true }; - // also create default social relationship entries for the portal - RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portal.PortalID); - } + permissions.Add(tabPermission); + } - // Convert old Messages to new schema - ConvertOldMessages(); + /// ----------------------------------------------------------------------------- + /// + /// AddSearchResults adds a top level Hidden Search Results Page. + /// + /// The Module Deinition Id for the Search Results Module. + /// ----------------------------------------------------------------------------- + private static void AddSearchResults(int moduleDefId) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSearchResults:" + moduleDefId); + var portals = PortalController.Instance.GetPortals(); + int intPortal; - // Replace old Messaging module on User Profile with new - ReplaceMessagingModule(); + // Add Page to Admin Menu of all configured Portals + for (intPortal = 0; intPortal <= portals.Count - 1; intPortal++) + { + var tabPermissions = new TabPermissionCollection(); - // Move Photo Property to the end of the propert list. - MovePhotoProperty(); + var portal = (PortalInfo)portals[intPortal]; - // Update Child Portal's Default Page - UpdateChildPortalsDefaultPage(); + AddPagePermission(tabPermissions, "View", Convert.ToInt32(Globals.glbRoleAllUsers)); + AddPagePermission(tabPermissions, "View", Convert.ToInt32(portal.AdministratorRoleId)); + AddPagePermission(tabPermissions, "Edit", Convert.ToInt32(portal.AdministratorRoleId)); - // Add core notification types - AddCoreNotificationTypesFor620(); + // Create New Page (or get existing one) + var tab = AddPage(portal.PortalID, Null.NullInteger, "Search Results", string.Empty, string.Empty, string.Empty, false, tabPermissions, false); - // Console module should not be IPortable - var consoleModule = DesktopModuleController.GetDesktopModuleByModuleName("Console", Null.NullInteger); - consoleModule.SupportedFeatures = 0; - consoleModule.BusinessControllerClass = string.Empty; - DesktopModuleController.SaveDesktopModule(consoleModule, false, false); + // Add Module To Page + AddModuleToPage(tab, moduleDefId, "Search Results", string.Empty); + } } - private static void UpgradeToVersion621() + /// ----------------------------------------------------------------------------- + /// + /// AddSkinControl adds a new Module Control to the system. + /// + /// + /// + /// The key for this control in the Definition. + /// Package Name. + /// Te source of ths control. + /// ----------------------------------------------------------------------------- + private static void AddSkinControl(string controlKey, string packageName, string controlSrc) { - // update administrators' role description. - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddSkinControl:" + controlKey); + + // check if skin control exists + SkinControlInfo skinControl = SkinControlController.GetSkinControlByKey(controlKey); + if (skinControl == null) { - // update about me's template - var myProfileTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed//MyProfile", string.Empty); - if (myProfileTabId != Null.NullInteger) - { - var tabModules = ModuleController.Instance.GetTabModules(myProfileTabId); - foreach (var module in tabModules.Values) - { - var settings = module.TabModuleSettings; - if (settings.ContainsKey("ProfileTemplate") && settings["ProfileTemplate"].ToString().Contains("
    ")) - { - var template = @"
    -

    - -

    -
    -
    -

    - -

    0"">
    - 0"">
    - 0"">
    - -

    -
    -
    -

    - -
      -
    • 0"">:
    • -
    • 0"">:
    • -
    • 0"">:
    • -
    • 0"">:
    • -
    -
    -
    "; - ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "ProfileTemplate", template); - } - } - } + var package = new PackageInfo { Name = packageName, FriendlyName = string.Concat(controlKey, "SkinObject"), PackageType = "SkinObject", Version = new Version(1, 0, 0) }; + LegacyUtil.ParsePackageName(package); + + PackageController.Instance.SaveExtensionPackage(package); + + skinControl = new SkinControlInfo { PackageID = package.PackageID, ControlKey = controlKey, ControlSrc = controlSrc, SupportsPartialRendering = false }; + + SkinControlController.SaveSkinControl(skinControl); } } - private static void UpgradeToVersion623() + private static void AddDefaultModuleIcons() { -#pragma warning disable 618 - if (Host.jQueryUrl == "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js") + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddDefaultModuleIcons"); + var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Google Analytics"); + if (pkg != null) { - HostController.Instance.Update("jQueryUrl", jQuery.DefaultHostedUrl); + pkg.FolderName = "DesktopModules/Admin/Analytics"; + pkg.IconFile = "~/DesktopModules/Admin/Analytics/analytics.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - if (Host.jQueryUIUrl == "http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js") + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Configuration Manager"); + if (pkg != null) { - HostController.Instance.Update("jQueryUIUrl", jQuery.DefaultUIHostedUrl); + pkg.FolderName = "DesktopModules/Admin/XmlMerge"; + pkg.IconFile = "~/DesktopModules/Admin/XmlMerge/xmlMerge.png"; + PackageController.Instance.SaveExtensionPackage(pkg); } -#pragma warning restore 618 - } - - private static void UpgradeToVersion624() - { - UninstallPackage("DotNetNuke.MarketPlace", "Module"); - } - private static void UpgradeToVersion700() - { - // add the site Advanced Settings module to the admin tab - if (CoreModuleExists("AdvancedSettings") == false) + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Console"); + if (pkg != null) { - var moduleDefId = AddModuleDefinition("AdvancedSettings", string.Empty, "Advanced Settings"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/AdvancedSettings/AdvancedSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - AddAdminPages( - "Advanced Settings", - string.Empty, - "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png", - "~/Icons/Sigma/AdvancedSettings_32X32_Standard.png", - true, - moduleDefId, - "Advanced Settings", - "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png"); + pkg.FolderName = "DesktopModules/Admin/Console"; + pkg.IconFile = "~/DesktopModules/Admin/Console/console.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - ConvertCoreNotificationTypeActionsFor700(); - - // Remove Feed Explorer module - DesktopModuleController.DeleteDesktopModule("FeedExplorer"); - DesktopModuleController.DeleteDesktopModule("Solutions"); - - // Register Newtonsoft assembly - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Newtonsoft.Json.dll", "4.5.6"); - - // subhost.aspx was updated - UpdateChildPortalsDefaultPage(); - } - - private static void UpgradeToVersion710() - { - // create a placeholder entry - uses the most common 5 character password (seed list is 6 characters and above) - const string listName = "BannedPasswords"; - var listController = new ListController(); - var entry = new ListEntryInfo(); + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ContentList"); + if (pkg != null) { - entry.DefinitionID = Null.NullInteger; - entry.PortalID = Null.NullInteger; - entry.ListName = listName; - entry.Value = "12345"; - entry.Text = "Placeholder"; - entry.SystemList = false; + pkg.FolderName = "DesktopModules/Admin/ContentList"; + pkg.IconFile = "~/DesktopModules/Admin/ContentList/contentList.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - // add list to each portal and update primary alias - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Dashboard"); + if (pkg != null) { - entry.PortalID = portal.PortalID; - entry.SystemList = false; - entry.ListName = listName + "-" + portal.PortalID; - listController.AddListEntry(entry); - - var defaultAlias = PortalController.GetPortalSetting("DefaultPortalAlias", portal.PortalID, string.Empty); - if (!string.IsNullOrEmpty(defaultAlias)) - { - foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Where(alias => alias.HTTPAlias == defaultAlias)) - { - alias.IsPrimary = true; - PortalAliasController.Instance.UpdatePortalAlias(alias); - } - } + pkg.FolderName = "DesktopModules/Admin/Dashboard"; + pkg.IconFile = "~/DesktopModules/Admin/Dashboard/dashboard.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - // Add File Content Type - var typeController = new ContentTypeController(); - var contentTypeFile = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - - if (contentTypeFile == null) + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Languages"); + if (pkg != null) { - typeController.AddContentType(new ContentType { ContentType = "File" }); + pkg.FolderName = "DesktopModules/Admin/Languages"; + pkg.IconFile = "~/DesktopModules/Admin/Languages/languages.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - - // only perform following for an existing installation upgrading - if (Globals.Status == Globals.UpgradeStatus.Upgrade) + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Marketplace"); + if (pkg != null) { - UpdateFoldersForParentId(); - ImportDocumentLibraryCategories(); - ImportDocumentLibraryCategoryAssoc(fileContentType); + pkg.FolderName = "DesktopModules/Admin/Marketplace"; + pkg.IconFile = "~/DesktopModules/Admin/Marketplace/marketplace.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } - // Add 404 Log - var logTypeInfo = new LogTypeInfo + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Sitemap"); + if (pkg != null) { - 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); + pkg.FolderName = "DesktopModules/Admin/Sitemap"; + pkg.IconFile = "~/DesktopModules/Admin/Sitemap/sitemap.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); + } - // Add LogType - var logTypeConf = new LogTypeConfigInfo + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Skin Designer"); + if (pkg != null) { - 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); - - UninstallPackage("DotNetNuke.SearchInput", "Module"); - - // enable password strength meter for new installs only - HostController.Instance.Update("EnableStrengthMeter", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); + pkg.FolderName = "DesktopModules/Admin/SkinDesigner"; + pkg.IconFile = "~/DesktopModules/Admin/SkinDesigner/skinDesigner.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); + } - // Add IP filter log type - var logTypeFilterInfo = new LogTypeInfo + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Skins"); + if (pkg != null) { - LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), - LogTypeFriendlyName = "HTTP Error Code 403.6 forbidden ip address rejected", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - }; - LogController.Instance.AddLogType(logTypeFilterInfo); + pkg.FolderName = "DesktopModules/Admin/Skins"; + pkg.IconFile = "~/DesktopModules/Admin/Skins/skins.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); + } - // Add LogType - var logTypeFilterConf = new LogTypeConfigInfo + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ViewProfile"); + if (pkg != null) { - 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); + pkg.FolderName = "DesktopModules/Admin/ViewProfile"; + pkg.IconFile = "~/DesktopModules/Admin/ViewProfile/viewProfile.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); + } - int tabID = TabController.GetTabByTabPath(Null.NullInteger, "//Host//SearchAdmin", Null.NullString); - if (tabID > Null.NullInteger) + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.ProfessionalPreview"); + if (pkg != null) { - TabController.Instance.DeleteTab(tabID, Null.NullInteger); + pkg.FolderName = "DesktopModules/Admin/ProfessionalPreview"; + pkg.IconFile = "~/DesktopModules/Admin/ProfessionalPreview/professionalPreview.gif"; + PackageController.Instance.SaveExtensionPackage(pkg); } + } - var modDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Search Admin"); + private static void AddModuleCategories() + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleCategories"); + DesktopModuleController.AddModuleCategory("< None >"); + DesktopModuleController.AddModuleCategory("Admin"); + DesktopModuleController.AddModuleCategory("Common"); - if (modDef != null) + foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) { - AddAdminPages("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "~/Icons/Sigma/Search_16x16_Standard.png", "~/Icons/Sigma/Search_32x32_Standard.png", true, modDef.ModuleDefID, "Search Admin", string.Empty); - } + bool update = false; + switch (desktopModuleInfo.Value.ModuleName) + { + case "Portals": + case "SQL": + case "HostSettings": + case "Scheduler": + case "SearchAdmin": + case "Lists": + case "Extensions": + case "WhatsNew": + case "Dashboard": + case "Marketplace": + case "ConfigurationManager": + case "Security": + case "Tabs": + case "Vendors": + case "Banners": + case "FileManager": + case "SiteLog": + case "Newsletters": + case "RecycleBin": + case "LogViewer": + case "SiteWizard": + case "Languages": + case "Skins": + case "SkinDesigner": + case "GoogleAnalytics": + case "Sitemap": + case "DotNetNuke.Taxonomy": + desktopModuleInfo.Value.Category = "Admin"; + update = true; + break; + default: + break; + } + + if (update) + { + if (desktopModuleInfo.Value.PackageID == Null.NullInteger) + { + LegacyUtil.ProcessLegacyModule(desktopModuleInfo.Value); + } - CopyGettingStartedStyles(); + DesktopModuleController.SaveDesktopModule(desktopModuleInfo.Value, false, false); + } + } } - private static void UpgradeToVersion711() + /// ----------------------------------------------------------------------------- + /// + /// CoreModuleExists determines whether a Core Module exists on the system. + /// + /// + /// + /// The Friendly Name of the Module. + /// True if the Module exists, otherwise False. + /// ----------------------------------------------------------------------------- + private static bool CoreModuleExists(string desktopModuleName) { - DesktopModuleController.DeleteDesktopModule("FileManager"); - - // Add TabUrl Logtypes - 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); + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); - logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); - logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; - LogController.Instance.AddLogType(logTypeInfo); + return desktopModule != null; } - private static void UpgradeToVersion712() + private static void EnableModalPopUps() { - // update console module in Admin/Host page to set OrderTabsByHierarchy setting to true. - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "EnableModalPopUps"); + foreach (var desktopModuleInfo in DesktopModuleController.GetDesktopModules(Null.NullInteger)) { - var tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); - if (tabId != Null.NullInteger) + switch (desktopModuleInfo.Value.ModuleName) { - foreach (var module in ModuleController.Instance.GetTabModules(tabId).Where(m => m.Value.ModuleDefinition.FriendlyName == "Console")) - { - ModuleController.Instance.UpdateModuleSetting(module.Key, "OrderTabsByHierarchy", "True"); - } + case "Portals": + case "SQL": + case "HostSettings": + case "Scheduler": + case "SearchAdmin": + case "Lists": + case "Extensions": + case "WhatsNew": + case "Dashboard": + case "Marketplace": + case "ConfigurationManager": + case "Security": + case "Tabs": + case "Vendors": + case "Banners": + case "FileManager": + case "SiteLog": + case "Newsletters": + case "RecycleBin": + case "LogViewer": + case "SiteWizard": + case "Languages": + case "Skins": + case "SkinDesigner": + case "GoogleAnalytics": + case "Sitemap": + case "DotNetNuke.Taxonomy": + foreach (ModuleDefinitionInfo definition in desktopModuleInfo.Value.ModuleDefinitions.Values) + { + foreach (ModuleControlInfo control in definition.ModuleControls.Values) + { + if (!string.IsNullOrEmpty(control.ControlKey)) + { + control.SupportsPopUps = true; + ModuleControlController.SaveModuleControl(control, false); + } + } + } + + break; + default: + break; } } - var hostTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host", Null.NullString); - if (hostTabId != Null.NullInteger) + foreach (ModuleControlInfo control in ModuleControlController.GetModuleControlsByModuleDefinitionID(Null.NullInteger).Values) { - foreach (var module in ModuleController.Instance.GetTabModules(hostTabId).Where(m => m.Value.ModuleDefinition.FriendlyName == "Console")) - { - ModuleController.Instance.UpdateModuleSetting(module.Key, "OrderTabsByHierarchy", "True"); - } + control.SupportsPopUps = true; + ModuleControlController.SaveModuleControl(control, false); } } - private static void UpgradeToVersion720() + /// ----------------------------------------------------------------------------- + /// + /// GetModuleDefinition gets the Module Definition Id of a module. + /// + /// The Friendly Name of the Module to Add. + /// The Module Definition Name. + /// The Module Definition Id of the Module (-1 if no module definition). + /// ----------------------------------------------------------------------------- + private static int GetModuleDefinition(string desktopModuleName, string moduleDefinitionName) { - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("51Degrees.mobi", Null.NullInteger); - if (desktopModule != null) + // get desktop module + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); + if (desktopModule == null) { - DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); + return -1; } - desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.RadEditorProvider", Null.NullInteger); - if (desktopModule != null) + // get module definition + ModuleDefinitionInfo objModuleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(moduleDefinitionName, desktopModule.DesktopModuleID); + if (objModuleDefinition == null) { - DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); + return -1; } - // ensure old codeplex module is uninstalled - need to check for both variants of package name - UninstallPackage("DotNetNuke.Module Creator", "Module"); - UninstallPackage("DNNCorp.ModuleCreator", "Module"); + return objModuleDefinition.ModuleDefID; + } - DesktopModuleController.AddModuleCategory("Developer"); - var moduleDefId = AddModuleDefinition("Module Creator", "Development of modules.", "Module Creator"); - AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ModuleCreator/CreateModule.ascx", "~/DesktopModules/Admin/ModuleCreator/icon.png", SecurityAccessLevel.Host, 0); - if (ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId) != null) - { - var desktopModuleId = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId).DesktopModuleID; - desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); - desktopModule.Category = "Developer"; - DesktopModuleController.SaveDesktopModule(desktopModule, false, false); + /// ----------------------------------------------------------------------------- + /// + /// HostTabExists determines whether a tab of a given name exists under the Host tab. + /// + /// + /// + /// The Name of the Tab. + /// True if the Tab exists, otherwise False. + /// ----------------------------------------------------------------------------- + private static bool HostTabExists(string tabName) + { + bool tabExists = false; + var hostTab = TabController.Instance.GetTabByName("Host", Null.NullInteger); - var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID); - package.IconFile = "~/Icons/Sigma/ModuleCreator_32x32.png"; - PackageController.Instance.SaveExtensionPackage(package); + var tab = TabController.Instance.GetTabByName(tabName, Null.NullInteger, hostTab.TabID); + if (tab != null) + { + tabExists = true; } - var typeController = new ContentTypeController(); - var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); + return tabExists; + } - // only perform following for an existing installation upgrading - if (Globals.Status == Globals.UpgradeStatus.Upgrade) + /// ----------------------------------------------------------------------------- + /// + /// InstallMemberRoleProviderScript - Installs a specific MemberRole Provider script. + /// + /// + /// + /// The Path to the Provider Directory. + /// The Name of the Script File. + /// Whether or not to echo results. + private static string InstallMemberRoleProviderScript(string providerPath, string scriptFile, bool writeFeedback) + { + if (writeFeedback) { - ImportDocumentLibraryCategories(); - ImportDocumentLibraryCategoryAssoc(fileContentType); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Executing Script: " + scriptFile + "
    "); } - // fixes issue introduced by eventlog's being defined in upgrade.cs - PortalController.EnsureRequiredEventLogTypesExist(); + string exceptions = DataProvider.Instance().ExecuteScript(FileSystemUtils.ReadFile(providerPath + scriptFile + ".sql")); - // Remove Professional Features pages from CE - int advancedFeaturesTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//ProfessionalFeatures", Null.NullString); - if (DotNetNukeContext.Current.Application.Name == "DNNCORP.CE") + // log the results + try { - foreach (var tab in TabController.GetTabsByParent(advancedFeaturesTabId, Null.NullInteger)) + using (StreamWriter streamWriter = File.CreateText(providerPath + scriptFile + ".log.resources")) { - TabController.Instance.DeleteTab(tab.TabID, Null.NullInteger); + streamWriter.WriteLine(exceptions); + streamWriter.Close(); } - - TabController.Instance.DeleteTab(advancedFeaturesTabId, Null.NullInteger); } - - // Remove Whats New - int whatsNewTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//WhatsNew", Null.NullString); - TabController.Instance.DeleteTab(whatsNewTabId, Null.NullInteger); - - // Remove WhatsNew module - DesktopModuleController.DeleteDesktopModule("WhatsNew"); - - // read plaintext password via old API and encrypt - var current = HostController.Instance.GetString("SMTPPassword"); - if (!string.IsNullOrEmpty(current)) + catch (Exception exc) { - HostController.Instance.UpdateEncryptedString("SMTPPassword", current, Config.GetDecryptionkey()); + // does not have permission to create the log file + Logger.Error(exc); } + + return exceptions; } - private static void UpgradeToVersion721() + /// ----------------------------------------------------------------------------- + /// + /// ParseFiles parses the Host Template's Files node. + /// + /// + /// + /// The Files node. + /// The PortalId (-1 for Host Files). + /// ----------------------------------------------------------------------------- + private static void ParseFiles(XmlNode node, int portalId) { - try + // Parse the File nodes + if (node != null) { - // the username maybe html encode when register in 7.1.2, it will caught unicode charactors changed, need use InputFilter to correct the value. - var portalSecurity = PortalSecurity.Instance; - using (var reader = DataProvider.Instance().ExecuteSQL("SELECT UserID, Username FROM {databaseOwner}[{objectQualifier}Users] WHERE Username LIKE '%&%'")) + XmlNodeList nodes = node.SelectNodes("file"); + if (nodes != null) { - while (reader.Read()) + var folderManager = FolderManager.Instance; + var fileManager = FileManager.Instance; + + foreach (XmlNode fileNode in nodes) { - var userId = Convert.ToInt32(reader["UserID"]); - var userName = reader["Username"].ToString(); + string fileName = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "filename"); + string extension = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "extension"); + long size = long.Parse(XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "size")); + int width = XmlUtils.GetNodeValueInt(fileNode, "width"); + int height = XmlUtils.GetNodeValueInt(fileNode, "height"); + string contentType = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "contentType"); + string folder = XmlUtils.GetNodeValue(fileNode.CreateNavigator(), "folder"); - if (userName != HttpUtility.HtmlDecode(userName)) + var folderInfo = folderManager.GetFolder(portalId, folder); + var file = new FileInfo(portalId, fileName, extension, (int)size, width, height, contentType, folder, folderInfo.FolderID, folderInfo.StorageLocation, true); + + using (var fileContent = fileManager.GetFileContent(file)) { - userName = portalSecurity.InputFilter( - HttpUtility.HtmlDecode(userName), - PortalSecurity.FilterFlag.NoScripting | - PortalSecurity.FilterFlag.NoAngleBrackets | - PortalSecurity.FilterFlag.NoMarkup); + var addedFile = fileManager.AddFile(folderInfo, file.FileName, fileContent, false); - UserController.ChangeUsername(userId, userName); + file.FileId = addedFile.FileId; + file.EnablePublishPeriod = addedFile.EnablePublishPeriod; + file.EndDate = addedFile.EndDate; + file.StartDate = addedFile.StartDate; } + + fileManager.UpdateFile(file); } } } - catch (Exception ex) - { - Logger.Error(ex); - } - - AddManageUsersModulePermissions(); } - private static void UpgradeToVersion722() + /// ----------------------------------------------------------------------------- + /// + /// RemoveCoreModule removes a Core Module from the system. + /// + /// + /// + /// The Friendly Name of the Module to Remove. + /// The Name of the parent Tab/Page for this module. + /// The Name to tab that contains the Module. + /// A flag to determine whether to remove the Tab if it has no + /// other modules. + /// ----------------------------------------------------------------------------- + private static void RemoveCoreModule(string desktopModuleName, string parentTabName, string tabName, bool removeTab) { - UninstallPackage("DotNetNuke.Messaging", "Module"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveCoreModule:" + desktopModuleName); - // add event log type:POTENTIAL_PAYPAL_PAYMENT_FRAUD - if (!DoesLogTypeExists(EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString())) - { - var logTypeInfo = new LogTypeInfo - { - LogTypeKey = - EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString(), - LogTypeFriendlyName = "Potential Paypal Payment Fraud", - LogTypeDescription = string.Empty, - LogTypeCSSClass = "OperationFailure", - LogTypeOwner = "DotNetNuke.Logging.EventLogType", - }; - LogController.Instance.AddLogType(logTypeInfo); - } + int moduleDefId = Null.NullInteger; + int desktopModuleId = 0; - // AdvancedSettings module needs to be made a system package - var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.AdvancedSettings"); - if (pkg != null) + // Find and remove the Module from the Tab + switch (parentTabName) { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); - } + case "Host": + var tab = TabController.Instance.GetTabByName("Host", Null.NullInteger, Null.NullInteger); - // Site Wizard module needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteWizard"); - if (pkg != null) - { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); - } + if (tab != null) + { + moduleDefId = RemoveModule(desktopModuleName, tabName, tab.TabID, removeTab); + } - // Site Log module needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteLog"); - if (pkg != null) - { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); - } + break; + case "Admin": + var portals = PortalController.Instance.GetPortals(); - // Module Creator module needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Module Creator"); - if (pkg != null) - { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); + // Iterate through the Portals to remove the Module from the Tab + for (int intPortal = 0; intPortal <= portals.Count - 1; intPortal++) + { + var portal = (PortalInfo)portals[intPortal]; + moduleDefId = RemoveModule(desktopModuleName, tabName, portal.AdminTabId, removeTab); + } + + break; } - // Telerik.Web module needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Telerik.Web"); - if (pkg != null) + DesktopModuleInfo desktopModule = null; + if (moduleDefId == Null.NullInteger) { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); + desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(desktopModuleName, Null.NullInteger); + desktopModuleId = desktopModule.DesktopModuleID; } - - // jQuery needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery"); - if (pkg != null) + else { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); + // Get the Module Definition + ModuleDefinitionInfo moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId); + if (moduleDefinition != null) + { + desktopModuleId = moduleDefinition.DesktopModuleID; + desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); + } } - // jQuery-Migrate needs to be made a system package - pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery-Migrate"); - if (pkg != null) + if (desktopModule != null) { - pkg.IsSystemPackage = true; - PackageController.Instance.SaveExtensionPackage(pkg); - } + // Delete the Desktop Module + var desktopModuleController = new DesktopModuleController(); + desktopModuleController.DeleteDesktopModule(desktopModuleId); - // Make ConfigurationManager Premium - MakeModulePremium(@"ConfigurationManager"); + // Delete the Package + PackageController.Instance.DeleteExtensionPackage(PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID)); + } + } - // Make ConfigurationManager Premium - MakeModulePremium(@"Dashboard"); + private static void RemoveModuleControl(int moduleDefId, string controlKey) + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleControl:" + moduleDefId); - // Make ProfessionalPreview Premium - MakeModulePremium(@"ProfessionalPreview"); + // get Module Control + var moduleControl = ModuleControlController.GetModuleControlByControlKey(controlKey, moduleDefId); + if (moduleControl != null) + { + ModuleControlController.DeleteModuleControl(moduleControl.ModuleControlID); + } } - private static void UpgradeToVersion730() + private static void RemoveModuleFromPortals(string friendlyName) { -#pragma warning disable 612,618 - if (jQuery.UseHostedScript) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveModuleFromPortals:" + friendlyName); + DesktopModuleInfo desktopModule = DesktopModuleController.GetDesktopModuleByFriendlyName(friendlyName); + if (desktopModule != null) { - HostController.Instance.Update("CDNEnabled", "True", true); - - var jquery = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQuery); - jquery.CDNPath = jQuery.HostedUrl; - JavaScriptLibraryController.Instance.SaveLibrary(jquery); - - var jqueryui = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQueryUI); - jqueryui.CDNPath = jQuery.HostedUIUrl; - JavaScriptLibraryController.Instance.SaveLibrary(jqueryui); + // Module was incorrectly assigned as "IsPremium=False" + if (desktopModule.PackageID > Null.NullInteger) + { + desktopModule.IsPremium = true; + DesktopModuleController.SaveDesktopModule(desktopModule, false, true); + } - var jquerymigrate = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQueryMigrate); - jquerymigrate.CDNPath = jQuery.HostedMigrateUrl; - JavaScriptLibraryController.Instance.SaveLibrary(jquerymigrate); + // Remove the module from Portals + DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); } -#pragma warning restore 612,618 } - private static void UpgradeToVersion732() + private static bool TabPermissionExists(TabPermissionInfo tabPermission, int portalID) { - // Register System referenced 3rd party assemblies. - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.dll", "3.0.3"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.FastVectorHighlighter.dll", "3.0.3"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.Analyzers.dll", "3.0.3"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.ApplicationBlocks.Data.dll", "2.0.0"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.Web.Helpers.dll", "2.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.Web.Infrastructure.dll", "1.0.20105"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Newtonsoft.Json.dll", "4.5.7"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "PetaPoco.dll", "5.0.1"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "SharpZipLib.dll", "0.81.0"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.dll", "1.0.0"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.Formatting.dll", "4.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.WebRequest.dll", "1.0.0"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Helpers.dll", "2.0.20216"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Http.dll", "4.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Http.WebHost.dll", "4.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Razor.dll", "2.0.20216"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.Deployment.dll", "2.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.dll", "2.0.20710"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.Razor.dll", "2.0.20126"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebFormsMvp.dll", "1.4.1"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.Data.dll", "2.0.20126"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.WebData.dll", "2.0.20126"); - - // update help url - HostController.Instance.Update("HelpURL", "https://dnndocs.com", false); + return TabPermissionController.GetTabPermissions(tabPermission.TabID, portalID).Cast().Any(permission => permission.TabID == tabPermission.TabID && permission.RoleID == tabPermission.RoleID && permission.PermissionID == tabPermission.PermissionID); } - private static void UpgradeToVersion733() + private static void FavIconsToPortalSettings() { - var notificationType = new NotificationType { Name = "NewUnauthorizedUserRegistration", Description = "New Unauthorized User Registration Notification" }; - NotificationsController.Instance.CreateNotificationType(notificationType); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "FavIconsToPortalSettings"); + const string fileName = "favicon.ico"; + var portals = PortalController.Instance.GetPortals().Cast(); - var actions = new List - { - new NotificationTypeAction - { - NameResourceKey = "AuthorizeUser", - DescriptionResourceKey = "AuthorizeUserDescription", - APICall = "API/InternalServices/NewUserNotificationService/Authorize", - }, - new NotificationTypeAction - { - NameResourceKey = "RejectUser", - DescriptionResourceKey = "RejectUserDescription", - APICall = "API/InternalServices/NewUserNotificationService/Reject" - }, - }; + foreach (var portalInfo in portals) + { + string localPath = Path.Combine(portalInfo.HomeDirectoryMapPath, fileName); - NotificationsController.Instance.SetNotificationTypeActions(actions, notificationType.NotificationTypeId); - } + if (File.Exists(localPath)) + { + try + { + int fileId; + var folder = FolderManager.Instance.GetFolder(portalInfo.PortalID, string.Empty); + if (!FileManager.Instance.FileExists(folder, fileName)) + { + using (var stream = File.OpenRead(localPath)) + { + FileManager.Instance.AddFile(folder, fileName, stream, /*overwrite*/ false); + } + } - private static void UpgradeToVersion740() - { - string PageHeadTextForUpgrade = "" + "\n" + - "" + "\n" + - "" + "\n" + + fileId = FileManager.Instance.GetFile(folder, fileName).FileId; + + new FavIcon(portalInfo.PortalID).Update(fileId); + } + catch (Exception e) + { + string message = string.Format("Unable to setup Favicon for Portal: {0}", portalInfo.PortalName); + var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.ADMIN_ALERT.ToString() }; + log.AddProperty("Issue", message); + log.AddProperty("ExceptionMessage", e.Message); + log.AddProperty("StackTrace", e.StackTrace); + LogController.Instance.AddLog(log); - "" + "\n" + - "" + "\n" + - "" + "\n"; - ArrayList portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) - { - PortalController.UpdatePortalSetting(portal.PortalID, "PageHeadText", PageHeadTextForUpgrade); + Logger.Warn(message, e); + } + } } - - RemoveContentListModuleFromSearchResultsPage(); - ReIndexUserSearch(); } - private static void UpgradeToVersion742() + private static void AddIconToAllowedFiles() { - var containerFolder = string.Format("{0}Containers\\DarkKnightMobile", Globals.HostMapPath); - var skinFolder = string.Format("{0}Skins\\DarkKnightMobile", Globals.HostMapPath); - if (!Directory.Exists(skinFolder)) - { - UninstallPackage("DarkKnightMobile", "Skin"); // Skin - } - - if (!Directory.Exists(containerFolder)) - { - UninstallPackage("DarkKnightMobile", "Container"); // Container - } + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddIconToAllowedFiles"); + var toAdd = new List { ".ico" }; + HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); } - private static void ReIndexUserSearch() + private static void UpgradeToVersion323() { - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) - { - PortalController.UpdatePortalSetting(portal.PortalID, UserIndexer.UserIndexResetFlag, "TRUE"); - } + // add new SecurityException + string configFile = Globals.HostMapPath + "Logs\\LogConfig\\SecurityExceptionTemplate.xml.resources"; + LogController.Instance.AddLogType(configFile, Null.NullString); } - private static void RemoveContentListModuleFromSearchResultsPage() + private static void UpgradeToVersion440() { + // remove module cache files with *.htm extension ( they are now securely named *.resources ) var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + foreach (PortalInfo objPortal in portals) { - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(portal.SearchTabId)) + if (Directory.Exists(Globals.ApplicationMapPath + "\\Portals\\" + objPortal.PortalID + "\\Cache\\")) { - var module = kvp.Value; - if (module.DesktopModule.FriendlyName == "ContentList") + string[] files = Directory.GetFiles(Globals.ApplicationMapPath + "\\Portals\\" + objPortal.PortalID + "\\Cache\\", "*.htm"); + foreach (string file in files) { - // Delete the Module from the Modules list - ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); - break; + File.Delete(file); } } } } - private static void AddManageUsersModulePermissions() + private static void UpgradeToVersion470() { - var permCtl = new PermissionController(); - var desktopInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); - - // add new user dialog - var md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Account", desktopInfo.DesktopModuleID); - try - { - var pi = new PermissionInfo - { - ModuleDefID = md.ModuleDefID, - PermissionCode = "SECURITY_MODULE", - PermissionKey = "MANAGEUSER", - PermissionName = "Manage User", - }; - - permCtl.AddPermission(pi); - } - catch - { - // suppress - } - - md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", desktopInfo.DesktopModuleID); - try + string hostTemplateFile = Globals.HostMapPath + "Templates\\Default.page.template"; + if (File.Exists(hostTemplateFile)) { - var pi = new PermissionInfo + ArrayList portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - ModuleDefID = md.ModuleDefID, - PermissionCode = "SECURITY_MODULE", - PermissionKey = "MANAGEUSERS", - PermissionName = "Manage Users", - }; + string portalTemplateFolder = portal.HomeDirectoryMapPath + "Templates\\"; - permCtl.AddPermission(pi); - } - catch - { - // suppress - } + if (!Directory.Exists(portalTemplateFolder)) + { + // Create Portal Templates folder + Directory.CreateDirectory(portalTemplateFolder); + } - md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Security Roles", desktopInfo.DesktopModuleID); - try - { - var pi = new PermissionInfo - { - ModuleDefID = md.ModuleDefID, - PermissionCode = "SECURITY_MODULE", - PermissionKey = "MANAGEROLES", - PermissionName = "Manage Roles", - }; + string portalTemplateFile = portalTemplateFolder + "Default.page.template"; + if (!File.Exists(portalTemplateFile)) + { + File.Copy(hostTemplateFile, portalTemplateFile); - permCtl.AddPermission(pi); - } - catch - { - // suppress + // Synchronize the Templates folder to ensure the templates are accessible + FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); + } + } } } - private static ContentItem CreateFileContentItem() + private static void UpgradeToVersion482() { - var typeController = new ContentTypeController(); - var contentTypeFile = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - - if (contentTypeFile == null) - { - contentTypeFile = new ContentType { ContentType = "File" }; - contentTypeFile.ContentTypeId = typeController.AddContentType(contentTypeFile); - } - - var objContent = new ContentItem - { - ContentTypeId = contentTypeFile.ContentTypeId, - Indexed = false, - }; - - objContent.ContentItemId = DotNetNuke.Entities.Content.Common.Util.GetContentController().AddContentItem(objContent); - - return objContent; + // checks for the very rare case where the default validationkey prior to 4.08.02 + // is still being used and updates it + Config.UpdateValidationKey(); } - private static void ImportDocumentLibraryCategoryAssoc(ContentType fileContentType) + private static void UpgradeToVersion500() { - DataProvider dataProvider = DataProvider.Instance(); - IDataReader dr; - try + ArrayList portals = PortalController.Instance.GetPortals(); + + // Add Edit Permissions for Admin Tabs to legacy portals + var permissionController = new PermissionController(); + ArrayList permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_TAB", "EDIT"); + int permissionId = -1; + if (permissions.Count == 1) { - var termController = new TermController(); - var vocabulary = new VocabularyController().GetVocabularies().Single(v => v.Name == "Tags"); - var terms = termController.GetTermsByVocabulary(vocabulary.VocabularyId); - using (dr = dataProvider.ExecuteReader("ImportDocumentLibraryCategoryAssoc")) + var permission = permissions[0] as PermissionInfo; + if (permission != null) { - while (dr.Read()) + permissionId = permission.PermissionID; + } + + foreach (PortalInfo portal in portals) + { + var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, true); + if (adminTab != null) { - var file = FileManager.Instance.GetFile((int)dr["FileId"]); - ContentItem attachContentItem; - if (file.ContentItemID == Null.NullInteger) - { - attachContentItem = CreateFileContentItem(); - file.ContentItemID = attachContentItem.ContentItemId; - FileManager.Instance.UpdateFile(file); - } - else + var tabPermission = new TabPermissionInfo { TabID = adminTab.TabID, PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; + if (!TabPermissionExists(tabPermission, portal.PortalID)) { - attachContentItem = Util.GetContentController().GetContentItem(file.ContentItemID); + adminTab.TabPermissions.Add(tabPermission); } - var term = terms.SingleOrDefault(t => t.Name == dr["CategoryName"].ToString()); - if (term == null) + // Save Tab Permissions to Data Base + TabPermissionController.SaveTabPermissions(adminTab); + + foreach (var childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) { - term = new Term(dr["CategoryName"].ToString(), null, vocabulary.VocabularyId); - termController.AddTerm(term); - } + tabPermission = new TabPermissionInfo { TabID = childTab.TabID, PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; + if (!TabPermissionExists(tabPermission, portal.PortalID)) + { + childTab.TabPermissions.Add(tabPermission); + } - termController.AddTermToContent(term, attachContentItem); + // Save Tab Permissions to Data Base + TabPermissionController.SaveTabPermissions(childTab); + } } } } - catch (Exception ex) - { - Logger.Error(ex); - } - } - - private static void ImportDocumentLibraryCategories() - { - VocabularyController vocabularyController = new VocabularyController(); - var defaultTags = (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); - - DataProvider dataProvider = DataProvider.Instance(); - dataProvider.ExecuteNonQuery("ImportDocumentLibraryCategories", defaultTags.VocabularyId); - } - - private static void UpdateFoldersForParentId() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeFolders"); - // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out - var foldersToConvert = DataProvider.Instance().GetLegacyFolderCount(); - var foldersRemaining = foldersToConvert; - - if (foldersRemaining > 0) + // Update Host/Admin modules Visibility setting + bool superTabProcessed = Null.NullBoolean; + foreach (PortalInfo portal in portals) { - // Create an empty line - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); + if (!superTabProcessed) + { + // Process Host Tabs + foreach (TabInfo childTab in TabController.GetTabsByParent(portal.SuperTabId, Null.NullInteger)) + { + foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) + { + tabModule.Visibility = VisibilityState.None; + ModuleController.Instance.UpdateModule(tabModule); + } + } + } + + // Process Portal Tabs + foreach (TabInfo childTab in TabController.GetTabsByParent(portal.AdminTabId, portal.PortalID)) + { + foreach (ModuleInfo tabModule in ModuleController.Instance.GetTabModules(childTab.TabID).Values) + { + tabModule.Visibility = VisibilityState.None; + ModuleController.Instance.UpdateModule(tabModule); + } + } } - while (foldersRemaining > 0) + // Upgrade PortalDesktopModules to support new "model" + permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_DESKTOPMODULE", "DEPLOY"); + if (permissions.Count == 1) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Converting old Folders to new format. Total: {0} [Remaining: {1}]
    ", foldersToConvert, foldersRemaining)); - try + var permission = permissions[0] as PermissionInfo; + if (permission != null) { - using (DataProvider.Instance().UpdateLegacyFolders()) - { - } + permissionId = permission.PermissionID; } - catch (Exception ex) + + foreach (PortalInfo portal in portals) { - Exceptions.Exceptions.LogException(ex); - } + foreach (DesktopModuleInfo desktopModule in DesktopModuleController.GetDesktopModules(Null.NullInteger).Values) + { + if (!desktopModule.IsPremium) + { + // Parse the permissions + var deployPermissions = new DesktopModulePermissionCollection(); + DesktopModulePermissionInfo deployPermission; - foldersRemaining = DataProvider.Instance().GetLegacyFolderCount(); - } + // if Not IsAdmin add Registered Users + if (!desktopModule.IsAdmin) + { + deployPermission = new DesktopModulePermissionInfo { PermissionID = permissionId, AllowAccess = true, RoleID = portal.RegisteredRoleId }; + deployPermissions.Add(deployPermission); + } - if (foldersToConvert > 0) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Conversion of old Folders Completed. Total Converted: {0}
    ", foldersToConvert)); + // if Not a Host Module add Administrators + const string hostModules = "Portals, SQL, HostSettings, Scheduler, SearchAdmin, Lists, SkinDesigner, Extensions"; + if (!hostModules.Contains(desktopModule.ModuleName)) + { + deployPermission = new DesktopModulePermissionInfo { PermissionID = permissionId, AllowAccess = true, RoleID = portal.AdministratorRoleId }; + deployPermissions.Add(deployPermission); + } + + // Add Portal/Module to PortalDesktopModules + DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, false); + } + } + + DataCache.ClearPortalCache(portal.PortalID, true); + } } + + LegacyUtil.ProcessLegacyModules(); + LegacyUtil.ProcessLegacyLanguages(); + LegacyUtil.ProcessLegacySkins(); + LegacyUtil.ProcessLegacySkinControls(); } - private static void UninstallPackage(string packageName, string packageType, bool deleteFiles = true, string version = "") + private static void UpgradeToVersion501() { - DnnInstallLogger.InstallLogInfo(string.Concat(Localization.GetString("LogStart", Localization.GlobalResourceFile), "Uninstallation of Package:", packageName, " Type:", packageType, " Version:", version)); - - var searchInput = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => - p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase) - && p.PackageType.Equals(packageType, StringComparison.OrdinalIgnoreCase) - && (string.IsNullOrEmpty(version) || p.Version.ToString() == version)); - if (searchInput != null) - { - var searchInputInstaller = new Installer(searchInput, Globals.ApplicationMapPath); - searchInputInstaller.UnInstall(deleteFiles); - } + // add new Cache Error Event Type + string configFile = string.Format("{0}Logs\\LogConfig\\CacheErrorTemplate.xml.resources", Globals.HostMapPath); + LogController.Instance.AddLogType(configFile, Null.NullString); } - private static void ConvertCoreNotificationTypeActionsFor700() + private static void UpgradeToVersion510() { - var notificationTypeNames = new[] { "FriendRequest", "FollowerRequest", "FollowBackRequest", "TranslationSubmitted" }; + int moduleDefId; - foreach (var name in notificationTypeNames) + // add Dashboard module and tab + if (HostTabExists("Dashboard") == false) { - var nt = NotificationsController.Instance.GetNotificationType(name); + moduleDefId = AddModuleDefinition("Dashboard", "Provides a snapshot of your DotNetNuke Application.", "Dashboard", true, true); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Dashboard/Dashboard.ascx", "icon_dashboard_32px.gif", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Export", string.Empty, "DesktopModules/Admin/Dashboard/Export.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); - if (nt != null) - { - var actions = NotificationsController.Instance.GetNotificationTypeActions(nt.NotificationTypeId).ToList(); + // Create New Host Page (or get existing one) + TabInfo dashboardPage = AddHostPage("Dashboard", "Summary view of application and site settings.", "~/images/icon_dashboard_16px.gif", "~/images/icon_dashboard_32px.gif", true); - if (actions.Any()) - { - foreach (var action in actions) - { - action.APICall = action.APICall.Replace(".ashx", string.Empty); - NotificationsController.Instance.DeleteNotificationTypeAction( - action.NotificationTypeActionId); - } + // Add Module To Page + AddModuleToPage(dashboardPage, moduleDefId, "Dashboard", "~/images/icon_dashboard_32px.gif"); + } + else + { + // Module was incorrectly assigned as "IsPremium=False" + RemoveModuleFromPortals("Dashboard"); - NotificationsController.Instance.SetNotificationTypeActions(actions, nt.NotificationTypeId); - } - } - else - { - AddMissingNotificationTypes(name); - } + // fix path for dashboarcontrols + moduleDefId = GetModuleDefinition("Dashboard", "Dashboard"); + RemoveModuleControl(moduleDefId, "DashboardControls"); + AddModuleControl(moduleDefId, "DashboardControls", string.Empty, "DesktopModules/Admin/Dashboard/DashboardControls.ascx", string.Empty, SecurityAccessLevel.Host, 0); } - } - private static void AddMissingNotificationTypes(string notificationTypeName) - { - switch (notificationTypeName) + // Add the Extensions Module + if (CoreModuleExists("Extensions") == false) { - case "FriendRequest": - var friendRequestType = new NotificationType { Name = notificationTypeName, Description = "Friend Request" }; - var friendRequestTypeActions = new List(); - friendRequestTypeActions.Add(new NotificationTypeAction - { - NameResourceKey = "Accept", - DescriptionResourceKey = "AcceptFriend", - APICall = "API/InternalServices/RelationshipService/AcceptFriend", - }); - NotificationsController.Instance.CreateNotificationType(friendRequestType); - NotificationsController.Instance.SetNotificationTypeActions(friendRequestTypeActions, friendRequestType.NotificationTypeId); - break; - case "FollowerRequest": - var followerRequestType = new NotificationType { Name = notificationTypeName, Description = "Follower Request" }; - NotificationsController.Instance.CreateNotificationType(followerRequestType); - break; - case "FollowBackRequest": - var followBackRequestType = new NotificationType { Name = notificationTypeName, Description = "Follow Back Request" }; - var followBackRequestTypeActions = new List(); - followBackRequestTypeActions.Add(new NotificationTypeAction - { - NameResourceKey = "FollowBack", - DescriptionResourceKey = "FollowBack", - ConfirmResourceKey = string.Empty, - APICall = "API/InternalServices/RelationshipService/FollowBack", - }); - NotificationsController.Instance.CreateNotificationType(followBackRequestType); - NotificationsController.Instance.SetNotificationTypeActions(followBackRequestTypeActions, followBackRequestType.NotificationTypeId); - break; - case "TranslationSubmitted": - var translationSubmittedType = new NotificationType { Name = notificationTypeName, Description = "Translation Submitted" }; - NotificationsController.Instance.CreateNotificationType(translationSubmittedType); - break; - default: - break; + moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Extensions/Extensions.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.View, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Feature", "DesktopModules/Admin/Extensions/EditExtension.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "PackageWriter", "Package Writer", "DesktopModules/Admin/Extensions/PackageWriter.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "EditControl", "Edit Control", "DesktopModules/Admin/Extensions/Editors/EditModuleControl.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "ImportModuleDefinition", "Import Module Definition", "DesktopModules/Admin/Extensions/Editors/ImportModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "BatchInstall", "Batch Install", "DesktopModules/Admin/Extensions/BatchInstall.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "NewExtension", "New Extension Wizard", "DesktopModules/Admin/Extensions/ExtensionWizard.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); } - } + else + { + moduleDefId = GetModuleDefinition("Extensions", "Extensions"); + RemoveModuleControl(moduleDefId, "EditLanguage"); + RemoveModuleControl(moduleDefId, "TimeZone"); + RemoveModuleControl(moduleDefId, "Verify"); + RemoveModuleControl(moduleDefId, "LanguageSettings"); + RemoveModuleControl(moduleDefId, "EditResourceKey"); + RemoveModuleControl(moduleDefId, "EditSkins"); + AddModuleControl(moduleDefId, "UsageDetails", "Usage Information", "DesktopModules/Admin/Extensions/UsageDetails.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0, string.Empty, true); - private static void AddCoreNotificationTypesFor620() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddCoreNotificationTypesFor620"); - var actions = new List(); + // Module was incorrectly assigned as "IsPremium=False" + RemoveModuleFromPortals("Extensions"); + } - // Friend request - var type = new NotificationType { Name = "FriendRequest", Description = "Friend Request" }; - actions.Add(new NotificationTypeAction - { - NameResourceKey = "Accept", - DescriptionResourceKey = "AcceptFriend", - APICall = "API/InternalServices/RelationshipService/AcceptFriend", - }); - NotificationsController.Instance.CreateNotificationType(type); - NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); + // Remove Module Definitions Module from Host Page (if present) + RemoveCoreModule("Module Definitions", "Host", "Module Definitions", false); - // Follower - type = new NotificationType { Name = "FollowerRequest", Description = "Follower Request" }; - NotificationsController.Instance.CreateNotificationType(type); + // Remove old Module Definition DynamicContentValidator module + DesktopModuleController.DeleteDesktopModule("Module Definition DynamicContentValidator"); - // Follow Back - type = new NotificationType { Name = "FollowBackRequest", Description = "Follow Back Request" }; - actions.Clear(); - actions.Add(new NotificationTypeAction - { - NameResourceKey = "FollowBack", - DescriptionResourceKey = "FollowBack", - ConfirmResourceKey = string.Empty, - APICall = "API/InternalServices/RelationshipService/FollowBack", - }); - NotificationsController.Instance.CreateNotificationType(type); - NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); + // Get Module Definitions + TabInfo definitionsPage = TabController.Instance.GetTabByName("Module Definitions", Null.NullInteger); - // Translation submitted - type = new NotificationType { Name = "TranslationSubmitted", Description = "Translation Submitted" }; - NotificationsController.Instance.CreateNotificationType(type); - } + // Add Module To Page if not present + int moduleId = AddModuleToPage(definitionsPage, moduleDefId, "Module Definitions", "~/images/icon_moduledefinitions_32px.gif"); + ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "Module"); - private static void ConvertOldMessages() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ConvertOldMessages"); + // Add Extensions Host Page + TabInfo extensionsPage = AddHostPage("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true); - // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out - var messagesToConvert = InternalMessagingController.Instance.CountLegacyMessages(); - var messagesRemaining = messagesToConvert; - const int batchSize = 500; + moduleId = AddModuleToPage(extensionsPage, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); + ModuleController.Instance.UpdateModuleSetting(moduleId, "Extensions_Mode", "All"); - if (messagesRemaining > 0) - { - // Create an empty line - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); - } + // Add Extensions Module to Admin Page for all Portals + AddAdminPages("Extensions", "Install, add, modify and delete extensions, such as modules, skins and language packs.", "~/images/icon_extensions_16px.gif", "~/images/icon_extensions_32px.png", true, moduleDefId, "Extensions", "~/images/icon_extensions_32px.png"); - while (messagesRemaining > 0) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Converting old Messages to new format. Total: {0} [Remaining: {1}]
    ", messagesToConvert, messagesRemaining)); - try - { - InternalMessagingController.Instance.ConvertLegacyMessages(0, batchSize); - } - catch (Exception ex) - { - Exceptions.Exceptions.LogException(ex); - } + // Remove Host Languages Page + RemoveHostPage("Languages"); + + // Remove Admin > Authentication Pages + RemoveAdminPages("//Admin//Authentication"); + + // Remove old Languages module + DesktopModuleController.DeleteDesktopModule("Languages"); - messagesRemaining -= batchSize; - } + // Add new Languages module + moduleDefId = AddModuleDefinition("Languages", string.Empty, "Languages", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Language", "DesktopModules/Admin/Languages/EditLanguage.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "EditResourceKey", "Full Language Editor", "DesktopModules/Admin/Languages/languageeditorext.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "LanguageSettings", "Language Settings", "DesktopModules/Admin/Languages/LanguageSettings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); + AddModuleControl(moduleDefId, "TimeZone", "TimeZone Editor", "DesktopModules/Admin/Languages/timezoneeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Verify", "Resource File Verifier", "DesktopModules/Admin/Languages/resourceverifier.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "PackageWriter", "Language Pack Writer", "DesktopModules/Admin/Languages/LanguagePackWriter.ascx", string.Empty, SecurityAccessLevel.Host, 0); - if (messagesToConvert > 0) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Conversion of old Messages Completed. Total Converted: {0}
    ", messagesToConvert)); - } - } + // Add Module to Admin Page for all Portals + AddAdminPages("Languages", "Manage Language Resources.", "~/images/icon_language_16px.gif", "~/images/icon_language_32px.gif", true, moduleDefId, "Language Editor", "~/images/icon_language_32px.gif"); - private static void ReplaceMessagingModule() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ReplaceMessagingModule"); - var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Message Center"); - if (moduleDefinition == null) - { - return; - } + // Remove Host Skins Page + RemoveHostPage("Skins"); - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) - { - if (portal.UserTabId > Null.NullInteger) - { - // Find TabInfo - TabInfo tab = TabController.Instance.GetTab(portal.UserTabId, portal.PortalID, true); - if (tab != null) - { - // Add new module to the page - AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", string.Empty, true); - } + // Remove old Skins module + DesktopModuleController.DeleteDesktopModule("Skins"); - foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(portal.UserTabId)) - { - var module = kvp.Value; - if (module.DesktopModule.FriendlyName == "Messaging") - { - // Delete the Module from the Modules list - ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); - break; - } - } - } - } - } + // Add new Skins module + moduleDefId = AddModuleDefinition("Skins", string.Empty, "Skins", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Skins/editskins.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.View, 0); - private static void MovePhotoProperty() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "MovePhotoProperty"); - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) - { - var properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID).Cast(); - var propPhoto = properties.FirstOrDefault(p => p.PropertyName == "Photo"); - if (propPhoto != null) - { - var maxOrder = properties.Max(p => p.ViewOrder); - if (propPhoto.ViewOrder != maxOrder) - { - properties.Where(p => p.ViewOrder > propPhoto.ViewOrder).ToList().ForEach(p => - { - p.ViewOrder -= 2; - ProfileController.UpdatePropertyDefinition(p); - }); - propPhoto.ViewOrder = maxOrder; - ProfileController.UpdatePropertyDefinition(propPhoto); - } - } - } - } + // Add Module to Admin Page for all Portals + AddAdminPages("Skins", "Manage Skin Resources.", "~/images/icon_skins_16px.gif", "~/images/icon_skins_32px.gif", true, moduleDefId, "Skin Editor", "~/images/icon_skins_32px.gif"); - private static void UpdateChildPortalsDefaultPage() - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateChildPortalsDefaultPage"); + // Remove old Skin Designer module + DesktopModuleController.DeleteDesktopModule("Skin Designer"); + DesktopModuleController.DeleteDesktopModule("SkinDesigner"); - // Update Child Portal subHost.aspx - foreach (PortalAliasInfo aliasInfo in PortalAliasController.Instance.GetPortalAliases().Values) - { - // For the alias to be for a child it must be of the form ...../child - int intChild = aliasInfo.HTTPAlias.IndexOf("/"); - if (intChild != -1 && intChild != (aliasInfo.HTTPAlias.Length - 1)) - { - var childPath = Globals.ApplicationMapPath + "\\" + aliasInfo.HTTPAlias.Substring(intChild + 1); - if (!string.IsNullOrEmpty(Globals.ApplicationPath)) - { - childPath = childPath.Replace("\\", "/"); - childPath = childPath.Replace(Globals.ApplicationPath, string.Empty); - } + // Add new Skin Designer module + moduleDefId = AddModuleDefinition("Skin Designer", "Allows you to modify skin attributes.", "Skin Designer", true, true); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SkinDesigner/Attributes.ascx", "~/images/icon_skins_32px.gif", SecurityAccessLevel.Host, 0); - childPath = childPath.Replace("/", "\\"); + // Add new Skin Designer to every Admin Skins Tab + AddModuleToPages("//Admin//Skins", moduleDefId, "Skin Designer", "~/images/icon_skins_32px.gif", true); - // check if File exists and make sure it's not the site's main default.aspx page - string childDefaultPage = childPath + "\\" + Globals.glbDefaultPage; - if (childPath != Globals.ApplicationMapPath && File.Exists(childDefaultPage)) - { - var objDefault = new System.IO.FileInfo(childDefaultPage); - var objSubHost = new System.IO.FileInfo(Globals.HostMapPath + "subhost.aspx"); + // Remove Admin Whats New Page + RemoveAdminPages("//Admin//WhatsNew"); - // check if upgrade is necessary - if (objDefault.Length != objSubHost.Length) - { - // check file is readonly - bool wasReadonly = false; - FileAttributes attributes = File.GetAttributes(childDefaultPage); - if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) - { - wasReadonly = true; + // WhatsNew needs to be set to IsPremium and removed from all portals + RemoveModuleFromPortals("WhatsNew"); - // remove readonly attribute - File.SetAttributes(childDefaultPage, FileAttributes.Normal); - } + // Create New WhatsNew Host Page (or get existing one) + TabInfo newPage = AddHostPage("What's New", "Provides a summary of the major features for each release.", "~/images/icon_whatsnew_16px.gif", "~/images/icon_whatsnew_32px.gif", true); - // Rename existing file - File.Copy(childDefaultPage, childPath + "\\old_" + Globals.glbDefaultPage, true); + // Add WhatsNew Module To Page + moduleDefId = GetModuleDefinition("WhatsNew", "WhatsNew"); + AddModuleToPage(newPage, moduleDefId, "What's New", "~/images/icon_whatsnew_32px.gif"); - // copy file - File.Copy(Globals.HostMapPath + "subhost.aspx", childDefaultPage, true); + // add console module + moduleDefId = AddModuleDefinition("Console", "Display children pages as icon links for navigation.", "Console", "DotNetNuke.Modules.Console.Components.ConsoleController", true, false, false); + AddModuleControl(moduleDefId, string.Empty, "Console", "DesktopModules/Admin/Console/ViewConsole.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Console Settings", "DesktopModules/Admin/Console/Settings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); - // set back the readonly attribute - if (wasReadonly) - { - File.SetAttributes(childDefaultPage, FileAttributes.ReadOnly); - } - } - } - } - } - } + // add console module to host page + moduleId = AddModuleToPage("//Host", Null.NullInteger, moduleDefId, "Basic Features", string.Empty, true); + int tabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host", Null.NullString); + TabInfo tab; - private static void CopyGettingStartedStyles() - { - // copy getting started css to portals folder. - var hostGettingStartedFile = string.Format("{0}GettingStarted.css", Globals.HostMapPath); - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + // add console settings for host page + if (tabId != Null.NullInteger) { - if (File.Exists(hostGettingStartedFile)) + tab = TabController.Instance.GetTab(tabId, Null.NullInteger, true); + if (tab != null) { - var portalFile = portal.HomeDirectoryMapPath + "GettingStarted.css"; - if (!File.Exists(portalFile)) - { - File.Copy(hostGettingStartedFile, portalFile); - } + AddConsoleModuleSettings(moduleId); } + } - // update the getting started page to have this custom style sheet. - var gettingStartedTabId = PortalController.GetPortalSettingAsInteger("GettingStartedTabId", portal.PortalID, Null.NullInteger); - if (gettingStartedTabId > Null.NullInteger) + // add module to all admin pages + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); + if (tabId != Null.NullInteger) { - // check if tab exists - if (TabController.Instance.GetTab(gettingStartedTabId, portal.PortalID, true) != null) + tab = TabController.Instance.GetTab(tabId, portal.PortalID, true); + if (tab != null) { - TabController.Instance.UpdateTabSetting(gettingStartedTabId, "CustomStylesheet", "GettingStarted.css"); + moduleId = AddModuleToPage(tab, moduleDefId, "Basic Features", string.Empty, true); + AddConsoleModuleSettings(moduleId); } } } + + // Add Google Analytics module + moduleDefId = AddModuleDefinition("Google Analytics", "Configure Site Google Analytics settings.", "GoogleAnalytics", false, false); + AddModuleControl(moduleDefId, string.Empty, "Google Analytics", "DesktopModules/Admin/Analytics/GoogleAnalyticsSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddAdminPages("Google Analytics", "Configure Site Google Analytics settings.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Google Analytics", "~/images/icon_analytics_32px.gif"); } - private static void RemoveGettingStartedPages() + private static void UpgradeToVersion511() { - foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + // New Admin pages may not have administrator permission + // Add Admin role if it does not exist for google analytics or extensions + AddAdminRoleToPage("//Admin//Extensions"); + AddAdminRoleToPage("//Admin//GoogleAnalytics"); + } + + private static void UpgradeToVersion513() + { + // Ensure that default language is present (not neccessarily enabled) + var defaultLanguage = LocaleController.Instance.GetLocale("en-US") ?? new Locale(); + defaultLanguage.Code = "en-US"; + defaultLanguage.Text = "English (United States)"; + Localization.SaveLanguage(defaultLanguage); + + // Ensure that there is a Default Authorization System + var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DefaultAuthentication"); + if (package == null) { - try + package = new PackageInfo { - var fileInfo = FileManager.Instance.GetFile(portal.PortalID, "GettingStarted.css"); - if (fileInfo != null) - { - FileManager.Instance.DeleteFile(fileInfo); - } + Name = "DefaultAuthentication", + FriendlyName = "Default Authentication", + Description = "The Default UserName/Password Authentication System for DotNetNuke.", + PackageType = "Auth_System", + Version = new Version(1, 0, 0), + Owner = "DNN", + License = Localization.GetString("License", Localization.GlobalResourceFile), + Organization = ".NET Foundation", + Url = "https://dnncommunity.org", + Email = "info@dnncommunity.org", + ReleaseNotes = "There are no release notes for this version.", + IsSystemPackage = true, + }; + PackageController.Instance.SaveExtensionPackage(package); - var gettingStartedTabId = PortalController.GetPortalSettingAsInteger("GettingStartedTabId", portal.PortalID, Null.NullInteger); - if (gettingStartedTabId > Null.NullInteger) - { - // remove getting started page from portal - if (TabController.Instance.GetTab(gettingStartedTabId, portal.PortalID, true) != null) - { - TabController.Instance.DeleteTab(gettingStartedTabId, portal.PortalID); - } + // Add Authentication System + var authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN") ?? new AuthenticationInfo(); + authSystem.PackageID = package.PackageID; + authSystem.AuthenticationType = "DNN"; + authSystem.SettingsControlSrc = "DesktopModules/AuthenticationServices/DNN/Settings.ascx"; + authSystem.LoginControlSrc = "DesktopModules/AuthenticationServices/DNN/Login.ascx"; + authSystem.IsEnabled = true; - PortalController.DeletePortalSetting(portal.PortalID, "GettingStartedTabId"); - } + if (authSystem.AuthenticationID == Null.NullInteger) + { + AuthenticationController.AddAuthentication(authSystem); } - catch (Exception ex) + else { - Logger.Error(ex); + AuthenticationController.UpdateAuthentication(authSystem); } } } - private static bool DoesLogTypeExists(string logTypeKey) + private static void UpgradeToVersion520() { - LogTypeInfo logType; - Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); - logTypeDictionary.TryGetValue(logTypeKey, out logType); - if (logType == null) - { - return false; - } + // Add new ViewSource control + AddModuleControl(Null.NullInteger, "ViewSource", "View Module Source", "Admin/Modules/ViewSource.ascx", "~/images/icon_source_32px.gif", SecurityAccessLevel.Host, 0, string.Empty, true); - return true; + // Add Marketplace module definition + int moduleDefId = AddModuleDefinition("Marketplace", "Search for DotNetNuke modules, extension and skins.", "Marketplace"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Marketplace/Marketplace.ascx", "~/images/icon_marketplace_32px.gif", SecurityAccessLevel.Host, 0); + + // Add marketplace Module To Page + TabInfo newPage = AddHostPage("Marketplace", "Search for DotNetNuke modules, extension and skins.", "~/images/icon_marketplace_16px.gif", "~/images/icon_marketplace_32px.gif", true); + moduleDefId = GetModuleDefinition("Marketplace", "Marketplace"); + AddModuleToPage(newPage, moduleDefId, "Marketplace", "~/images/icon_marketplace_32px.gif"); } - /// ----------------------------------------------------------------------------- - /// - /// AddHostPage adds a Host Tab Page. - /// - /// The Name to give this new Tab. - /// - /// The Icon for this new Tab. - /// - /// A flag indicating whether the tab is visible. - /// - /// ----------------------------------------------------------------------------- - public static TabInfo AddHostPage(string tabName, string description, string tabIconFile, string tabIconFileLarge, bool isVisible) + private static void UpgradeToVersion521() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddHostPage:" + tabName); - TabInfo hostPage = TabController.Instance.GetTabByName("Host", Null.NullInteger); + // UpgradeDefaultLanguages is a temporary procedure containing code that + // needed to execute after the 5.1.3 application upgrade code above + DataProvider.Instance().ExecuteNonQuery("UpgradeDefaultLanguages"); - if (hostPage != null) + // This procedure is not intended to be part of the database schema + // and is therefore dropped once it has been executed. + using (DataProvider.Instance().ExecuteSQL("DROP PROCEDURE {databaseOwner}{objectQualifier}UpgradeDefaultLanguages")) { - return AddPage(hostPage, tabName, description, tabIconFile, tabIconFileLarge, isVisible, new TabPermissionCollection(), true); } - - return null; } - /// ----------------------------------------------------------------------------- - /// - /// AddModuleControl adds a new Module Control to the system. - /// - /// - /// - /// The Module Definition Id. - /// The key for this control in the Definition. - /// The title of this control. - /// Te source of ths control. - /// The icon file. - /// The type of control. - /// The vieworder for this module. - /// ----------------------------------------------------------------------------- - public static void AddModuleControl(int moduleDefId, string controlKey, string controlTitle, string controlSrc, string iconFile, SecurityAccessLevel controlType, int viewOrder) + private static void UpgradeToVersion530() { - // Call Overload with HelpUrl = Null.NullString - AddModuleControl(moduleDefId, controlKey, controlTitle, controlSrc, iconFile, controlType, viewOrder, Null.NullString); - } + // update languages module + int moduleDefId = GetModuleDefinition("Languages", "Languages"); + RemoveModuleControl(moduleDefId, string.Empty); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Languages/languageEnabler.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0, string.Empty, true); + AddModuleControl(moduleDefId, "Editor", string.Empty, "DesktopModules/Admin/Languages/languageeditor.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.View, 0); - /// ----------------------------------------------------------------------------- - /// - /// AddModuleDefinition adds a new Core Module Definition to the system. - /// - /// - /// This overload asumes the module is an Admin module and not a Premium Module. - /// - /// The Friendly Name of the Module to Add. - /// Description of the Module. - /// The Module Definition Name. - /// The Module Definition Id of the new Module. - /// ----------------------------------------------------------------------------- - public static int AddModuleDefinition(string desktopModuleName, string description, string moduleDefinitionName) - { - // Call overload with Premium=False and Admin=True - return AddModuleDefinition(desktopModuleName, description, moduleDefinitionName, false, true); - } + // Add new View Profile module + moduleDefId = AddModuleDefinition("ViewProfile", string.Empty, "ViewProfile", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ViewProfile/ViewProfile.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.View, 0); + AddModuleControl(moduleDefId, "Settings", "Settings", "DesktopModules/Admin/ViewProfile/Settings.ascx", "~/images/icon_profile_32px.gif", SecurityAccessLevel.Edit, 0); - /// ----------------------------------------------------------------------------- - /// - /// AddModuleToPage adds a module to a Page. - /// - /// - /// - /// The Page to add the Module to. - /// The Module Deinition Id for the module to be aded to this tab. - /// The Module's title. - /// The Module's icon. - /// Inherit the Pages View Permisions. - /// - /// ----------------------------------------------------------------------------- - public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) - { - return AddModuleToPage(page, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions, true, Globals.glbDefaultPane); - } + // Add new Sitemap settings module + moduleDefId = AddModuleDefinition("Sitemap", string.Empty, "Sitemap", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Sitemap/SitemapSettings.ascx", "~/images/icon_analytics_32px.gif", SecurityAccessLevel.View, 0); + AddAdminPages("Search Engine Sitemap", "Configure the sitemap for submission to common search engines.", "~/images/icon_analytics_16px.gif", "~/images/icon_analytics_32px.gif", true, moduleDefId, "Search Engine Sitemap", "~/images/icon_analytics_32px.gif"); - public static int AddModuleToPage(TabInfo page, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions, bool displayTitle, string paneName) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); - ModuleInfo moduleInfo; - int moduleId = Null.NullInteger; + // Add new Photo Profile field to Host + var listController = new ListController(); + Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - if (page != null) + var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); + ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); + + string installTemplateFile = string.Format("{0}Template\\UserProfile.page.template", Globals.InstallMapPath); + string hostTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.HostMapPath); + if (File.Exists(installTemplateFile)) { - bool isDuplicate = false; - foreach (var kvp in ModuleController.Instance.GetTabModules(page.TabID)) + if (!File.Exists(hostTemplateFile)) { - moduleInfo = kvp.Value; - if (moduleInfo.ModuleDefID == moduleDefId) - { - isDuplicate = true; - moduleId = moduleInfo.ModuleID; - } + File.Copy(installTemplateFile, hostTemplateFile); } + } - if (!isDuplicate) + if (File.Exists(hostTemplateFile)) + { + ArrayList portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - moduleInfo = new ModuleInfo + properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID); + + // Add new Photo Profile field to Portal + ProfileController.AddDefaultDefinition(portal.PortalID, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); + + // Rename old Default Page template + string defaultPageTemplatePath = string.Format("{0}Templates\\Default.page.template", portal.HomeDirectoryMapPath); + if (File.Exists(defaultPageTemplatePath)) { - ModuleID = Null.NullInteger, - PortalID = page.PortalID, - TabID = page.TabID, - ModuleOrder = -1, - ModuleTitle = moduleTitle, - PaneName = paneName, - ModuleDefID = moduleDefId, - CacheTime = 0, - IconFile = moduleIconFile, - AllTabs = false, - Visibility = VisibilityState.None, - InheritViewPermissions = inheritPermissions, - DisplayTitle = displayTitle, - }; + File.Move(defaultPageTemplatePath, string.Format("{0}Templates\\Default_old.page.template", portal.HomeDirectoryMapPath)); + } - ModuleController.Instance.InitialModulePermission(moduleInfo, moduleInfo.TabID, inheritPermissions ? 0 : 1); + // Update Default profile template in every portal + PortalController.Instance.CopyPageTemplate("Default.page.template", portal.HomeDirectoryMapPath); - moduleInfo.TabModuleSettings["hideadminborder"] = "True"; + // Add User profile template to every portal + PortalController.Instance.CopyPageTemplate("UserProfile.page.template", portal.HomeDirectoryMapPath); + + // Synchronize the Templates folder to ensure the templates are accessible + FolderManager.Instance.Synchronize(portal.PortalID, "Templates/", false, true); + var xmlDoc = new XmlDocument { XmlResolver = null }; try { - moduleId = ModuleController.Instance.AddModule(moduleInfo); + // open the XML file + xmlDoc.Load(hostTemplateFile); } - catch (Exception exc) + catch (Exception ex) { - Logger.Error(exc); - DnnInstallLogger.InstallLogError(exc); + Exceptions.Exceptions.LogException(ex); + } + + XmlNode userTabNode = xmlDoc.SelectSingleNode("//portal/tabs/tab"); + if (userTabNode != null) + { + string tabName = XmlUtils.GetNodeValue(userTabNode.CreateNavigator(), "name"); + + var userTab = TabController.Instance.GetTabByName(tabName, portal.PortalID) ?? TabController.DeserializeTab(userTabNode, null, portal.PortalID, PortalTemplateModuleAction.Merge); + + // Update SiteSettings to point to the new page + if (portal.UserTabId > Null.NullInteger) + { + portal.RegisterTabId = portal.UserTabId; + } + else + { + portal.UserTabId = userTab.TabID; + } + } + + PortalController.Instance.UpdatePortalInfo(portal); + + // Add Users folder to every portal + string usersFolder = string.Format("{0}Users\\", portal.HomeDirectoryMapPath); + + if (!Directory.Exists(usersFolder)) + { + // Create Users folder + Directory.CreateDirectory(usersFolder); + + // Synchronize the Users folder to ensure the user folder is accessible + FolderManager.Instance.Synchronize(portal.PortalID, "Users/", false, true); } } } - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "AddModuleToPage:" + moduleDefId); - return moduleId; + AddEventQueueApplicationStartFirstRequest(); + + // Change Key for Module Defintions; + moduleDefId = GetModuleDefinition("Extensions", "Extensions"); + RemoveModuleControl(moduleDefId, "ImportModuleDefinition"); + AddModuleControl(moduleDefId, "EditModuleDefinition", "Edit Module Definition", "DesktopModules/Admin/Extensions/Editors/EditModuleDefinition.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); + + // Module was incorrectly assigned as "IsPremium=False" + RemoveModuleFromPortals("Users And Roles"); } - public static int AddModuleToPage(string tabPath, int portalId, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + private static void UpgradeToVersion540() { - int moduleId = Null.NullInteger; + var configDoc = Config.Load(); + var configNavigator = configDoc.CreateNavigator().SelectSingleNode("/configuration/system.web.extensions"); + if (configNavigator == null) + { + // attempt to remove "System.Web.Extensions" configuration section + string upgradeFile = string.Format("{0}\\Config\\SystemWebExtensions.config", Globals.InstallMapPath); + string message = UpdateConfig(upgradeFile, ApplicationVersion, "Remove System.Web.Extensions"); + EventLogController.Instance.AddLog( + "UpgradeConfig", + string.IsNullOrEmpty(message) + ? "Remove System Web Extensions" + : string.Format("Remove System Web Extensions failed. Error reported during attempt to update:{0}", message), + PortalController.Instance.GetCurrentPortalSettings(), + UserController.Instance.GetCurrentUserInfo().UserID, + EventLogController.EventLogType.HOST_ALERT); + } + + // Add Styles Skin Object + AddSkinControl("TAGS", "DotNetNuke.TagsSkinObject", "Admin/Skins/Tags.ascx"); + + // Add Content List module definition + int moduleDefId = AddModuleDefinition("ContentList", "This module displays a list of content by tag.", "Content List"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ContentList/ContentList.ascx", string.Empty, SecurityAccessLevel.View, 0); - int tabID = TabController.GetTabByTabPath(portalId, tabPath, Null.NullString); - if (tabID != Null.NullInteger) + // Update registration page + ArrayList portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - TabInfo tab = TabController.Instance.GetTab(tabID, portalId, true); - if (tab != null) - { - moduleId = AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); - } - } + // objPortal.RegisterTabId = objPortal.UserTabId; + PortalController.Instance.UpdatePortalInfo(portal); - return moduleId; + // Add ContentList to Search Results Page + int tabId = TabController.GetTabByTabPath(portal.PortalID, "//SearchResults", Null.NullString); + TabInfo searchPage = TabController.Instance.GetTab(tabId, portal.PortalID, false); + AddModuleToPage(searchPage, moduleDefId, "Results", string.Empty); + } } - public static void AddModuleToPages(string tabPath, int moduleDefId, string moduleTitle, string moduleIconFile, bool inheritPermissions) + private static void UpgradeToVersion543() { - var portals = PortalController.Instance.GetPortals(); - foreach (PortalInfo portal in portals) + // get log file path + string logFilePath = DataProvider.Instance().GetProviderPath(); + if (Directory.Exists(logFilePath)) { - int tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if (tabID != Null.NullInteger) + // get log files + foreach (string fileName in Directory.GetFiles(logFilePath, "*.log")) { - var tab = TabController.Instance.GetTab(tabID, portal.PortalID, true); - if (tab != null) + if (File.Exists(fileName + ".resources")) { - AddModuleToPage(tab, moduleDefId, moduleTitle, moduleIconFile, inheritPermissions); + File.Delete(fileName + ".resources"); } + + // copy requires use of move + File.Move(fileName, fileName + ".resources"); } } } - /// ----------------------------------------------------------------------------- - /// - /// AddPortal manages the Installation of a new DotNetNuke Portal. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - public static int AddPortal(XmlNode node, bool status, int indent, UserInfo superUser = null) + private static void UpgradeToVersion550() { - int portalId = -1; - try - { - string hostMapPath = Globals.HostMapPath; - string childPath = string.Empty; - string domain = string.Empty; + // update languages module + int moduleDefId = GetModuleDefinition("Languages", "Languages"); + AddModuleControl(moduleDefId, "TranslationStatus", string.Empty, "DesktopModules/Admin/Languages/TranslationStatus.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0); - if (HttpContext.Current != null) - { - domain = Globals.GetDomainName(HttpContext.Current.Request, true).ToLowerInvariant().Replace("/install", string.Empty); - } + // due to an error in 5.3.0 we need to recheck and readd Application_Start_FirstRequest + AddEventQueueApplicationStartFirstRequest(); - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddPortal:" + domain); - string portalName = XmlUtils.GetNodeValue(node.CreateNavigator(), "portalname"); - if (status) + // check if UserProfile page template exists in Host folder and if not, copy it from Install folder + string installTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.InstallMapPath); + if (File.Exists(installTemplateFile)) + { + string hostTemplateFile = string.Format("{0}Templates\\UserProfile.page.template", Globals.HostMapPath); + if (!File.Exists(hostTemplateFile)) { - if (HttpContext.Current != null) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Site: " + portalName + "
    "); - } + File.Copy(installTemplateFile, hostTemplateFile); } + } - XmlNode adminNode = node.SelectSingleNode("administrator"); - if (adminNode != null) + // Fix the permission for User Folders + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + foreach (FolderInfo folder in FolderManager.Instance.GetFolders(portal.PortalID)) { - string firstName = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "firstname"); - string lastName = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "lastname"); - string username = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "username"); - string password = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "password"); - string email = XmlUtils.GetNodeValue(adminNode.CreateNavigator(), "email"); - string description = XmlUtils.GetNodeValue(node.CreateNavigator(), "description"); - string keyWords = XmlUtils.GetNodeValue(node.CreateNavigator(), "keywords"); - string templateFileName = XmlUtils.GetNodeValue(node.CreateNavigator(), "templatefile"); - string serverPath = Globals.ApplicationMapPath + "\\"; - bool isChild = bool.Parse(XmlUtils.GetNodeValue(node.CreateNavigator(), "ischild")); - string homeDirectory = XmlUtils.GetNodeValue(node.CreateNavigator(), "homedirectory"); - - // Get the Portal Alias - XmlNodeList portalAliases = node.SelectNodes("portalaliases/portalalias"); - string strPortalAlias = domain; - if (portalAliases != null) - { - if (portalAliases.Count > 0) - { - if (!string.IsNullOrEmpty(portalAliases[0].InnerText)) - { - strPortalAlias = portalAliases[0].InnerText; - } - } - } - - // Create default email - if (string.IsNullOrEmpty(email)) - { - email = "admin@" + domain.Replace("www.", string.Empty); - - // Remove any domain subfolder information ( if it exists ) - if (email.IndexOf("/") != -1) - { - email = email.Substring(0, email.IndexOf("/")); - } - } - - if (isChild) - { - childPath = PortalController.GetPortalFolder(strPortalAlias); - } - - var template = FindBestTemplate(templateFileName); - var userInfo = superUser ?? CreateUserInfo(firstName, lastName, username, password, email); - - // Create Portal - portalId = PortalController.Instance.CreatePortal( - portalName, - userInfo, - description, - keyWords, - template, - homeDirectory, - strPortalAlias, - serverPath, - serverPath + childPath, - isChild); - - if (portalId > -1) + if (folder.FolderPath.StartsWith("Users/")) { - // Add Extra Aliases - if (portalAliases != null) + foreach (PermissionInfo permission in PermissionController.GetPermissionsByFolder()) { - foreach (XmlNode portalAlias in portalAliases) + if (permission.PermissionKey.Equals("READ", StringComparison.InvariantCultureIgnoreCase)) { - if (!string.IsNullOrEmpty(portalAlias.InnerText)) + // Add All Users Read Access to the folder + int roleId = int.Parse(Globals.glbRoleAllUsers); + if (!folder.FolderPermissions.Contains(permission.PermissionKey, folder.FolderID, roleId, Null.NullInteger)) { - if (status) - { - if (HttpContext.Current != null) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Creating Site Alias: " + portalAlias.InnerText + "
    "); - } - } + var folderPermission = new FolderPermissionInfo(permission) { FolderID = folder.FolderID, UserID = Null.NullInteger, RoleID = roleId, AllowAccess = true }; - PortalController.Instance.AddPortalAlias(portalId, portalAlias.InnerText); + folder.FolderPermissions.Add(folderPermission); } } } - // 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); + FolderPermissionController.SaveFolderPermissions(folder); } + } - return portalId; + // Remove user page template from portal if it exists (from 5.3) + if (File.Exists(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath))) + { + File.Delete(string.Format("{0}Templates\\UserProfile.page.template", portal.HomeDirectoryMapPath)); } } - catch (Exception ex) + + // DNN-12894 - Country Code for "United Kingdom" is incorrect + var listController = new ListController(); + var listItem = listController.GetListEntryInfo("Country", "UK"); + if (listItem != null) { - Logger.Error(ex); + listItem.Value = "GB"; + listController.UpdateListEntry(listItem); + } - if (HttpContext.Current != null) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + // fix issue where portal default language may be disabled + string defaultLanguage = portal.DefaultLanguage; + if (!IsLanguageEnabled(portal.PortalID, defaultLanguage)) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, indent, "Error! " + ex.Message + ex.StackTrace + "
    "); - DnnInstallLogger.InstallLogError(ex); + Locale language = LocaleController.Instance.GetLocale(defaultLanguage); + Localization.AddLanguageToPortal(portal.PortalID, language.LanguageId, true); } - // failure - portalId = -1; + // preemptively create any missing localization records rather than relying on dynamic creation + foreach (Locale locale in LocaleController.Instance.GetLocales(portal.PortalID).Values) + { + DataProvider.Instance().EnsureLocalizationExists(portal.PortalID, locale.Code); + } } - - 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); } - public static string BuildUserTable(IDataReader dr, string header, string message) + private static void UpgradeToVersion560() { - string warnings = Null.NullString; - var stringBuilder = new StringBuilder(); - bool hasRows = false; + // Add .htmtemplate file extension + var toAdd = new List { ".htmtemplate" }; + HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); - stringBuilder.Append("

    " + header + "

    "); - stringBuilder.Append("

    " + message + "

    "); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - while (dr.Read()) - { - hasRows = true; - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - stringBuilder.Append(""); - } + // Add new Xml Merge module + int moduleDefId = AddModuleDefinition("Configuration Manager", string.Empty, "Configuration Manager", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/XmlMerge/XmlMerge.ascx", "~/images/icon_configuration_32px.png", SecurityAccessLevel.Host, 0); - stringBuilder.Append("
    IDUserNameFirst NameLast NameEmail
    " + dr.GetInt32(0) + "" + dr.GetString(1) + "" + dr.GetString(2) + "" + dr.GetString(3) + "" + dr.GetString(4) + "
    "); + // Add Module To Page + TabInfo hostPage = AddHostPage("Configuration Manager", "Modify configuration settings for your site", "~/images/icon_configuration_16px.png", "~/images/icon_configuration_32px.png", true); + AddModuleToPage(hostPage, moduleDefId, "Configuration Manager", "~/images/icon_configuration_32px.png"); - if (hasRows) - { - warnings = stringBuilder.ToString(); - } + // Update Google Analytics Script in SiteAnalysis.config + var googleAnalyticsController = new GoogleAnalyticsController(); + googleAnalyticsController.UpgradeModule("05.06.00"); - return warnings; + // Updated LanguageSettings.ascx control to be a Settings control + ModuleDefinitionInfo languageModule = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Languages"); + ModuleControlInfo moduleControl = ModuleControlController.GetModuleControlsByModuleDefinitionID(languageModule.ModuleDefID)["LanguageSettings"]; + moduleControl.ControlKey = "Settings"; + ModuleControlController.UpdateModuleControl(moduleControl); } - /// ----------------------------------------------------------------------------- - /// - /// CheckUpgrade checks whether there are any possible upgrade issues. - /// - /// - /// ----------------------------------------------------------------------------- - public static string CheckUpgrade() + private static void UpgradeToVersion562() { - DataProvider dataProvider = DataProvider.Instance(); - IDataReader dr; - string warnings = Null.NullString; + // Add new Photo Profile field to Host + var listController = new ListController(); + Dictionary dataTypes = listController.GetListEntryInfoDictionary("DataType"); - try - { - using (dr = dataProvider.ExecuteReader("CheckUpgrade")) - { - warnings = BuildUserTable(dr, "Duplicate SuperUsers", "We have detected that the following SuperUsers have duplicate entries as Portal Users. Although, no longer supported, these users may have been created in early Betas of DNN v3.0. You need to be aware that after the upgrade, these users will only be able to log in using the Super User Account's password."); + var properties = ProfileController.GetPropertyDefinitionsByPortal(Null.NullInteger); + ProfileController.AddDefaultDefinition(Null.NullInteger, "Preferences", "Photo", "Image", 0, (properties.Count * 2) + 2, UserVisibilityMode.AllUsers, dataTypes); - if (dr.NextResult()) - { - warnings += BuildUserTable(dr, "Duplicate Portal Users", "We have detected that the following Users have duplicate entries (they exist in more than one portal). You need to be aware that after the upgrade, the password for some of these users may have been automatically changed (as the system now only uses one password per user, rather than one password per user per portal). It is important to remember that your Users can always retrieve their password using the Password Reminder feature, which will be sent to the Email addess shown in the table."); - } - } - } - catch (SqlException ex) + HostController.Instance.Update("AutoAddPortalAlias", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); + + // remove the system message module from the admin tab + // System Messages are now managed through Localization + if (CoreModuleExists("System Messages")) { - Logger.Error(ex); - warnings += ex.Message; + RemoveCoreModule("System Messages", "Admin", "Site Settings", false); } - catch (Exception ex) + + // remove portal alias module + if (CoreModuleExists("PortalAliases")) { - Logger.Error(ex); - warnings += ex.Message; + RemoveCoreModule("PortalAliases", "Admin", "Site Settings", false); } - try + // add the log viewer module to the admin tab + int moduleDefId; + if (CoreModuleExists("LogViewer") == false) { - using (dr = dataProvider.ExecuteReader("GetUserCount")) - { - dr.Read(); - int userCount = dr.GetInt32(0); - - // ReSharper disable PossibleLossOfFraction - double time = userCount / 10834; + moduleDefId = AddModuleDefinition("LogViewer", "Allows you to view log entries for site events.", "Log Viewer"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/LogViewer/LogViewer.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Log Settings", "DesktopModules/Admin/LogViewer/EditLogTypes.ascx", string.Empty, SecurityAccessLevel.Host, 0); - // ReSharper restore PossibleLossOfFraction - if (userCount > 1000) - { - warnings += "

    More than 1000 Users

    This DotNetNuke Database has " + userCount + - " users. As the users and their profiles are transferred to a new format, it is estimated that the script will take ~" + time.ToString("F2") + - " minutes to execute.

    "; - } - } + // Add the Module/Page to all configured portals + AddAdminPages("Log Viewer", "View a historical log of database events such as event schedules, exceptions, account logins, module and page changes, user account activities, security role activities, etc.", "icon_viewstats_16px.gif", "icon_viewstats_32px.gif", true, moduleDefId, "Log Viewer", "icon_viewstats_16px.gif"); } - catch (Exception ex) + + // add the schedule module to the host tab + TabInfo newPage; + if (CoreModuleExists("Scheduler") == false) { - Logger.Error(ex); - warnings += Environment.NewLine + Environment.NewLine + ex.Message; - } + moduleDefId = AddModuleDefinition("Scheduler", "Allows you to schedule tasks to be run at specified intervals.", "Scheduler"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Scheduler/ViewSchedule.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddModuleControl(moduleDefId, "Edit", "Edit Schedule", "DesktopModules/Admin/Scheduler/EditSchedule.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "History", "Schedule History", "DesktopModules/Admin/Scheduler/ViewScheduleHistory.ascx", string.Empty, SecurityAccessLevel.Host, 0); + AddModuleControl(moduleDefId, "Status", "Schedule Status", "DesktopModules/Admin/Scheduler/ViewScheduleStatus.ascx", string.Empty, SecurityAccessLevel.Host, 0); - return warnings; - } + // Create New Host Page (or get existing one) + newPage = AddHostPage("Schedule", "Add, modify and delete scheduled tasks to be run at specified intervals.", "icon_scheduler_16px.gif", "icon_scheduler_32px.gif", true); - 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; - } + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, "Schedule", "icon_scheduler_16px.gif"); + } - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName, string currentCulture) - { - if (string.IsNullOrEmpty(currentCulture)) + // add the Search Admin module to the host tab + if (CoreModuleExists("SearchAdmin") == false) { - currentCulture = Localization.SystemLocale; - } + moduleDefId = AddModuleDefinition("SearchAdmin", "The Search Admininstrator provides the ability to manage search settings.", "Search Admin"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchAdmin/SearchAdmin.ascx", string.Empty, SecurityAccessLevel.Host, 0); - var templates = PortalController.Instance.GetAvailablePortalTemplates(); + // Create New Host Page (or get existing one) + newPage = AddHostPage("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "icon_search_16px.gif", "icon_search_32px.gif", true); - var defaultTemplates = - templates.Where(x => Path.GetFileName(x.TemplateFilePath) == templateFileName).ToList(); + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, "Search Admin", "icon_search_16px.gif"); + } - var match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant() == currentCulture); - if (match == null) + // add the Search Input module + if (CoreModuleExists("SearchInput") == false) { - match = defaultTemplates.FirstOrDefault(x => x.CultureCode.ToLowerInvariant().StartsWith(currentCulture.Substring(0, 2))); + moduleDefId = AddModuleDefinition("SearchInput", "The Search Input module provides the ability to submit a search to a given search results module.", "Search Input", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchInput/SearchInput.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Search Input Settings", "DesktopModules/Admin/SearchInput/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); } - if (match == null) + // add the Search Results module + if (CoreModuleExists("SearchResults") == false) { - match = defaultTemplates.FirstOrDefault(x => string.IsNullOrEmpty(x.CultureCode)); + moduleDefId = AddModuleDefinition("SearchResults", "The Search Reasults module provides the ability to display search results.", "Search Results", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SearchResults/SearchResults.ascx", string.Empty, SecurityAccessLevel.Anonymous, 0); + AddModuleControl(moduleDefId, "Settings", "Search Results Settings", "DesktopModules/Admin/SearchResults/Settings.ascx", string.Empty, SecurityAccessLevel.Edit, 0); + + // Add the Search Module/Page to all configured portals + AddSearchResults(moduleDefId); } - if (match == null) + // add the site wizard module to the admin tab + if (CoreModuleExists("SiteWizard") == false) { - throw new Exception("Unable to locate specified portal template: " + templateFileName); + moduleDefId = AddModuleDefinition("SiteWizard", "The Administrator can use this user-friendly wizard to set up the common Extensions of the Portal/Site.", "Site Wizard"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/SiteWizard/Sitewizard.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddAdminPages("Site Wizard", "Configure portal settings, page design and apply a site template using a step-by-step wizard.", "icon_wizard_16px.gif", "icon_wizard_32px.gif", true, moduleDefId, "Site Wizard", "icon_wizard_16px.gif"); } - return match; - } + // add Lists module and tab + if (HostTabExists("Lists") == false) + { + moduleDefId = AddModuleDefinition("Lists", "Allows you to edit common lists.", "Lists"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Lists/ListEditor.ascx", string.Empty, SecurityAccessLevel.Host, 0); - internal static PortalController.PortalTemplateInfo FindBestTemplate(string templateFileName) - { - // Load Template - var installTemplate = new XmlDocument { XmlResolver = null }; - Upgrade.GetInstallTemplate(installTemplate); + // Create New Host Page (or get existing one) + newPage = AddHostPage("Lists", "Manage common lists.", "icon_lists_16px.gif", "icon_lists_32px.gif", true); - // Parse the root node - XmlNode rootNode = installTemplate.SelectSingleNode("//dotnetnuke"); - string currentCulture = string.Empty; - if (rootNode != null) - { - currentCulture = XmlUtils.GetNodeValue(rootNode.CreateNavigator(), "installCulture"); + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, "Lists", "icon_lists_16px.gif"); } - if (string.IsNullOrEmpty(currentCulture)) + if (HostTabExists("Superuser Accounts") == false) { - currentCulture = Localization.SystemLocale; + // add SuperUser Accounts module and tab + DesktopModuleInfo objDesktopModuleInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); + moduleDefId = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", objDesktopModuleInfo.DesktopModuleID).ModuleDefID; + + // Create New Host Page (or get existing one) + newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", "icon_users_16px.gif", "icon_users_32px.gif", true); + + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "icon_users_32px.gif"); } - currentCulture = currentCulture.ToLowerInvariant(); + // Add Edit Role Groups + moduleDefId = GetModuleDefinition("Security", "Security Roles"); + AddModuleControl(moduleDefId, "EditGroup", "Edit Role Groups", "DesktopModules/Admin/Security/EditGroups.ascx", "icon_securityroles_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); + AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); - return FindBestTemplate(templateFileName, currentCulture); - } + // Add User Accounts Controls + moduleDefId = GetModuleDefinition("Security", "User Accounts"); + AddModuleControl(moduleDefId, "ManageProfile", "Manage Profile Definition", "DesktopModules/Admin/Security/ProfileDefinitions.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); + AddModuleControl(moduleDefId, "EditProfileProperty", "Edit Profile Property Definition", "DesktopModules/Admin/Security/EditProfileDefinition.ascx", "icon_users_32px.gif", SecurityAccessLevel.Edit, Null.NullInteger); + AddModuleControl(moduleDefId, "UserSettings", "Manage User Settings", "DesktopModules/Admin/Security/UserSettings.ascx", "~/images/settings.gif", SecurityAccessLevel.Edit, Null.NullInteger); + AddModuleControl(Null.NullInteger, "Profile", "Profile", "DesktopModules/Admin/Security/ManageUsers.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); + AddModuleControl(Null.NullInteger, "SendPassword", "Send Password", "DesktopModules/Admin/Security/SendPassword.ascx", string.Empty, SecurityAccessLevel.Anonymous, Null.NullInteger); + AddModuleControl(Null.NullInteger, "ViewProfile", "View Profile", "DesktopModules/Admin/Security/ViewProfile.ascx", "icon_users_32px.gif", SecurityAccessLevel.Anonymous, Null.NullInteger); - /// ----------------------------------------------------------------------------- - /// - /// DeleteInstallerFiles - clean up install config and installwizard files - /// If installwizard is ran again this will be recreated via the dotnetnuke.install.config.resources file. - /// - /// - /// uses FileSystemUtils.DeleteFile as it checks for readonly attribute status - /// and changes it if required, as well as verifying file exists. - /// - /// ----------------------------------------------------------------------------- - public static void DeleteInstallerFiles() - { - var files = new List - { - "DotNetNuke.install.config", - "DotNetNuke.install.config.resources", - "InstallWizard.aspx", - "InstallWizard.aspx.cs", - "InstallWizard.aspx.designer.cs", - "UpgradeWizard.aspx", - "UpgradeWizard.aspx.cs", - "UpgradeWizard.aspx.designer.cs", - "Install.aspx", - "Install.aspx.cs", - "Install.aspx.designer.cs", - }; + // Update Child Portal subHost.aspx + UpdateChildPortalsDefaultPage(); - foreach (var file in files) + // add the solutions explorer module to the admin tab + if (CoreModuleExists("Solutions") == false) { - try - { - FileSystemUtils.DeleteFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Install", file)); - } - catch (Exception ex) - { - Logger.Error("File deletion failed for [Install\\" + file + "]. PLEASE REMOVE THIS MANUALLY." + ex); - } + moduleDefId = AddModuleDefinition("Solutions", "Browse additional solutions for your application.", "Solutions", false, false); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/Solutions/Solutions.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddAdminPages("Solutions", "DotNetNuke Solutions Explorer page provides easy access to locate free and commercial DotNetNuke modules, skin and more.", "icon_solutions_16px.gif", "icon_solutions_32px.gif", true, moduleDefId, "Solutions Explorer", "icon_solutions_32px.gif"); } + + // Add Search Skin Object + AddSkinControl("SEARCH", "DotNetNuke.SearchSkinObject", "Admin/Skins/Search.ascx"); + + // Add TreeView Skin Object + AddSkinControl("TREEVIEW", "DotNetNuke.TreeViewSkinObject", "Admin/Skins/TreeViewMenu.ascx"); + + // Add Text Skin Object + AddSkinControl("TEXT", "DotNetNuke.TextSkinObject", "Admin/Skins/Text.ascx"); + + // Add Styles Skin Object + AddSkinControl("STYLES", "DotNetNuke.StylesSkinObject", "Admin/Skins/Styles.ascx"); } - /// ----------------------------------------------------------------------------- - /// - /// DeleteFiles - clean up deprecated files and folders. - /// - /// - /// - /// Path to provider. - /// The Version being Upgraded. - /// Display status in UI?. - /// - /// ----------------------------------------------------------------------------- - public static string DeleteFiles(string providerPath, Version version, bool writeFeedback) + private static void UpgradeToVersion600() { - var stringVersion = GetStringVersionWithRevision(version); + var hostPages = TabController.Instance.GetTabsByPortal(Null.NullInteger); - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "DeleteFiles:" + stringVersion); - string exceptions = string.Empty; - if (writeFeedback) + // This ensures that all host pages have a tab path. + // so they can be found later. (DNNPRO-17129) + foreach (var hostPage in hostPages.Values) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Cleaning Up Files: " + stringVersion); + hostPage.TabPath = Globals.GenerateTabPath(hostPage.ParentId, hostPage.TabName); + TabController.Instance.UpdateTab(hostPage); } - string listFile = Globals.InstallMapPath + "Cleanup\\" + stringVersion + ".txt"; - try + var settings = PortalController.Instance.GetCurrentPortalSettings(); + + if (settings != null) { - if (File.Exists(listFile)) + var hostTab = TabController.Instance.GetTab(settings.SuperTabId, Null.NullInteger, false); + hostTab.IsVisible = false; + TabController.Instance.UpdateTab(hostTab); + foreach (var module in ModuleController.Instance.GetTabModules(settings.SuperTabId).Values) { - exceptions = FileSystemUtils.DeleteFiles(File.ReadAllLines(listFile)); + ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "hideadminborder", "true"); } } - catch (Exception ex) + + // remove timezone editor + int moduleDefId = GetModuleDefinition("Languages", "Languages"); + RemoveModuleControl(moduleDefId, "TimeZone"); + + // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Host + ProfilePropertyDefinition ppdHostTimeZone = ProfileController.GetPropertyDefinitionByName(Null.NullInteger, "TimeZone"); + if (ppdHostTimeZone != null) { - Logger.Error("Error cleanup file " + listFile, ex); + ProfileController.DeletePropertyDefinition(ppdHostTimeZone); + } - exceptions += $"Error: {ex.Message + ex.StackTrace}{Environment.NewLine}"; + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + // update timezoneinfo +#pragma warning disable 612,618 + TimeZoneInfo timeZoneInfo = Localization.ConvertLegacyTimeZoneOffsetToTimeZoneInfo(portal.TimeZoneOffset); +#pragma warning restore 612,618 + PortalController.UpdatePortalSetting(portal.PortalID, "TimeZone", timeZoneInfo.Id, false); - // log the results - DnnInstallLogger.InstallLogError(exceptions); - try + // 6.0 requires the old TimeZone property to be marked as Deleted - Delete for Portals + ProfilePropertyDefinition ppdTimeZone = ProfileController.GetPropertyDefinitionByName(portal.PortalID, "TimeZone"); + if (ppdTimeZone != null) { - using (StreamWriter streamWriter = File.CreateText(providerPath + stringVersion + "_Config.log")) - { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); - } + ProfileController.DeletePropertyDefinition(ppdTimeZone); } - catch (Exception exc) + + var adminTab = TabController.Instance.GetTab(portal.AdminTabId, portal.PortalID, false); + + adminTab.IsVisible = false; + TabController.Instance.UpdateTab(adminTab); + + foreach (var module in ModuleController.Instance.GetTabModules(portal.AdminTabId).Values) { - Logger.Error(exc); + ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "hideadminborder", "true"); } } - if (writeFeedback) + // Ensure that Display Beta Notice setting is present + var displayBetaNotice = Host.DisplayBetaNotice; + HostController.Instance.Update("DisplayBetaNotice", displayBetaNotice ? "Y" : "N"); + + moduleDefId = GetModuleDefinition("Languages", "Languages"); + AddModuleControl(moduleDefId, "EnableContent", "Enable Localized Content", "DesktopModules/Admin/Languages/EnableLocalizedContent.ascx", string.Empty, SecurityAccessLevel.Host, 0, null, false); + + AddDefaultModuleIcons(); + + AddIconToAllowedFiles(); + + FavIconsToPortalSettings(); + + var tab = TabController.Instance.GetTabByName("Host", Null.NullInteger, Null.NullInteger); + + if (tab != null) { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); + RemoveModule("Extensions", "Module Definitions", tab.TabID, true); + RemoveModule("Marketplace", "Marketplace", tab.TabID, true); } - - return exceptions; } - /// ----------------------------------------------------------------------------- - /// - /// ExecuteScripts manages the Execution of Scripts from the Install/Scripts folder. - /// It is also triggered by InstallDNN and UpgradeDNN. - /// - /// - /// - /// The path to the Data Provider. - /// ----------------------------------------------------------------------------- - public static void ExecuteScripts(string strProviderPath) + private static void UpgradeToVersion601() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ExecuteScripts:" + strProviderPath); - string scriptPath = Globals.ApplicationMapPath + "\\Install\\Scripts\\"; - if (Directory.Exists(scriptPath)) + // List module needs to be available to Portals also + var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Lists"); + if (pkg != null) { - string[] files = Directory.GetFiles(scriptPath); - foreach (string file in files) + // List package is no longer a system package + pkg.IsSystemPackage = false; + PackageController.Instance.SaveExtensionPackage(pkg); + + // List desktop module is no longer premium or admin module + var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(pkg.PackageID); + desktopModule.IsAdmin = false; + desktopModule.IsPremium = false; + DesktopModuleController.SaveDesktopModule(desktopModule, false, true); + + var permissionController = new PermissionController(); + ArrayList permissions = permissionController.GetPermissionByCodeAndKey("SYSTEM_DESKTOPMODULE", "DEPLOY"); + if (permissions.Count == 1) { - // Execute if script is a provider script - if (file.IndexOf("." + DefaultProvider) != -1) + var permission = permissions[0] as PermissionInfo; + if (permission != null) { - ExecuteScript(file, true); - - // delete the file - try - { - File.SetAttributes(file, FileAttributes.Normal); - File.Delete(file); - } - catch (Exception exc) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - Logger.Error(exc); + // ensure desktop module is not present in the portal + var pdmi = DesktopModuleController.GetPortalDesktopModule(portal.PortalID, desktopModule.DesktopModuleID); + if (pdmi == null) + { + // Parse the permissions + var deployPermissions = new DesktopModulePermissionCollection(); + var deployPermission = new DesktopModulePermissionInfo { PermissionID = permission.PermissionID, AllowAccess = true, RoleID = portal.AdministratorRoleId }; + deployPermissions.Add(deployPermission); + + // Add Portal/Module to PortalDesktopModules + DesktopModuleController.AddDesktopModuleToPortal(portal.PortalID, desktopModule, deployPermissions, true); + } } } } } } - /// ----------------------------------------------------------------------------- - /// - /// ExecuteScript executes a special script. - /// - /// - /// - /// The script file to execute. - /// ----------------------------------------------------------------------------- - public static void ExecuteScript(string file) + private static void UpgradeToVersion602() { - // Execute if script is a provider script - if (file.IndexOf("." + DefaultProvider) != -1) + // Add avi,mpg,mpeg,mp3,wmv,mov,wav extensions + var exts = new List { ".avi", ".mpg", ".mpeg", ".mp3", ".wmv", ".mov", ".wav" }; + HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(exts)); + + // Fix the icons for SiteMap page + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - ExecuteScript(file, true); + var siteMap = TabController.Instance.GetTabByName("Search Engine SiteMap", portal.PortalID); + + if (siteMap != null) + { + siteMap.IconFile = "~/Icons/Sigma/Sitemap_16X16_Standard.png"; + siteMap.IconFileLarge = "~/Icons/Sigma/Sitemap_32X32_Standard.png"; + TabController.Instance.UpdateTab(siteMap); + } } } - private static string GetStringVersionWithRevision(Version version) + private static void UpgradeToVersion610() { - var stringVersion = GetStringVersion(version); - if (version.Revision > 0) - { - stringVersion += "." + version.Revision.ToString("D2"); - } + AddModuleCategories(); - return stringVersion; - } + // update languages module + int moduleDefId = GetModuleDefinition("Languages", "Languages"); + AddModuleControl(moduleDefId, "LocalizePages", "Localize Pages", "DesktopModules/Admin/Languages/LocalizePages.ascx", "~/images/icon_language_32px.gif", SecurityAccessLevel.Edit, 0, Null.NullString, true); - /// ----------------------------------------------------------------------------- - /// - /// GetInstallTemplate retrieves the Installation Template as specifeid in web.config. - /// - /// - /// - /// The Xml Document to load. - /// A string which contains the error message - if appropriate. - /// ----------------------------------------------------------------------------- - public static string GetInstallTemplate(XmlDocument xmlDoc) - { - string errorMessage = Null.NullString; - string installTemplate = Config.GetSetting("InstallTemplate"); - try - { - xmlDoc.Load(Globals.ApplicationMapPath + "\\Install\\" + installTemplate); - } - catch - { - // error - errorMessage = "Failed to load Install template.

    "; - } + // add store control + moduleDefId = AddModuleDefinition("Extensions", string.Empty, "Extensions"); + AddModuleControl(moduleDefId, "Store", "Store Details", "DesktopModules/Admin/Extensions/Store.ascx", "~/images/icon_extensions_32px.png", SecurityAccessLevel.Host, 0); - return errorMessage; - } + EnableModalPopUps(); - /// - /// SetInstalltemplate saves the XmlDocument back to Installation Template specified in web.config. - /// - /// The Xml Document to save. - /// A string which contains the error massage - if appropriate. - public static string SetInstallTemplate(XmlDocument xmlDoc) - { - string errorMessage = Null.NullString; - string installTemplate = Config.GetSetting("InstallTemplate"); - string filePath = Globals.ApplicationMapPath + "\\Install\\" + installTemplate; - try + var tab = TabController.Instance.GetTabByName("Portals", Null.NullInteger); + tab.TabName = "Site Management"; + TabController.Instance.UpdateTab(tab); + + foreach (var module in ModuleController.Instance.GetTabModules(tab.TabID).Values) { - // ensure the file is not read-only - var attributes = File.GetAttributes(filePath); - if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + if (module.ModuleTitle == "Portals") { - // file is readonly, then remove it - attributes = attributes & ~FileAttributes.ReadOnly; - File.SetAttributes(filePath, attributes); + module.ModuleTitle = "Site Management"; + ModuleController.Instance.UpdateModule(module); } + } - xmlDoc.Save(filePath); + // Add List module to Admin page of every portal + ModuleDefinitionInfo mDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Lists"); + if (mDef != null) + { + AddAdminPages( + "Lists", + "Manage common lists", + "~/Icons/Sigma/Lists_16X16_Standard.png", + "~/Icons/Sigma/Lists_32X32_Standard.png", + true, + mDef.ModuleDefID, + "Lists", + "~/Icons/Sigma/Lists_16X16_Standard.png", + true); } - catch + + // update DotNetNuke.Portals' friend name to 'Sites'. + var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); + if (portalPackage != null) { - // error - errorMessage = "Failed to save Install template.

    "; + portalPackage.FriendlyName = "Sites"; + PackageController.Instance.SaveExtensionPackage(portalPackage); } - return errorMessage; + // add mobile preview control + AddModuleControl(Null.NullInteger, "MobilePreview", "Mobile Preview", "DesktopModules/Admin/MobilePreview/Preview.ascx", string.Empty, SecurityAccessLevel.Admin, Null.NullInteger); } - /// ----------------------------------------------------------------------------- - /// - /// GetInstallVersion retrieves the Base Instal Version as specifeid in the install - /// template. - /// - /// - /// - /// The Install Template. - /// - /// ----------------------------------------------------------------------------- - public static Version GetInstallVersion(XmlDocument xmlDoc) + private static void UpgradeToVersion612() { - string version = Null.NullString; + // update DotNetNuke.Portals' friend name to 'Sites'. + var portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Portals"); + if (portalPackage != null) + { + portalPackage.FriendlyName = "Site Management"; + portalPackage.Description = + "The Super User can manage the various parent and child sites within the install instance. This module allows you to add a new site, modify an existing site, and delete a site."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } - // get base version - XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke"); - if (node != null) + // update 'Portal' to 'Sites' in package description. + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Tabs"); + if (portalPackage != null) { - version = XmlUtils.GetNodeValue(node.CreateNavigator(), "version"); + portalPackage.Description = + "Administrators can manage the Pages within the site. This module allows you to create a new page, modify an existing page, delete pages, change the page order, and change the hierarchical page level."; + PackageController.Instance.SaveExtensionPackage(portalPackage); } - return new Version(version); - } + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Vendors"); + if (portalPackage != null) + { + portalPackage.Description = + "Administrators can manage the Vendors and Banners associated to the site. This module allows you to add a new vendor, modify an existing vendor, and delete a vendor."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } - /// ----------------------------------------------------------------------------- - /// - /// GetLogFile gets the filename for the version's log file. - /// - /// - /// - /// The path to the Data Provider. - /// The Version. - /// - /// ----------------------------------------------------------------------------- - public static string GetLogFile(string providerPath, Version version) - { - return providerPath + GetStringVersion(version) + ".log.resources"; - } + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteLog"); + if (portalPackage != null) + { + portalPackage.Description = + "Administrators can view the details of visitors using their site. There are a variety of reports available to display information regarding site usage, membership, and volumes."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } - /// ----------------------------------------------------------------------------- - /// - /// GetScriptFile gets the filename for the version. - /// - /// - /// - /// The path to the Data Provider. - /// The Version. - /// - /// ----------------------------------------------------------------------------- - public static string GetScriptFile(string providerPath, Version version) - { - return providerPath + GetStringVersion(version) + "." + DefaultProvider; - } + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteWizard"); + if (portalPackage != null) + { + portalPackage.Description = + "The Administrator can use this user-friendly wizard to set up the common features of the site."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } - /// ----------------------------------------------------------------------------- - /// - /// GetStringVersion gets the Version String (xx.xx.xx) from the Version. - /// - /// - /// - /// The Version. - /// - /// ----------------------------------------------------------------------------- - public static string GetStringVersion(Version version) - { - var versionArray = new int[3]; - versionArray[0] = version.Major; - versionArray[1] = version.Minor; - versionArray[2] = version.Build; - string stringVersion = Null.NullString; - for (int i = 0; i <= 2; i++) + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Security"); + if (portalPackage != null) { - if (versionArray[i] == 0) - { - stringVersion += "00"; - } - else if (versionArray[i] >= 1 && versionArray[i] <= 9) - { - stringVersion += "0" + versionArray[i]; - } - else - { - stringVersion += versionArray[i].ToString(); - } + portalPackage.Description = + "Administrators can manage the security roles defined for their site. The module allows you to add new security roles, modify existing security roles, delete security roles, and manage the users assigned to security roles."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } - if (i < 2) - { - stringVersion += "."; - } + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.LogViewer"); + if (portalPackage != null) + { + portalPackage.Description = + "Allows you to view log entries for site events."; + PackageController.Instance.SaveExtensionPackage(portalPackage); } - return stringVersion; + portalPackage = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Google Analytics"); + if (portalPackage != null) + { + portalPackage.Description = + "Configure Site Google Analytics settings."; + PackageController.Instance.SaveExtensionPackage(portalPackage); + } } - /// ----------------------------------------------------------------------------- - /// - /// GetSuperUser gets the superuser from the Install Template. - /// - /// - /// - /// The install Templae. - /// a flag to determine whether to output feedback. - /// - /// ----------------------------------------------------------------------------- - public static UserInfo GetSuperUser(XmlDocument xmlTemplate, bool writeFeedback) + private static void UpgradeToVersion613() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "GetSuperUser"); - XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/superuser"); - UserInfo superUser = null; - if (node != null) + // Rename admin pages page's title to 'Page Management'. + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Configuring SuperUser:
    "); - } - - // Parse the SuperUsers nodes - string firstName = XmlUtils.GetNodeValue(node.CreateNavigator(), "firstname"); - string lastName = XmlUtils.GetNodeValue(node.CreateNavigator(), "lastname"); - string username = XmlUtils.GetNodeValue(node.CreateNavigator(), "username"); - string password = XmlUtils.GetNodeValue(node.CreateNavigator(), "password"); - string email = XmlUtils.GetNodeValue(node.CreateNavigator(), "email"); - string locale = XmlUtils.GetNodeValue(node.CreateNavigator(), "locale"); - string updatePassword = XmlUtils.GetNodeValue(node.CreateNavigator(), "updatepassword"); - - superUser = new UserInfo - { - PortalID = -1, - FirstName = firstName, - LastName = lastName, - Username = username, - DisplayName = firstName + " " + lastName, - Membership = { Password = password }, - Email = email, - IsSuperUser = true, - }; - superUser.Membership.Approved = true; - - superUser.Profile.FirstName = firstName; - superUser.Profile.LastName = lastName; - superUser.Profile.PreferredLocale = locale; - superUser.Profile.PreferredTimeZone = TimeZoneInfo.Local; + var pagesTabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin//Pages", Null.NullString); - if (updatePassword.ToLowerInvariant() == "true") + if (pagesTabId != Null.NullInteger) { - superUser.Membership.UpdatePassword = true; + var pagesTab = TabController.Instance.GetTab(pagesTabId, portal.PortalID, false); + if (pagesTab != null && pagesTab.Title == "Pages") + { + pagesTab.Title = "Page Management"; + TabController.Instance.UpdateTab(pagesTab); + } } } - - return superUser; } - /// ----------------------------------------------------------------------------- - /// - /// GetUpgradeScripts gets an ArrayList of the Scripts required to Upgrade to the - /// current Assembly Version. - /// - /// - /// - /// The path to the Data Provider. - /// The current Database Version. - /// - /// ----------------------------------------------------------------------------- - public static ArrayList GetUpgradeScripts(string providerPath, Version databaseVersion) + private static void UpgradeToVersion620() { - var scriptFiles = new ArrayList(); - string[] files = Directory.GetFiles(providerPath, "*." + DefaultProvider); - Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. + // add host (system) profanityfilter list + const string listName = "ProfanityFilter"; + var listController = new ListController(); + var entry = new ListEntryInfo(); + { + entry.DefinitionID = Null.NullInteger; + entry.PortalID = Null.NullInteger; + entry.ListName = listName; + entry.Value = "ReplaceWithNothing"; + entry.Text = "FindThisText"; + entry.SystemList = true; + } - Logger.TraceFormat("GetUpgradedScripts databaseVersion:{0} applicationVersion:{1}", databaseVersion, ApplicationVersion); + listController.AddListEntry(entry); - foreach (string file in files) + // add same list to each portal + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - // script file name must conform to ##.##.##.DefaultProviderName - if (file != null) - { - if (GetFileName(file).Length == 9 + DefaultProvider.Length) - { - var version = new Version(GetFileNameWithoutExtension(file)); + entry.PortalID = portal.PortalID; + entry.SystemList = false; + entry.ListName = listName + "-" + portal.PortalID; + listController.AddListEntry(entry); - // check if script file is relevant for upgrade - if (version > databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) - { - scriptFiles.Add(file); + // also create default social relationship entries for the portal + RelationshipController.Instance.CreateDefaultRelationshipsForPortal(portal.PortalID); + } - // check if any incrementals exist - var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); - if (incrementalfiles != null) - { - scriptFiles.AddRange(incrementalfiles); - } + // Convert old Messages to new schema + ConvertOldMessages(); - Logger.TraceFormat("GetUpgradedScripts including {0}", file); - } + // Replace old Messaging module on User Profile with new + ReplaceMessagingModule(); - if (version == databaseVersion && version <= ApplicationVersion && GetFileName(file).Length == 9 + DefaultProvider.Length) - { - var incrementalfiles = AddAvailableIncrementalFiles(providerPath, version); - if (incrementalfiles != null) - { - scriptFiles.AddRange(incrementalfiles); - } + // Move Photo Property to the end of the propert list. + MovePhotoProperty(); - Logger.TraceFormat("GetUpgradedScripts including {0}", file); - } + // Update Child Portal's Default Page + UpdateChildPortalsDefaultPage(); - // else - // { - // Logger.TraceFormat("GetUpgradedScripts excluding {0}", file); - // } - } - } - } + // Add core notification types + AddCoreNotificationTypesFor620(); - return scriptFiles; + // Console module should not be IPortable + var consoleModule = DesktopModuleController.GetDesktopModuleByModuleName("Console", Null.NullInteger); + consoleModule.SupportedFeatures = 0; + consoleModule.BusinessControllerClass = string.Empty; + DesktopModuleController.SaveDesktopModule(consoleModule, false, false); } - /// ----------------------------------------------------------------------------- - /// - /// InitialiseHostSettings gets the Host Settings from the Install Template. - /// - /// - /// - /// The install Templae. - /// a flag to determine whether to output feedback. - /// ----------------------------------------------------------------------------- - public static void InitialiseHostSettings(XmlDocument xmlTemplate, bool writeFeedback) + private static void UpgradeToVersion621() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InitialiseHostSettings"); - XmlNode node = xmlTemplate.SelectSingleNode("//dotnetnuke/settings"); - if (node != null) + // update administrators' role description. + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - if (writeFeedback) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Settings:
    "); - } - - // Need to clear the cache to pick up new HostSettings from the SQLDataProvider script - DataCache.RemoveCache(DataCache.HostSettingsCacheKey); - - // Parse the Settings nodes - foreach (XmlNode settingNode in node.ChildNodes) + // update about me's template + var myProfileTabId = TabController.GetTabByTabPath(portal.PortalID, "//ActivityFeed//MyProfile", string.Empty); + if (myProfileTabId != Null.NullInteger) { - string settingName = settingNode.Name; - string settingValue = settingNode.InnerText; - if (settingNode.Attributes != null) + var tabModules = ModuleController.Instance.GetTabModules(myProfileTabId); + foreach (var module in tabModules.Values) { - XmlAttribute secureAttrib = settingNode.Attributes["Secure"]; - bool settingIsSecure = false; - if (secureAttrib != null) + var settings = module.TabModuleSettings; + if (settings.ContainsKey("ProfileTemplate") && settings["ProfileTemplate"].ToString().Contains("
    ")) { - if (secureAttrib.Value.ToLowerInvariant() == "true") - { - settingIsSecure = true; - } + var template = @"
    +

    + +

    +
    +
    +

    + +

    0"">
    + 0"">
    + 0"">
    + +

    +
    +
    +

    + +
      +
    • 0"">:
    • +
    • 0"">:
    • +
    • 0"">:
    • +
    • 0"">:
    • +
    +
    +
    "; + ModuleController.Instance.UpdateTabModuleSetting(module.TabModuleID, "ProfileTemplate", template); } + } + } + } + } - string domainName = Globals.GetDomainName(HttpContext.Current.Request); + private static void UpgradeToVersion623() + { +#pragma warning disable 618 + if (Host.jQueryUrl == "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js") + { + HostController.Instance.Update("jQueryUrl", jQuery.DefaultHostedUrl); + } - switch (settingName) - { - case "HostURL": - if (string.IsNullOrEmpty(settingValue)) - { - settingValue = domainName; - } + if (Host.jQueryUIUrl == "http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js") + { + HostController.Instance.Update("jQueryUIUrl", jQuery.DefaultUIHostedUrl); + } +#pragma warning restore 618 + } - break; - case "HostEmail": - if (string.IsNullOrEmpty(settingValue)) - { - settingValue = "support@" + domainName; + private static void UpgradeToVersion624() + { + UninstallPackage("DotNetNuke.MarketPlace", "Module"); + } - // Remove any folders - settingValue = settingValue.Substring(0, settingValue.IndexOf("/")); + private static void UpgradeToVersion700() + { + // add the site Advanced Settings module to the admin tab + if (CoreModuleExists("AdvancedSettings") == false) + { + var moduleDefId = AddModuleDefinition("AdvancedSettings", string.Empty, "Advanced Settings"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/AdvancedSettings/AdvancedSettings.ascx", string.Empty, SecurityAccessLevel.Admin, 0); + AddAdminPages( + "Advanced Settings", + string.Empty, + "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png", + "~/Icons/Sigma/AdvancedSettings_32X32_Standard.png", + true, + moduleDefId, + "Advanced Settings", + "~/Icons/Sigma/AdvancedSettings_16X16_Standard.png"); + } - // Remove port number - if (settingValue.IndexOf(":") != -1) - { - settingValue = settingValue.Substring(0, settingValue.IndexOf(":")); - } - } + ConvertCoreNotificationTypeActionsFor700(); - break; - } + // Remove Feed Explorer module + DesktopModuleController.DeleteDesktopModule("FeedExplorer"); + DesktopModuleController.DeleteDesktopModule("Solutions"); - HostController.Instance.Update(settingName, settingValue, settingIsSecure); - } - } - } + // Register Newtonsoft assembly + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Newtonsoft.Json.dll", "4.5.6"); + + // subhost.aspx was updated + UpdateChildPortalsDefaultPage(); } - /// ----------------------------------------------------------------------------- - /// - /// InstallDatabase runs all the "scripts" identifed in the Install Template to - /// install the base version. - /// - /// - /// - /// - /// The Xml Document to load. - /// A flag that determines whether to output feedback to the Response Stream. - /// - /// A string which contains the error message - if appropriate. - /// ----------------------------------------------------------------------------- - public static string InstallDatabase(Version version, string providerPath, XmlDocument xmlDoc, bool writeFeedback) + private static void UpgradeToVersion710() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDatabase:" + Globals.FormatVersion(version)); - string defaultProvider = Config.GetDefaultProvider("data").Name; - string message = Null.NullString; + // create a placeholder entry - uses the most common 5 character password (seed list is 6 characters and above) + const string listName = "BannedPasswords"; + var listController = new ListController(); + var entry = new ListEntryInfo(); + { + entry.DefinitionID = Null.NullInteger; + entry.PortalID = Null.NullInteger; + entry.ListName = listName; + entry.Value = "12345"; + entry.Text = "Placeholder"; + entry.SystemList = false; + } - // Output feedback line - if (writeFeedback) + // add list to each portal and update primary alias + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Version: " + Globals.FormatVersion(version) + "
    "); + entry.PortalID = portal.PortalID; + entry.SystemList = false; + entry.ListName = listName + "-" + portal.PortalID; + listController.AddListEntry(entry); + + var defaultAlias = PortalController.GetPortalSetting("DefaultPortalAlias", portal.PortalID, string.Empty); + if (!string.IsNullOrEmpty(defaultAlias)) + { + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(portal.PortalID).Where(alias => alias.HTTPAlias == defaultAlias)) + { + alias.IsPrimary = true; + PortalAliasController.Instance.UpdatePortalAlias(alias); + } + } } - // Parse the script nodes - XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/scripts"); - if (node != null) + // Add File Content Type + var typeController = new ContentTypeController(); + var contentTypeFile = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); + + if (contentTypeFile == null) { - // Loop through the available scripts - message = (from XmlNode scriptNode in node.SelectNodes("script") select scriptNode.InnerText + "." + defaultProvider).Aggregate(message, (current, script) => current + ExecuteScript(providerPath + script, writeFeedback)); + typeController.AddContentType(new ContentType { ContentType = "File" }); } - // update the version - Globals.UpdateDataBaseVersion(version); - - // Optionally Install the memberRoleProvider - message += InstallMemberRoleProvider(providerPath, writeFeedback); - - return message; - } + var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) - { - if (version.Major < 8) + // only perform following for an existing installation upgrading + if (Globals.Status == Globals.UpgradeStatus.Upgrade) { - return null; + UpdateFoldersForParentId(); + ImportDocumentLibraryCategories(); + ImportDocumentLibraryCategoryAssoc(fileContentType); } - 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. - /// - /// - /// - /// The path to the Data Provider. - /// ----------------------------------------------------------------------------- - public static void InstallDNN(string strProviderPath) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallDNN:" + strProviderPath); - var xmlDoc = new XmlDocument { XmlResolver = null }; - - // open the Install Template XML file - string errorMessage = GetInstallTemplate(xmlDoc); - - if (string.IsNullOrEmpty(errorMessage)) + // Add 404 Log + var logTypeInfo = new LogTypeInfo { - // get base version - Version baseVersion = GetInstallVersion(xmlDoc); + 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); - // Install Base Version - InstallDatabase(baseVersion, strProviderPath, xmlDoc, true); + // 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); - // Call Upgrade with the current DB Version to carry out any incremental upgrades - UpgradeDNN(strProviderPath, baseVersion); + UninstallPackage("DotNetNuke.SearchInput", "Module"); - // parse Host Settings if available - InitialiseHostSettings(xmlDoc, true); + // enable password strength meter for new installs only + HostController.Instance.Update("EnableStrengthMeter", Globals.Status == Globals.UpgradeStatus.Install ? "Y" : "N"); - // Create SuperUser only when it's not there (even soft deleted) - var superUsers = UserController.GetUsers(true, true, Null.NullInteger); - if (superUsers == null || superUsers.Count == 0) - { - // parse SuperUser if Available - UserInfo superUser = GetSuperUser(xmlDoc, true); - UserController.CreateUser(ref superUser); - superUsers.Add(superUser); - } + // Add IP filter log type + var logTypeFilterInfo = new LogTypeInfo + { + LogTypeKey = EventLogController.EventLogType.IP_LOGIN_BANNED.ToString(), + LogTypeFriendlyName = "HTTP Error Code 403.6 forbidden ip address rejected", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeFilterInfo); - // parse File List if available - InstallFiles(xmlDoc, true); + // 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); - // Run any addition scripts in the Scripts folder - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Executing Additional Scripts:
    "); - ExecuteScripts(strProviderPath); + int tabID = TabController.GetTabByTabPath(Null.NullInteger, "//Host//SearchAdmin", Null.NullString); + if (tabID > Null.NullInteger) + { + TabController.Instance.DeleteTab(tabID, Null.NullInteger); + } - // Install optional resources if present - var packages = GetInstallPackages(); - foreach (var package in packages) - { - InstallPackage(package.Key, package.Value.PackageType, true); - } + var modDef = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Search Admin"); - // Set Status to None - Globals.SetStatus(Globals.UpgradeStatus.None); + if (modDef != null) + { + AddAdminPages("Search Admin", "Manage search settings associated with DotNetNuke's search capability.", "~/Icons/Sigma/Search_16x16_Standard.png", "~/Icons/Sigma/Search_32x32_Standard.png", true, modDef.ModuleDefID, "Search Admin", string.Empty); + } - // download LP (and templates) if not using en-us - IInstallationStep ensureLpAndTemplate = new UpdateLanguagePackStep(); - ensureLpAndTemplate.Execute(); + CopyGettingStartedStyles(); + } - // install LP that contains templates if installing in a different language - var installConfig = InstallController.Instance.GetInstallConfig(); - string culture = installConfig.InstallCulture; - if (!culture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) - { - string installFolder = HttpContext.Current.Server.MapPath("~/Install/language"); - string lpAndTemplates = installFolder + "\\installlanguage.resources"; + private static void UpgradeToVersion711() + { + DesktopModuleController.DeleteDesktopModule("FileManager"); - if (File.Exists(lpAndTemplates)) - { - InstallPackage(lpAndTemplates, "Language", false); - } - } + // Add TabUrl Logtypes + 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); - // parse portal(s) if available - XmlNodeList nodes = xmlDoc.SelectNodes("//dotnetnuke/portals/portal"); - if (nodes != null) - { - foreach (XmlNode node in nodes) - { - if (node != null) - { - // add item to identity install from install wizard. - if (HttpContext.Current != null) - { - HttpContext.Current.Items.Add("InstallFromWizard", true); - } + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_UPDATED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL updated"; + LogController.Instance.AddLogType(logTypeInfo); - var portalHost = superUsers[0] as UserInfo; - int portalId = AddPortal(node, true, 2, portalHost); - if (portalId > -1) - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Successfully Installed Site " + portalId + ":
    "); - } - else - { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Site failed to install:Error!
    "); - } - } - } - } - } - else - { - // 500 Error - Redirect to ErrorPage - if (HttpContext.Current != null) - { - string url = "~/ErrorPage.aspx?status=500&error=" + errorMessage; - HttpContext.Current.Response.Clear(); - HttpContext.Current.Server.Transfer(url); - } - } + logTypeInfo.LogTypeKey = EventLogController.EventLogType.TABURL_DELETED.ToString(); + logTypeInfo.LogTypeFriendlyName = "TabURL deleted"; + LogController.Instance.AddLogType(logTypeInfo); } - /// ----------------------------------------------------------------------------- - /// - /// InstallFiles intsalls any files listed in the Host Install Configuration file. - /// - /// - /// - /// The Xml Document to load. - /// A flag that determines whether to output feedback to the Response Stream. - /// ----------------------------------------------------------------------------- - public static void InstallFiles(XmlDocument xmlDoc, bool writeFeedback) + private static void UpgradeToVersion712() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallFiles"); - - // Parse the file nodes - XmlNode node = xmlDoc.SelectSingleNode("//dotnetnuke/files"); - if (node != null) + // update console module in Admin/Host page to set OrderTabsByHierarchy setting to true. + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - if (writeFeedback) + var tabId = TabController.GetTabByTabPath(portal.PortalID, "//Admin", Null.NullString); + if (tabId != Null.NullInteger) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Loading Host Files:
    "); + foreach (var module in ModuleController.Instance.GetTabModules(tabId).Where(m => m.Value.ModuleDefinition.FriendlyName == "Console")) + { + ModuleController.Instance.UpdateModuleSetting(module.Key, "OrderTabsByHierarchy", "True"); + } } - - ParseFiles(node, Null.NullInteger); } - // Synchronise Host Folder - if (writeFeedback) + var hostTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host", Null.NullString); + if (hostTabId != Null.NullInteger) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Synchronizing Host Files:
    "); + foreach (var module in ModuleController.Instance.GetTabModules(hostTabId).Where(m => m.Value.ModuleDefinition.FriendlyName == "Console")) + { + ModuleController.Instance.UpdateModuleSetting(module.Key, "OrderTabsByHierarchy", "True"); + } } - - FolderManager.Instance.Synchronize(Null.NullInteger, string.Empty, true, true); } - public static bool InstallPackage(string file, string packageType, bool writeFeedback) + private static void UpgradeToVersion720() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackage:" + file); - bool success = Null.NullBoolean; - if (writeFeedback) + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("51Degrees.mobi", Null.NullInteger); + if (desktopModule != null) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "Installing Package File " + Path.GetFileNameWithoutExtension(file) + ": "); + DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); } - bool deleteTempFolder = true; - if (packageType == "Skin" || packageType == "Container") + desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.RadEditorProvider", Null.NullInteger); + if (desktopModule != null) { - deleteTempFolder = Null.NullBoolean; + DesktopModuleController.RemoveDesktopModuleFromPortals(desktopModule.DesktopModuleID); } - var installer = new Installer(new FileStream(file, FileMode.Open, FileAccess.Read), Globals.ApplicationMapPath, true, deleteTempFolder); + // ensure old codeplex module is uninstalled - need to check for both variants of package name + UninstallPackage("DotNetNuke.Module Creator", "Module"); + UninstallPackage("DNNCorp.ModuleCreator", "Module"); - // Check if manifest is valid - if (installer.IsValid) + DesktopModuleController.AddModuleCategory("Developer"); + var moduleDefId = AddModuleDefinition("Module Creator", "Development of modules.", "Module Creator"); + AddModuleControl(moduleDefId, string.Empty, string.Empty, "DesktopModules/Admin/ModuleCreator/CreateModule.ascx", "~/DesktopModules/Admin/ModuleCreator/icon.png", SecurityAccessLevel.Host, 0); + if (ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId) != null) { - installer.InstallerInfo.RepairInstall = true; - success = installer.Install(); + var desktopModuleId = ModuleDefinitionController.GetModuleDefinitionByID(moduleDefId).DesktopModuleID; + desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, Null.NullInteger); + desktopModule.Category = "Developer"; + DesktopModuleController.SaveDesktopModule(desktopModule, false, false); + + var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == desktopModule.PackageID); + package.IconFile = "~/Icons/Sigma/ModuleCreator_32x32.png"; + PackageController.Instance.SaveExtensionPackage(package); } - else - { - if (installer.InstallerInfo.ManifestFile == null) - { - // Missing manifest - if (packageType == "Skin" || packageType == "Container") - { - // Legacy Skin/Container - string tempInstallFolder = installer.TempInstallFolder; - string manifestFile = Path.Combine(tempInstallFolder, Path.GetFileNameWithoutExtension(file) + ".dnn"); - using (var manifestWriter = new StreamWriter(manifestFile)) - { - manifestWriter.Write(LegacyUtil.CreateSkinManifest(file, packageType, tempInstallFolder)); - } - installer = new Installer(tempInstallFolder, manifestFile, HttpContext.Current.Request.MapPath("."), true); + var typeController = new ContentTypeController(); + var fileContentType = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); - // Set the Repair flag to true for Batch Install - installer.InstallerInfo.RepairInstall = true; + // only perform following for an existing installation upgrading + if (Globals.Status == Globals.UpgradeStatus.Upgrade) + { + ImportDocumentLibraryCategories(); + ImportDocumentLibraryCategoryAssoc(fileContentType); + } - success = installer.Install(); - } - else if (Globals.Status != Globals.UpgradeStatus.None) - { - var message = string.Format(Localization.GetString("InstallPackageError", Localization.ExceptionsResourceFile), file, "Manifest file missing"); - DnnInstallLogger.InstallLogError(message); - } - } - else - { - // log the failure log when installer is invalid and not caught by mainfest file missing. - foreach (var log in installer.InstallerInfo.Log.Logs - .Where(l => l.Type == LogType.Failure)) - { - Logger.Error(log.Description); - DnnInstallLogger.InstallLogError(log.Description); - } + // fixes issue introduced by eventlog's being defined in upgrade.cs + PortalController.EnsureRequiredEventLogTypesExist(); - success = false; + // Remove Professional Features pages from CE + int advancedFeaturesTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//ProfessionalFeatures", Null.NullString); + if (DotNetNukeContext.Current.Application.Name == "DNNCORP.CE") + { + foreach (var tab in TabController.GetTabsByParent(advancedFeaturesTabId, Null.NullInteger)) + { + TabController.Instance.DeleteTab(tab.TabID, Null.NullInteger); } + + TabController.Instance.DeleteTab(advancedFeaturesTabId, Null.NullInteger); } - if (writeFeedback) + // Remove Whats New + int whatsNewTabId = TabController.GetTabByTabPath(Null.NullInteger, "//Host//WhatsNew", Null.NullString); + TabController.Instance.DeleteTab(whatsNewTabId, Null.NullInteger); + + // Remove WhatsNew module + DesktopModuleController.DeleteDesktopModule("WhatsNew"); + + // read plaintext password via old API and encrypt + var current = HostController.Instance.GetString("SMTPPassword"); + if (!string.IsNullOrEmpty(current)) { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, success); + HostController.Instance.UpdateEncryptedString("SMTPPassword", current, Config.GetDecryptionkey()); } + } - if (success) + private static void UpgradeToVersion721() + { + try { - // delete file - try - { - File.SetAttributes(file, FileAttributes.Normal); - File.Delete(file); - } - catch (Exception exc) + // the username maybe html encode when register in 7.1.2, it will caught unicode charactors changed, need use InputFilter to correct the value. + var portalSecurity = PortalSecurity.Instance; + using (var reader = DataProvider.Instance().ExecuteSQL("SELECT UserID, Username FROM {databaseOwner}[{objectQualifier}Users] WHERE Username LIKE '%&%'")) { - Logger.Error(exc); + while (reader.Read()) + { + var userId = Convert.ToInt32(reader["UserID"]); + var userName = reader["Username"].ToString(); + + if (userName != HttpUtility.HtmlDecode(userName)) + { + userName = portalSecurity.InputFilter( + HttpUtility.HtmlDecode(userName), + PortalSecurity.FilterFlag.NoScripting | + PortalSecurity.FilterFlag.NoAngleBrackets | + PortalSecurity.FilterFlag.NoMarkup); + + UserController.ChangeUsername(userId, userName); + } + } } } + catch (Exception ex) + { + Logger.Error(ex); + } - return success; + AddManageUsersModulePermissions(); } - /// - /// Gets a ist of installable extensions sorted to ensure dependencies are installed first. - /// - /// - public static IDictionary GetInstallPackages() + private static void UpgradeToVersion722() { - var packageTypes = new string[] { "Library", "Module", "Skin", "Container", "JavaScriptLibrary", "Language", "Provider", "AuthSystem", "Package" }; - var invalidPackages = new List(); - - var packages = new Dictionary(); - - ParsePackagesFromApplicationPath(packageTypes, packages, invalidPackages); - - // Add packages with no dependency requirements - var sortedPackages = packages.Where(p => p.Value.Dependencies.Count == 0).ToDictionary(p => p.Key, p => p.Value); - - var prevDependentCount = -1; + UninstallPackage("DotNetNuke.Messaging", "Module"); - var dependentPackages = packages.Where(p => p.Value.Dependencies.Count > 0).ToDictionary(p => p.Key, p => p.Value); - var dependentCount = dependentPackages.Count; - while (dependentCount != prevDependentCount) + // add event log type:POTENTIAL_PAYPAL_PAYMENT_FRAUD + if (!DoesLogTypeExists(EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString())) { - 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) + var logTypeInfo = new LogTypeInfo { - dependentPackages.Remove(packageKey); - } - - dependentCount = dependentPackages.Count; + LogTypeKey = + EventLogController.EventLogType.POTENTIAL_PAYPAL_PAYMENT_FRAUD.ToString(), + LogTypeFriendlyName = "Potential Paypal Payment Fraud", + LogTypeDescription = string.Empty, + LogTypeCSSClass = "OperationFailure", + LogTypeOwner = "DotNetNuke.Logging.EventLogType", + }; + LogController.Instance.AddLogType(logTypeInfo); } - // Add any packages whose dependency cannot be resolved - foreach (var package in dependentPackages) + // AdvancedSettings module needs to be made a system package + var pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.AdvancedSettings"); + if (pkg != null) { - sortedPackages.Add(package.Key, package.Value); + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); } - return sortedPackages; - } - - public static void InstallPackages(string packageType, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "InstallPackages:" + packageType); - if (writeFeedback) + // Site Wizard module needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteWizard"); + if (pkg != null) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Installing Optional " + packageType + "s:
    "); + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); } - string installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; - if (Directory.Exists(installPackagePath)) + // Site Log module needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.SiteLog"); + if (pkg != null) { - foreach (string file in Directory.GetFiles(installPackagePath)) - { - if (Path.GetExtension(file.ToLowerInvariant()) == ".zip" /*|| installLanguage */) - { - InstallPackage(file, packageType, writeFeedback); - } - } + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); } - } - public static bool IsNETFrameworkCurrent(string version) - { - bool isCurrent = Null.NullBoolean; - switch (version) + // Module Creator module needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Module Creator"); + if (pkg != null) { - case "3.5": - // Try and instantiate a 3.5 Class - if (Reflection.CreateType("System.Data.Linq.DataContext", true) != null) - { - isCurrent = true; - } + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); + } - 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; - } + // Telerik.Web module needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "DotNetNuke.Telerik.Web"); + if (pkg != null) + { + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); + } - break; - case "4.5": - // Try and instantiate a 4.5 Class - if (Reflection.CreateType("System.Reflection.ReflectionContext", true) != null) - { - isCurrent = true; - } + // jQuery needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery"); + if (pkg != null) + { + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); + } - break; + // jQuery-Migrate needs to be made a system package + pkg = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == "jQuery-Migrate"); + if (pkg != null) + { + pkg.IsSystemPackage = true; + PackageController.Instance.SaveExtensionPackage(pkg); } - return isCurrent; + // Make ConfigurationManager Premium + MakeModulePremium(@"ConfigurationManager"); + + // Make ConfigurationManager Premium + MakeModulePremium(@"Dashboard"); + + // Make ProfessionalPreview Premium + MakeModulePremium(@"ProfessionalPreview"); } - private static void ParsePackagesFromApplicationPath(IEnumerable packageTypes, Dictionary packages, List invalidPackages) + private static void UpgradeToVersion730() { - foreach (var packageType in packageTypes) +#pragma warning disable 612,618 + if (jQuery.UseHostedScript) { - var installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; - if (!Directory.Exists(installPackagePath)) - { - continue; - } - - var files = Directory.GetFiles(installPackagePath); - if (files.Length <= 0) - { - continue; - } - - Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. + HostController.Instance.Update("CDNEnabled", "True", true); - var optionalPackages = new List(); - foreach (var file in files) - { - var extension = Path.GetExtension(file.ToLowerInvariant()); - if (extension != ".zip" && extension != ".resources") - { - continue; - } + var jquery = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQuery); + jquery.CDNPath = jQuery.HostedUrl; + JavaScriptLibraryController.Instance.SaveLibrary(jquery); - PackageController.ParsePackage(file, installPackagePath, packages, invalidPackages); - if (packages.ContainsKey(file)) - { - // check whether have version conflict and remove old version. - var package = packages[file]; + var jqueryui = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQueryUI); + jqueryui.CDNPath = jQuery.HostedUIUrl; + JavaScriptLibraryController.Instance.SaveLibrary(jqueryui); - var installedPackage = PackageController.Instance.GetExtensionPackage( - Null.NullInteger, - p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) - && p.PackageType.Equals(package.PackageType, StringComparison.OrdinalIgnoreCase)); + var jquerymigrate = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName == CommonJs.jQueryMigrate); + jquerymigrate.CDNPath = jQuery.HostedMigrateUrl; + JavaScriptLibraryController.Instance.SaveLibrary(jquerymigrate); + } +#pragma warning restore 612,618 + } - if (packages.Values.Count(p => p.FriendlyName.Equals(package.FriendlyName, StringComparison.OrdinalIgnoreCase)) > 1 - || installedPackage != null) - { - var oldPackages = packages.Where(kvp => kvp.Value.FriendlyName.Equals(package.FriendlyName, StringComparison.OrdinalIgnoreCase) - && kvp.Value.Version < package.Version).ToList(); + private static void UpgradeToVersion732() + { + // Register System referenced 3rd party assemblies. + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.dll", "3.0.3"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.FastVectorHighlighter.dll", "3.0.3"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Lucene.Net.Contrib.Analyzers.dll", "3.0.3"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.ApplicationBlocks.Data.dll", "2.0.0"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.Web.Helpers.dll", "2.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Microsoft.Web.Infrastructure.dll", "1.0.20105"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "Newtonsoft.Json.dll", "4.5.7"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "PetaPoco.dll", "5.0.1"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "SharpZipLib.dll", "0.81.0"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.dll", "1.0.0"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.Formatting.dll", "4.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Net.Http.WebRequest.dll", "1.0.0"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Helpers.dll", "2.0.20216"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Http.dll", "4.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Http.WebHost.dll", "4.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.Razor.dll", "2.0.20216"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.Deployment.dll", "2.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.dll", "2.0.20710"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "System.Web.WebPages.Razor.dll", "2.0.20126"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebFormsMvp.dll", "1.4.1"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.Data.dll", "2.0.20126"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "WebMatrix.WebData.dll", "2.0.20126"); - // if there already have higher version installed, remove current one from list. - if (installedPackage != null && package.Version <= installedPackage.Version) - { - oldPackages.Add(new KeyValuePair(file, package)); - } + // update help url + HostController.Instance.Update("HelpURL", "https://dnndocs.com", false); + } - if (oldPackages.Any()) - { - foreach (var oldPackage in oldPackages) - { - try - { - packages.Remove(oldPackage.Key); - FileWrapper.Instance.Delete(oldPackage.Key); - } - catch (Exception) - { - // do nothing here. - } - } - } - } - } + private static void UpgradeToVersion733() + { + var notificationType = new NotificationType { Name = "NewUnauthorizedUserRegistration", Description = "New Unauthorized User Registration Notification" }; + NotificationsController.Instance.CreateNotificationType(notificationType); - if (extension != ".zip") - { - optionalPackages.Add(file); - } - } + var actions = new List + { + new NotificationTypeAction + { + NameResourceKey = "AuthorizeUser", + DescriptionResourceKey = "AuthorizeUserDescription", + APICall = "API/InternalServices/NewUserNotificationService/Authorize", + }, + new NotificationTypeAction + { + NameResourceKey = "RejectUser", + DescriptionResourceKey = "RejectUserDescription", + APICall = "API/InternalServices/NewUserNotificationService/Reject" + }, + }; - // remove optional - optionalPackages.ForEach(f => - { - if (packages.ContainsKey(f)) - { - packages.Remove(f); - } - }); - } + NotificationsController.Instance.SetNotificationTypeActions(actions, notificationType.NotificationTypeId); } - public static void RemoveAdminPages(string tabPath) + private static void UpgradeToVersion740() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveAdminPages:" + tabPath); + string PageHeadTextForUpgrade = "" + "\n" + + "" + "\n" + + "" + "\n" + - var portals = PortalController.Instance.GetPortals(); + "" + "\n" + + "" + "\n" + + "" + "\n"; + ArrayList portals = PortalController.Instance.GetPortals(); foreach (PortalInfo portal in portals) { - var tabID = TabController.GetTabByTabPath(portal.PortalID, tabPath, Null.NullString); - if (tabID != Null.NullInteger) - { - TabController.Instance.DeleteTab(tabID, portal.PortalID); - } + PortalController.UpdatePortalSetting(portal.PortalID, "PageHeadText", PageHeadTextForUpgrade); } + + RemoveContentListModuleFromSearchResultsPage(); + ReIndexUserSearch(); } - public static void RemoveHostPage(string pageName) + private static void UpgradeToVersion742() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "RemoveHostPage:" + pageName); - TabInfo skinsTab = TabController.Instance.GetTabByName(pageName, Null.NullInteger); - if (skinsTab != null) + var containerFolder = string.Format("{0}Containers\\DarkKnightMobile", Globals.HostMapPath); + var skinFolder = string.Format("{0}Skins\\DarkKnightMobile", Globals.HostMapPath); + if (!Directory.Exists(skinFolder)) { - TabController.Instance.DeleteTab(skinsTab.TabID, Null.NullInteger); + UninstallPackage("DarkKnightMobile", "Skin"); // Skin + } + + if (!Directory.Exists(containerFolder)) + { + UninstallPackage("DarkKnightMobile", "Container"); // Container } } - public static void StartTimer() + private static void ReIndexUserSearch() { - // Start Upgrade Timer - _startTime = DateTime.Now; + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) + { + PortalController.UpdatePortalSetting(portal.PortalID, UserIndexer.UserIndexResetFlag, "TRUE"); + } } - public static void TryUpgradeNETFramework() + private static void RemoveContentListModuleFromSearchResultsPage() { - switch (Globals.NETFrameworkVersion.ToString(2)) + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - case "3.5": - if (!IsNETFrameworkCurrent("3.5")) - { - // Upgrade to .NET 3.5 - string upgradeFile = string.Format("{0}\\Config\\Net35.config", Globals.InstallMapPath); - string message = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 3.5 Upgrade"); - if (string.IsNullOrEmpty(message)) - { - // Remove old AJAX file - FileSystemUtils.DeleteFile(Path.Combine(Globals.ApplicationMapPath, "bin\\System.Web.Extensions.dll")); - - // Log Upgrade - EventLogController.Instance.AddLog("UpgradeNet", "Upgraded Site to .NET 3.5", PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); - } - else - { - // Log Failed Upgrade - EventLogController.Instance.AddLog("UpgradeNet", string.Format("Upgrade to .NET 3.5 failed. Error reported during attempt to update:{0}", message), PortalController.Instance.GetCurrentPortalSettings(), UserController.Instance.GetCurrentUserInfo().UserID, EventLogController.EventLogType.HOST_ALERT); - } - } - - break; - case "4.0": - if (!IsNETFrameworkCurrent("4.0")) - { - // Upgrade to .NET 4.0 - string upgradeFile = string.Format("{0}\\Config\\Net40.config", Globals.InstallMapPath); - string strMessage = UpdateConfig(upgradeFile, ApplicationVersion, ".NET 4.0 Upgrade"); - EventLogController.Instance.AddLog( - "UpgradeNet", - string.IsNullOrEmpty(strMessage) - ? "Upgraded Site to .NET 4.0" - : string.Format("Upgrade to .NET 4.0 failed. Error reported during attempt to update:{0}", strMessage), - PortalController.Instance.GetCurrentPortalSettings(), - UserController.Instance.GetCurrentUserInfo().UserID, - EventLogController.EventLogType.HOST_ALERT); + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(portal.SearchTabId)) + { + var module = kvp.Value; + if (module.DesktopModule.FriendlyName == "ContentList") + { + // Delete the Module from the Modules list + ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); + break; } - - break; + } } } - /// ----------------------------------------------------------------------------- - /// - /// UpgradeApplication - This overload is used for general application upgrade operations. - /// - /// - /// Since it is not version specific and is invoked whenever the application is - /// restarted, the operations must be re-executable. - /// - /// ----------------------------------------------------------------------------- - public static void UpgradeApplication() + private static void AddManageUsersModulePermissions() { - try - { - // Remove UpdatePanel from Login Control - not neccessary in popup. - var loginControl = ModuleControlController.GetModuleControlByControlKey("Login", -1); - loginControl.SupportsPartialRendering = false; - - ModuleControlController.SaveModuleControl(loginControl, true); - - // Upgrade to .NET 3.5/4.0 - TryUpgradeNETFramework(); + var permCtl = new PermissionController(); + var desktopInfo = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); - // Update the version of the client resources - so the cache is cleared - DataCache.ClearHostCache(false); - HostController.Instance.IncrementCrmVersion(true); - } - catch (Exception ex) + // add new user dialog + var md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Account", desktopInfo.DesktopModuleID); + try { - Logger.Error(ex); - var log = new LogInfo + var pi = new PermissionInfo { - LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true, + ModuleDefID = md.ModuleDefID, + PermissionCode = "SECURITY_MODULE", + PermissionKey = "MANAGEUSER", + PermissionName = "Manage User", }; - log.AddProperty("Upgraded DotNetNuke", "General"); - log.AddProperty("Warnings", "Error: " + ex.Message + Environment.NewLine); - LogController.Instance.AddLog(log); - try - { - Exceptions.Exceptions.LogException(ex); - } - catch (Exception exc) - { - Logger.Error(exc); - } - } - // Remove any .txt and .config files that may exist in the Install folder - foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.txt") - .Concat(Directory.GetFiles(Globals.InstallMapPath + "Cleanup\\", "??.??.??.??.txt"))) + permCtl.AddPermission(pi); + } + catch { - FileSystemUtils.DeleteFile(file); + // suppress } - foreach (string file in Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.config") - .Concat(Directory.GetFiles(Globals.InstallMapPath + "Config\\", "??.??.??.??.config"))) + md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("User Accounts", desktopInfo.DesktopModuleID); + try { - FileSystemUtils.DeleteFile(file); - } - } + var pi = new PermissionInfo + { + ModuleDefID = md.ModuleDefID, + PermissionCode = "SECURITY_MODULE", + PermissionKey = "MANAGEUSERS", + PermissionName = "Manage Users", + }; - /// ----------------------------------------------------------------------------- - /// - /// UpgradeApplication - This overload is used for version specific application upgrade operations. - /// - /// - /// This should be used for file system modifications or upgrade operations which - /// should only happen once. Database references are not recommended because future - /// versions of the application may result in code incompatibilties. - /// - /// - /// ----------------------------------------------------------------------------- - public static string UpgradeApplication(string providerPath, Version version, bool writeFeedback) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); - string exceptions = string.Empty; - if (writeFeedback) + permCtl.AddPermission(pi); + } + catch { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + " : " + GetStringVersionWithRevision(version)); + // suppress } + md = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Security Roles", desktopInfo.DesktopModuleID); try { - if (version.Revision == -1) + var pi = new PermissionInfo { - switch (version.ToString(3)) - { - case "3.2.3": - UpgradeToVersion323(); - break; - case "4.4.0": - UpgradeToVersion440(); - break; - case "4.7.0": - UpgradeToVersion470(); - break; - case "4.8.2": - UpgradeToVersion482(); - break; - case "5.0.0": - UpgradeToVersion500(); - break; - case "5.0.1": - UpgradeToVersion501(); - break; - case "5.1.0": - UpgradeToVersion510(); - break; - case "5.1.1.0": - UpgradeToVersion511(); - break; - case "5.1.3": - UpgradeToVersion513(); - break; - case "5.2.0": - UpgradeToVersion520(); - break; - case "5.2.1": - UpgradeToVersion521(); - break; - case "5.3.0": - UpgradeToVersion530(); - break; - case "5.4.0": - UpgradeToVersion540(); - break; - case "5.4.3": - UpgradeToVersion543(); - break; - case "5.5.0": - UpgradeToVersion550(); - break; - case "5.6.0": - UpgradeToVersion560(); - break; - case "5.6.2": - UpgradeToVersion562(); - break; - case "6.0.0": - UpgradeToVersion600(); - break; - case "6.0.1": - UpgradeToVersion601(); - break; - case "6.0.2": - UpgradeToVersion602(); - break; - case "6.1.0": - UpgradeToVersion610(); - break; - case "6.1.2": - UpgradeToVersion612(); - break; - case "6.1.3": - UpgradeToVersion613(); - break; - case "6.2.0": - UpgradeToVersion620(); - break; - case "6.2.1": - UpgradeToVersion621(); - break; - case "6.2.3": - UpgradeToVersion623(); - break; - case "6.2.4": - UpgradeToVersion624(); - break; - case "7.0.0": - UpgradeToVersion700(); - break; - case "7.1.0": - UpgradeToVersion710(); - break; - case "7.1.1": - UpgradeToVersion711(); - break; - case "7.1.2": - UpgradeToVersion712(); - break; - case "7.2.0": - UpgradeToVersion720(); - break; - case "7.2.1": - UpgradeToVersion721(); - break; - case "7.2.2": - UpgradeToVersion722(); - break; - case "7.3.0": - UpgradeToVersion730(); - break; - case "7.3.2": - UpgradeToVersion732(); - break; - case "7.3.3": - UpgradeToVersion733(); - break; - case "7.4.0": - UpgradeToVersion740(); - break; - case "7.4.2": - UpgradeToVersion742(); - break; - case "9.1.0": - UpgradeToVersion910(); - break; - case "9.2.0": - UpgradeToVersion920(); - break; - case "9.2.1": - UpgradeToVersion921(); - break; - case "9.3.0": - UpgradeToVersion930(); - break; - case "9.4.1": - UpgradeToVersion941(); - break; - case "9.6.0": - UpgradeToVersion960(); - break; - } - } - else + ModuleDefID = md.ModuleDefID, + PermissionCode = "SECURITY_MODULE", + PermissionKey = "MANAGEROLES", + PermissionName = "Manage Roles", + }; + + permCtl.AddPermission(pi); + } + catch + { + // suppress + } + } + + private static ContentItem CreateFileContentItem() + { + var typeController = new ContentTypeController(); + var contentTypeFile = (from t in typeController.GetContentTypes() where t.ContentType == "File" select t).SingleOrDefault(); + + if (contentTypeFile == null) + { + contentTypeFile = new ContentType { ContentType = "File" }; + contentTypeFile.ContentTypeId = typeController.AddContentType(contentTypeFile); + } + + var objContent = new ContentItem + { + ContentTypeId = contentTypeFile.ContentTypeId, + Indexed = false, + }; + + objContent.ContentItemId = DotNetNuke.Entities.Content.Common.Util.GetContentController().AddContentItem(objContent); + + return objContent; + } + + private static void ImportDocumentLibraryCategoryAssoc(ContentType fileContentType) + { + DataProvider dataProvider = DataProvider.Instance(); + IDataReader dr; + try + { + var termController = new TermController(); + var vocabulary = new VocabularyController().GetVocabularies().Single(v => v.Name == "Tags"); + var terms = termController.GetTermsByVocabulary(vocabulary.VocabularyId); + using (dr = dataProvider.ExecuteReader("ImportDocumentLibraryCategoryAssoc")) { - // Incremental - switch (version.ToString(4)) + while (dr.Read()) { - case "8.0.0.6": - UpgradeToVersion8006(); - break; - case "8.0.0.7": - UpgradeToVersion8007(); - break; - case "8.0.0.13": - UpgradeToVersion80013(); - break; - case "8.0.0.16": - UpgradeToVersion80016(); - break; - case "8.0.0.26": - UpgradeToVersion80026(); - break; - case "8.0.0.27": - UpgradeToVersion80027(); - break; + var file = FileManager.Instance.GetFile((int)dr["FileId"]); + ContentItem attachContentItem; + if (file.ContentItemID == Null.NullInteger) + { + attachContentItem = CreateFileContentItem(); + file.ContentItemID = attachContentItem.ContentItemId; + FileManager.Instance.UpdateFile(file); + } + else + { + attachContentItem = Util.GetContentController().GetContentItem(file.ContentItemID); + } + + var term = terms.SingleOrDefault(t => t.Name == dr["CategoryName"].ToString()); + if (term == null) + { + term = new Term(dr["CategoryName"].ToString(), null, vocabulary.VocabularyId); + termController.AddTerm(term); + } + + termController.AddTermToContent(term, attachContentItem); } } } catch (Exception ex) { Logger.Error(ex); - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + } + } - // log the results - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + Localization.GetString("ApplicationUpgrades", Localization.GlobalResourceFile) + ": " + version.ToString(3)); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); - } + private static void ImportDocumentLibraryCategories() + { + VocabularyController vocabularyController = new VocabularyController(); + var defaultTags = (from v in vocabularyController.GetVocabularies() where v.IsSystem && v.Name == "Tags" select v).SingleOrDefault(); + + DataProvider dataProvider = DataProvider.Instance(); + dataProvider.ExecuteNonQuery("ImportDocumentLibraryCategories", defaultTags.VocabularyId); + } + + private static void UpdateFoldersForParentId() + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeFolders"); + + // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out + var foldersToConvert = DataProvider.Instance().GetLegacyFolderCount(); + var foldersRemaining = foldersToConvert; + + if (foldersRemaining > 0) + { + // Create an empty line + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); + } + while (foldersRemaining > 0) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Converting old Folders to new format. Total: {0} [Remaining: {1}]
    ", foldersToConvert, foldersRemaining)); try { - using (StreamWriter streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Application.log.resources")) + using (DataProvider.Instance().UpdateLegacyFolders()) { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); } } - catch (Exception exc) + catch (Exception ex) { - Logger.Error(exc); + Exceptions.Exceptions.LogException(ex); } + + foldersRemaining = DataProvider.Instance().GetLegacyFolderCount(); } - if (writeFeedback) + if (foldersToConvert > 0) { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(exceptions)); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Conversion of old Folders Completed. Total Converted: {0}
    ", foldersToConvert)); } - - return exceptions; } - public static string UpdateConfig(string providerPath, Version version, bool writeFeedback) + private static void UninstallPackage(string packageName, string packageType, bool deleteFiles = true, string version = "") { - var stringVersion = GetStringVersionWithRevision(version); + DnnInstallLogger.InstallLogInfo(string.Concat(Localization.GetString("LogStart", Localization.GlobalResourceFile), "Uninstallation of Package:", packageName, " Type:", packageType, " Version:", version)); - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); - if (writeFeedback) + var searchInput = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => + p.Name.Equals(packageName, StringComparison.OrdinalIgnoreCase) + && p.PackageType.Equals(packageType, StringComparison.OrdinalIgnoreCase) + && (string.IsNullOrEmpty(version) || p.Version.ToString() == version)); + if (searchInput != null) { - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, $"Updating Config Files: {stringVersion}"); + var searchInputInstaller = new Installer(searchInput, Globals.ApplicationMapPath); + searchInputInstaller.UnInstall(deleteFiles); } + } - string strExceptions = UpdateConfig(providerPath, Globals.InstallMapPath + "Config\\" + stringVersion + ".config", version, "Core Upgrade"); - if (string.IsNullOrEmpty(strExceptions)) + private static void ConvertCoreNotificationTypeActionsFor700() + { + var notificationTypeNames = new[] { "FriendRequest", "FollowerRequest", "FollowBackRequest", "TranslationSubmitted" }; + + foreach (var name in notificationTypeNames) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + stringVersion); + var nt = NotificationsController.Instance.GetNotificationType(name); + + if (nt != null) + { + var actions = NotificationsController.Instance.GetNotificationTypeActions(nt.NotificationTypeId).ToList(); + + if (actions.Any()) + { + foreach (var action in actions) + { + action.APICall = action.APICall.Replace(".ashx", string.Empty); + NotificationsController.Instance.DeleteNotificationTypeAction( + action.NotificationTypeActionId); + } + + NotificationsController.Instance.SetNotificationTypeActions(actions, nt.NotificationTypeId); + } + } + else + { + AddMissingNotificationTypes(name); + } } - else + } + + private static void AddMissingNotificationTypes(string notificationTypeName) + { + switch (notificationTypeName) { - DnnInstallLogger.InstallLogError(strExceptions); + case "FriendRequest": + var friendRequestType = new NotificationType { Name = notificationTypeName, Description = "Friend Request" }; + var friendRequestTypeActions = new List(); + friendRequestTypeActions.Add(new NotificationTypeAction + { + NameResourceKey = "Accept", + DescriptionResourceKey = "AcceptFriend", + APICall = "API/InternalServices/RelationshipService/AcceptFriend", + }); + NotificationsController.Instance.CreateNotificationType(friendRequestType); + NotificationsController.Instance.SetNotificationTypeActions(friendRequestTypeActions, friendRequestType.NotificationTypeId); + break; + case "FollowerRequest": + var followerRequestType = new NotificationType { Name = notificationTypeName, Description = "Follower Request" }; + NotificationsController.Instance.CreateNotificationType(followerRequestType); + break; + case "FollowBackRequest": + var followBackRequestType = new NotificationType { Name = notificationTypeName, Description = "Follow Back Request" }; + var followBackRequestTypeActions = new List(); + followBackRequestTypeActions.Add(new NotificationTypeAction + { + NameResourceKey = "FollowBack", + DescriptionResourceKey = "FollowBack", + ConfirmResourceKey = string.Empty, + APICall = "API/InternalServices/RelationshipService/FollowBack", + }); + NotificationsController.Instance.CreateNotificationType(followBackRequestType); + NotificationsController.Instance.SetNotificationTypeActions(followBackRequestTypeActions, followBackRequestType.NotificationTypeId); + break; + case "TranslationSubmitted": + var translationSubmittedType = new NotificationType { Name = notificationTypeName, Description = "Translation Submitted" }; + NotificationsController.Instance.CreateNotificationType(translationSubmittedType); + break; + default: + break; } + } - if (writeFeedback) + private static void AddCoreNotificationTypesFor620() + { + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "AddCoreNotificationTypesFor620"); + var actions = new List(); + + // Friend request + var type = new NotificationType { Name = "FriendRequest", Description = "Friend Request" }; + actions.Add(new NotificationTypeAction { - HtmlUtils.WriteSuccessError(HttpContext.Current.Response, string.IsNullOrEmpty(strExceptions)); - } + NameResourceKey = "Accept", + DescriptionResourceKey = "AcceptFriend", + APICall = "API/InternalServices/RelationshipService/AcceptFriend", + }); + NotificationsController.Instance.CreateNotificationType(type); + NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); + + // Follower + type = new NotificationType { Name = "FollowerRequest", Description = "Follower Request" }; + NotificationsController.Instance.CreateNotificationType(type); + + // Follow Back + type = new NotificationType { Name = "FollowBackRequest", Description = "Follow Back Request" }; + actions.Clear(); + actions.Add(new NotificationTypeAction + { + NameResourceKey = "FollowBack", + DescriptionResourceKey = "FollowBack", + ConfirmResourceKey = string.Empty, + APICall = "API/InternalServices/RelationshipService/FollowBack", + }); + NotificationsController.Instance.CreateNotificationType(type); + NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); - return strExceptions; + // Translation submitted + type = new NotificationType { Name = "TranslationSubmitted", Description = "Translation Submitted" }; + NotificationsController.Instance.CreateNotificationType(type); } - public static string UpdateConfig(string configFile, Version version, string reason) + private static void ConvertOldMessages() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - string exceptions = string.Empty; - if (File.Exists(configFile)) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ConvertOldMessages"); + + // Move old messages to new format. Do this in smaller batches so we can send feedback to browser and don't time out + var messagesToConvert = InternalMessagingController.Instance.CountLegacyMessages(); + var messagesRemaining = messagesToConvert; + const int batchSize = 500; + + if (messagesRemaining > 0) { - // Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); + // Create an empty line + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, "
    ", false); + } + + while (messagesRemaining > 0) + { + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Converting old Messages to new format. Total: {0} [Remaining: {1}]
    ", messagesToConvert, messagesRemaining)); try { - var merge = new XmlMerge(stream, version.ToString(3), reason); - - // Process merge - merge.UpdateConfigs(); + InternalMessagingController.Instance.ConvertLegacyMessages(0, batchSize); } 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)); + messagesRemaining -= batchSize; } - else + + if (messagesToConvert > 0) { - DnnInstallLogger.InstallLogError(exceptions); + HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, string.Format("Conversion of old Messages Completed. Total Converted: {0}
    ", messagesToConvert)); } - - return exceptions; } - private static void UpgradeToVersion8006() + private static void ReplaceMessagingModule() { - RemoveAdminPages("//Admin//Languages"); - RemoveAdminPages("//Admin//Lists"); - RemoveAdminPages("//Admin//LogViewer"); - RemoveAdminPages("//Admin//Newsletters"); - RemoveAdminPages("//Admin//Pages"); - RemoveAdminPages("//Admin//RecycleBin"); - RemoveAdminPages("//Admin//SiteLog"); - RemoveAdminPages("//Admin//SiteWizard"); - RemoveAdminPages("//Admin//Vendors"); - RemoveHostPage("Lists"); - RemoveHostPage("Vendors"); - - var package = PackageController.Instance.GetExtensionPackage(-1, p => p.Name == "DotNetNuke.Vendors"); - if (package != null) + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "ReplaceMessagingModule"); + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName("Message Center"); + if (moduleDefinition == null) { - PackageController.Instance.DeleteExtensionPackage(package); + return; } - package = PackageController.Instance.GetExtensionPackage(-1, p => p.Name == "DotNetNuke.SiteLog"); - if (package != null) + var portals = PortalController.Instance.GetPortals(); + foreach (PortalInfo portal in portals) { - PackageController.Instance.DeleteExtensionPackage(package); - } - } - - private static void UpgradeToVersion8007() - { - RemoveHostPage("Dashboard"); - RemoveHostPage("SQL"); - RemoveHostPage("Configuration Manager"); - - UninstallPackage("DotNetNuke.ProfessionalPreview", "Module"); - UninstallPackage("DotNetNuke.Dashboard", "Module"); - UninstallPackage("DotNetNuke.Configuration Manager", "Module"); - } - - private static void UpgradeToVersion80013() - { - UninstallPackage("DotNetNuke.Newsletters", "Module"); - } - - private static void UpgradeToVersion80016() - { - UninstallPackage("Solutions", "Module"); - - RemoveAdminPages("//Admin//GoogleAnalytics"); - UninstallPackage("DotNetNuke.Google Analytics", "Module"); - - RemoveAdminPages("//Admin//AdvancedSettings"); - UninstallPackage("DotNetNuke.AdvancedSettings", "Module"); - UninstallPackage("DotNetNuke.ContentList", "Module"); - - RemoveAdminPages("//Admin//Skins"); - UninstallPackage("DotNetNuke.Skins", "Module"); - UninstallPackage("DotNetNuke.Skin Designer", "Module"); - UninstallPackage("DotNetNuke.Banners", "Module"); - - RemoveGettingStartedPages(); - } + if (portal.UserTabId > Null.NullInteger) + { + // Find TabInfo + TabInfo tab = TabController.Instance.GetTab(portal.UserTabId, portal.PortalID, true); + if (tab != null) + { + // Add new module to the page + AddModuleToPage(tab, moduleDefinition.ModuleDefID, "Message Center", string.Empty, true); + } - private static void UpgradeToVersion80026() - { - FixTabsMissingLocalizedFields(); + foreach (KeyValuePair kvp in ModuleController.Instance.GetTabModules(portal.UserTabId)) + { + var module = kvp.Value; + if (module.DesktopModule.FriendlyName == "Messaging") + { + // Delete the Module from the Modules list + ModuleController.Instance.DeleteTabModule(module.TabID, module.ModuleID, false); + break; + } + } + } + } } - private static void UpgradeToVersion80027() + private static void MovePhotoProperty() { - RemoveAdminPages("//Admin//DynamicContentTypeManager"); - UninstallPackage("Dnn.DynamicContentManager", "Module"); - UninstallPackage("Dnn.DynamicContentViewer", "Module"); + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "MovePhotoProperty"); + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) + { + var properties = ProfileController.GetPropertyDefinitionsByPortal(portal.PortalID).Cast(); + var propPhoto = properties.FirstOrDefault(p => p.PropertyName == "Photo"); + if (propPhoto != null) + { + var maxOrder = properties.Max(p => p.ViewOrder); + if (propPhoto.ViewOrder != maxOrder) + { + properties.Where(p => p.ViewOrder > propPhoto.ViewOrder).ToList().ForEach(p => + { + p.ViewOrder -= 2; + ProfileController.UpdatePropertyDefinition(p); + }); + propPhoto.ViewOrder = maxOrder; + ProfileController.UpdatePropertyDefinition(propPhoto); + } + } + } } - private static void UpgradeToVersion910() + private static void UpdateChildPortalsDefaultPage() { - RemoveHostPage("Host Settings"); - RemoveHostPage("Site Management"); - RemoveHostPage("Schedule"); - RemoveHostPage("Superuser Accounts"); - RemoveHostPage("Extensions"); - RemoveHostPage("Device Detection Management"); - - RemoveAdminPages("//Admin//Extensions"); - RemoveAdminPages("//Admin//SiteSettings"); - RemoveAdminPages("//Admin//SecurityRoles"); - RemoveAdminPages("//Admin//Taxonomy"); - RemoveAdminPages("//Admin//SiteRedirectionManagement"); - RemoveAdminPages("//Admin//DevicePreviewManagement"); - RemoveAdminPages("//Admin//SearchAdmin"); - - // Normal Modules - UninstallPackage("DotNetNuke.MobileManagement", "Module"); - UninstallPackage("DotNetNuke.Modules.PreviewProfileManagement", "Module"); - - UninstallPackage("DotNetNuke.Dashboard.WebServer", "DashboardControl"); - UninstallPackage("DotNetNuke.Dashboard.Database", "DashboardControl"); - UninstallPackage("DotNetNuke.Dashboard.Host", "DashboardControl"); - UninstallPackage("DotNetNuke.Dashboard.Portals", "DashboardControl"); - UninstallPackage("DotNetNuke.Dashboard.Modules", "DashboardControl"); - UninstallPackage("DotNetNuke.Dashboard.Skins", "DashboardControl"); - - // Admin Modules - UninstallPackage("DotNetNuke.HostSettings", "Module"); - UninstallPackage("DotNetNuke.Languages", "Module"); - UninstallPackage("DotNetNuke.Lists", "Module"); - UninstallPackage("DotNetNuke.LogViewer", "Module"); - UninstallPackage("DotNetNuke.RecycleBin", "Module"); - UninstallPackage("DotNetNuke.Sitemap", "Module"); - UninstallPackage("DotNetNuke.SiteWizard", "Module"); - UninstallPackage("Dnn.Themes", "Module"); // aka. Skin Management - UninstallPackage("DotNetNuke.Tabs", "Module"); - - // at last remove "/Admin" / "/Host" pages - UninstallPackage("DotNetNuke.Portals", "Module"); - UninstallPackage("DotNetNuke.Scheduler", "Module"); - UninstallPackage("DotNetNuke.SearchAdmin", "Module"); - UninstallPackage("DotNetNuke.SQL", "Module"); - UninstallPackage("DotNetNuke.Extensions", "Module"); - UninstallPackage("DotNetNuke.Configuration Manager", "Module"); - UninstallPackage("DotNetNuke.Dashboard", "Module"); - UninstallPackage("DotNetNuke.Google Analytics", "Module"); - UninstallPackage("DotNetNuke.Taxonomy", "Module"); - - UninstallPackage("UrlManagement", "Library", false); - } + DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateChildPortalsDefaultPage"); - private static void UpgradeToVersion920() - { - DataProvider.Instance().UnRegisterAssembly(Null.NullInteger, "SharpZipLib.dll"); - DataProvider.Instance().RegisterAssembly(Null.NullInteger, "ICSharpCode.SharpZipLib.dll", "0.86.0"); + // Update Child Portal subHost.aspx + foreach (PortalAliasInfo aliasInfo in PortalAliasController.Instance.GetPortalAliases().Values) + { + // For the alias to be for a child it must be of the form ...../child + int intChild = aliasInfo.HTTPAlias.IndexOf("/"); + if (intChild != -1 && intChild != (aliasInfo.HTTPAlias.Length - 1)) + { + var childPath = Globals.ApplicationMapPath + "\\" + aliasInfo.HTTPAlias.Substring(intChild + 1); + if (!string.IsNullOrEmpty(Globals.ApplicationPath)) + { + childPath = childPath.Replace("\\", "/"); + childPath = childPath.Replace(Globals.ApplicationPath, string.Empty); + } - RemoveAdminPages("//Admin//SearchEngineSiteMap"); - RemoveAdminPages("//Admin//Solutions"); - RemoveAdminPages("//Admin//BulkEmail"); + childPath = childPath.Replace("/", "\\"); - RemoveHostPage("Marketplace"); - RemoveHostPage("Module Definitions"); - RemoveHostPage("Portals"); + // check if File exists and make sure it's not the site's main default.aspx page + string childDefaultPage = childPath + "\\" + Globals.glbDefaultPage; + if (childPath != Globals.ApplicationMapPath && File.Exists(childDefaultPage)) + { + var objDefault = new System.IO.FileInfo(childDefaultPage); + var objSubHost = new System.IO.FileInfo(Globals.HostMapPath + "subhost.aspx"); - if (!HostTabExists("Superuser Accounts")) - { - // add SuperUser Accounts module and tab - var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); - if (desktopModule != null) - { - var moduleDefId = ModuleDefinitionController - .GetModuleDefinitionByFriendlyName("User Accounts", desktopModule.DesktopModuleID).ModuleDefID; + // check if upgrade is necessary + if (objDefault.Length != objSubHost.Length) + { + // check file is readonly + bool wasReadonly = false; + FileAttributes attributes = File.GetAttributes(childDefaultPage); + if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) + { + wasReadonly = true; - // Create New Host Page (or get existing one) - var newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", - "~/Icons/Sigma/Users_16X16_Standard.png", "~/Icons/Sigma/Users_32X32_Standard.png", false); + // remove readonly attribute + File.SetAttributes(childDefaultPage, FileAttributes.Normal); + } - // Add Module To Page - AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "~/Icons/Sigma/Users_32X32_Standard.png"); - } - } + // Rename existing file + File.Copy(childDefaultPage, childPath + "\\old_" + Globals.glbDefaultPage, true); - var portalController = PortalController.Instance; - foreach (PortalInfo portal in portalController.GetPortals()) - { - if (!string.IsNullOrEmpty(portal.ProcessorPassword)) - { - portalController.UpdatePortalInfo(portal); + // copy file + File.Copy(Globals.HostMapPath + "subhost.aspx", childDefaultPage, true); + + // set back the readonly attribute + if (wasReadonly) + { + File.SetAttributes(childDefaultPage, FileAttributes.ReadOnly); + } + } + } } } } - private static void UpgradeToVersion921() - { - UninstallPackage("jQuery", "Javascript_Library", true, "1.9.1"); - UninstallPackage("jQuery-UI", "Javascript_Library", true, "1.11.3"); - UninstallPackage("jQuery-Migrate", "Javascript_Library", true, "1.2.1"); - } - - private static void UpgradeToVersion930() + private static void CopyGettingStartedStyles() { - var applicationName = System.Web.Security.Membership.ApplicationName; - if (string.IsNullOrWhiteSpace(applicationName)) + // copy getting started css to portals folder. + var hostGettingStartedFile = string.Format("{0}GettingStarted.css", Globals.HostMapPath); + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - Logger.Warn("Unable to run orphaned user check. Application name is missing or not defined."); - return; - } + if (File.Exists(hostGettingStartedFile)) + { + var portalFile = portal.HomeDirectoryMapPath + "GettingStarted.css"; + if (!File.Exists(portalFile)) + { + File.Copy(hostGettingStartedFile, portalFile); + } + } - using (var reader = DataProvider.Instance().ExecuteReader("DeleteOrphanedAspNetUsers", applicationName)) - { - while (reader.Read()) + // update the getting started page to have this custom style sheet. + var gettingStartedTabId = PortalController.GetPortalSettingAsInteger("GettingStartedTabId", portal.PortalID, Null.NullInteger); + if (gettingStartedTabId > Null.NullInteger) { - var errorMsg = reader["ErrorMessage"]; - if (errorMsg != null) + // check if tab exists + if (TabController.Instance.GetTab(gettingStartedTabId, portal.PortalID, true) != null) { - Logger.Error("Failed to remove orphaned aspnet users. Error: " + - errorMsg.ToString()); + TabController.Instance.UpdateTabSetting(gettingStartedTabId, "CustomStylesheet", "GettingStarted.css"); } } } } - private static void UpgradeToVersion941() + private static void RemoveGettingStartedPages() { - // It's possible previous versions of DNN created invalid binding redirects with , which are ignored - // This finds these and removes them, adding a correct binding redirect if one doesn't exist - var webConfig = Config.Load(); - - var ns = new XmlNamespaceManager(webConfig.NameTable); - ns.AddNamespace("ab", "urn:schemas-microsoft-com:asm.v1"); - - var invalidDependentAssemblies = webConfig.SelectNodes("/configuration/runtime/ab:assemblyBinding/dependentAssembly", ns); - foreach (XmlNode dependentAssembly in invalidDependentAssemblies) + foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { - var assemblyBindingElement = dependentAssembly.ParentNode; - var assemblyIdentity = dependentAssembly.ChildNodes.Cast().SingleOrDefault(n => n.LocalName.Equals("assemblyIdentity", StringComparison.Ordinal)); - if (assemblyIdentity == null) - { - assemblyBindingElement.RemoveChild(dependentAssembly); - continue; - } - - var name = assemblyIdentity.Attributes["name"]?.Value; - var publicKeyToken = assemblyIdentity.Attributes["publicKeyToken"]?.Value; - if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(publicKeyToken)) + try { - assemblyBindingElement.RemoveChild(dependentAssembly); - continue; - } + var fileInfo = FileManager.Instance.GetFile(portal.PortalID, "GettingStarted.css"); + if (fileInfo != null) + { + FileManager.Instance.DeleteFile(fileInfo); + } - var dependentAssemblyXPath = $"/configuration/runtime/ab:assemblyBinding/ab:dependentAssembly[ab:assemblyIdentity/@name='{name}'][ab:assemblyIdentity/@publicKeyToken='{publicKeyToken}']"; - var validDependentAssembly = webConfig.SelectSingleNode(dependentAssemblyXPath, ns); - if (validDependentAssembly != null) - { - // a valid dependentAssembly exists for this assembly, just remove the invalid element - assemblyBindingElement.RemoveChild(dependentAssembly); - continue; - } + var gettingStartedTabId = PortalController.GetPortalSettingAsInteger("GettingStartedTabId", portal.PortalID, Null.NullInteger); + if (gettingStartedTabId > Null.NullInteger) + { + // remove getting started page from portal + if (TabController.Instance.GetTab(gettingStartedTabId, portal.PortalID, true) != null) + { + TabController.Instance.DeleteTab(gettingStartedTabId, portal.PortalID); + } - // otherwise, replace the invalid dependentAssembly with a valid version of it - AssemblyName assemblyName; - try - { - assemblyName = AssemblyName.GetAssemblyName(Path.Combine(Globals.ApplicationMapPath, "bin", name + ".dll")); + PortalController.DeletePortalSetting(portal.PortalID, "GettingStartedTabId"); + } } - catch + catch (Exception ex) { - assemblyBindingElement.RemoveChild(dependentAssembly); - continue; + Logger.Error(ex); } + } + } - var validAssemblyIdentity = webConfig.CreateElement("assemblyIdentity", "urn:schemas-microsoft-com:asm.v1"); - validAssemblyIdentity.AddAttribute("name", name); - validAssemblyIdentity.AddAttribute("publicKeyToken", publicKeyToken); - - var validBindingRedirect = webConfig.CreateElement("bindingRedirect", "urn:schemas-microsoft-com:asm.v1"); - validBindingRedirect.AddAttribute("oldVersion", "0.0.0.0-32767.32767.32767.32767"); - validBindingRedirect.AddAttribute("newVersion", assemblyName.Version.ToString()); + private static bool DoesLogTypeExists(string logTypeKey) + { + LogTypeInfo logType; + Dictionary logTypeDictionary = LogController.Instance.GetLogTypeInfoDictionary(); + logTypeDictionary.TryGetValue(logTypeKey, out logType); + if (logType == null) + { + return false; + } - validDependentAssembly = webConfig.CreateElement("dependentAssembly", "urn:schemas-microsoft-com:asm.v1"); - validDependentAssembly.AppendChild(validAssemblyIdentity); - validDependentAssembly.AppendChild(validBindingRedirect); + return true; + } - assemblyBindingElement.ReplaceChild(validDependentAssembly, dependentAssembly); + private static string GetStringVersionWithRevision(Version version) + { + var stringVersion = GetStringVersion(version); + if (version.Revision > 0) + { + stringVersion += "." + version.Revision.ToString("D2"); } - if (invalidDependentAssemblies.Count > 0) + return stringVersion; + } + + private static string[] AddAvailableIncrementalFiles(string providerPath, Version version) + { + if (version.Major < 8) { - Config.Save(webConfig); + 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 void UpgradeToVersion960() + private static string GetFileName(string file) { - // Set default end user upload extension whitelist - ensure we don't add extensions that were not in the master list before - var toAdd = new List { ".export" }; - HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); - var exts = new FileExtensionWhitelist("jpg,jpeg,jpe,gif,bmp,png,svg,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,zip,rar,ico,avi,mpg,mpeg,mp3,wmv,mov,wav,mp4,webm,ogv,export"); - exts.RestrictBy(Host.AllowedExtensionWhitelist); - HostController.Instance.Update("DefaultEndUserExtensionWhitelist", exts.ToStorageString()); + return Path.GetFileName(file); } - public static string UpdateConfig(string providerPath, string configFile, Version version, string reason) + private static void ParsePackagesFromApplicationPath(IEnumerable packageTypes, Dictionary packages, List invalidPackages) { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - string exceptions = string.Empty; - if (File.Exists(configFile)) + foreach (var packageType in packageTypes) { - // Create XmlMerge instance from config file source - StreamReader stream = File.OpenText(configFile); - try + var installPackagePath = Globals.ApplicationMapPath + "\\Install\\" + packageType; + if (!Directory.Exists(installPackagePath)) { - var merge = new XmlMerge(stream, version.ToString(3), reason); + continue; + } - // Process merge - merge.UpdateConfigs(); + var files = Directory.GetFiles(installPackagePath); + if (files.Length <= 0) + { + continue; } - catch (Exception ex) + + Array.Sort(files); // The order of the returned file names is not guaranteed on certain NAS systems; use the Sort method if a specific sort order is required. + + var optionalPackages = new List(); + foreach (var file in files) { - Logger.Error(ex); - exceptions += string.Format("Error: {0}{1}", ex.Message + ex.StackTrace, Environment.NewLine); + var extension = Path.GetExtension(file.ToLowerInvariant()); + if (extension != ".zip" && extension != ".resources") + { + continue; + } - // log the results - try + PackageController.ParsePackage(file, installPackagePath, packages, invalidPackages); + if (packages.ContainsKey(file)) { - using (StreamWriter streamWriter = File.CreateText(providerPath + Globals.FormatVersion(version) + "_Config.log")) + // check whether have version conflict and remove old version. + var package = packages[file]; + + var installedPackage = PackageController.Instance.GetExtensionPackage( + Null.NullInteger, + p => p.Name.Equals(package.Name, StringComparison.OrdinalIgnoreCase) + && p.PackageType.Equals(package.PackageType, StringComparison.OrdinalIgnoreCase)); + + if (packages.Values.Count(p => p.FriendlyName.Equals(package.FriendlyName, StringComparison.OrdinalIgnoreCase)) > 1 + || installedPackage != null) { - streamWriter.WriteLine(exceptions); - streamWriter.Close(); + var oldPackages = packages.Where(kvp => kvp.Value.FriendlyName.Equals(package.FriendlyName, StringComparison.OrdinalIgnoreCase) + && kvp.Value.Version < package.Version).ToList(); + + // if there already have higher version installed, remove current one from list. + if (installedPackage != null && package.Version <= installedPackage.Version) + { + oldPackages.Add(new KeyValuePair(file, package)); + } + + if (oldPackages.Any()) + { + foreach (var oldPackage in oldPackages) + { + try + { + packages.Remove(oldPackage.Key); + FileWrapper.Instance.Delete(oldPackage.Key); + } + catch (Exception) + { + // do nothing here. + } + } + } } } - catch (Exception exc) + + if (extension != ".zip") { - Logger.Error(exc); + optionalPackages.Add(file); } } - finally - { - // Close stream - stream.Close(); - } - } - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogEnd", Localization.GlobalResourceFile) + "UpdateConfig:" + version.ToString(3)); - } - else - { - DnnInstallLogger.InstallLogError(exceptions); + // remove optional + optionalPackages.ForEach(f => + { + if (packages.ContainsKey(f)) + { + packages.Remove(f); + } + }); } - - return exceptions; } - /// ----------------------------------------------------------------------------- - /// - /// UpgradeDNN manages the Upgrade of an exisiting DotNetNuke Application. - /// - /// - /// - /// The path to the Data Provider. - /// The current Database Version. - /// ----------------------------------------------------------------------------- - public static void UpgradeDNN(string providerPath, Version dataBaseVersion) + private static void UpgradeToVersion8006() { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeDNN:" + Globals.FormatVersion(ApplicationVersion)); - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Upgrading to Version: " + Globals.FormatVersion(ApplicationVersion) + "
    "); - - // Process the Upgrade Script files - var versions = new List(); - foreach (string scriptFile in GetUpgradeScripts(providerPath, dataBaseVersion)) - { - var version = new Version(GetFileNameWithoutExtension(scriptFile)); - bool scriptExecuted; - UpgradeVersion(scriptFile, true, out scriptExecuted); - if (scriptExecuted) - { - versions.Add(version); - } - } - - foreach (Version ver in versions) - { - // ' perform version specific application upgrades - UpgradeApplication(providerPath, ver, true); - } + RemoveAdminPages("//Admin//Languages"); + RemoveAdminPages("//Admin//Lists"); + RemoveAdminPages("//Admin//LogViewer"); + RemoveAdminPages("//Admin//Newsletters"); + RemoveAdminPages("//Admin//Pages"); + RemoveAdminPages("//Admin//RecycleBin"); + RemoveAdminPages("//Admin//SiteLog"); + RemoveAdminPages("//Admin//SiteWizard"); + RemoveAdminPages("//Admin//Vendors"); + RemoveHostPage("Lists"); + RemoveHostPage("Vendors"); - foreach (Version ver in versions) + var package = PackageController.Instance.GetExtensionPackage(-1, p => p.Name == "DotNetNuke.Vendors"); + if (package != null) { - // delete files which are no longer used - DeleteFiles(providerPath, ver, true); + PackageController.Instance.DeleteExtensionPackage(package); } - foreach (Version ver in versions) + package = PackageController.Instance.GetExtensionPackage(-1, p => p.Name == "DotNetNuke.SiteLog"); + if (package != null) { - // execute config file updates - UpdateConfig(providerPath, ver, true); + PackageController.Instance.DeleteExtensionPackage(package); } + } - DataProvider.Instance().SetCorePackageVersions(); - - // perform general application upgrades - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 0, "Performing General Upgrades
    "); - DnnInstallLogger.InstallLogInfo(Localization.GetString("GeneralUpgrades", Localization.GlobalResourceFile)); - UpgradeApplication(); + private static void UpgradeToVersion8007() + { + RemoveHostPage("Dashboard"); + RemoveHostPage("SQL"); + RemoveHostPage("Configuration Manager"); - DataCache.ClearHostCache(true); + UninstallPackage("DotNetNuke.ProfessionalPreview", "Module"); + UninstallPackage("DotNetNuke.Dashboard", "Module"); + UninstallPackage("DotNetNuke.Configuration Manager", "Module"); } - public static string UpgradeIndicator(Version version, bool isLocal, bool isSecureConnection) + private static void UpgradeToVersion80013() { - return UpgradeIndicator(version, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty, isLocal, isSecureConnection); + UninstallPackage("DotNetNuke.Newsletters", "Module"); } - public static string UpgradeIndicator(Version version, string packageType, string packageName, string culture, bool isLocal, bool isSecureConnection) + private static void UpgradeToVersion80016() { - string url = string.Empty; - if (Host.CheckUpgrade && version != new Version(0, 0, 0)) - { - url = DotNetNukeContext.Current.Application.UpgradeUrl + "/update.aspx"; - - // use network path reference so it works in ssl-offload scenarios - url = url.Replace("http://", "//"); - url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); - url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); - url += "&type=" + packageType; - url += "&name=" + packageName; - if (packageType.ToLowerInvariant() == "module") - { - var moduleType = (from m in InstalledModulesController.GetInstalledModules() where m.ModuleName == packageName select m).SingleOrDefault(); - if (moduleType != null) - { - url += "&no=" + moduleType.Instances; - } - } + UninstallPackage("Solutions", "Module"); - url += "&id=" + Host.GUID; - if (packageType.Equals(DotNetNukeContext.Current.Application.Type, StringComparison.OrdinalIgnoreCase)) - { - if (!string.IsNullOrEmpty(HostController.Instance.GetString("NewsletterSubscribeEmail"))) - { - url += "&email=" + HttpUtility.UrlEncode(HostController.Instance.GetString("NewsletterSubscribeEmail")); - } + RemoveAdminPages("//Admin//GoogleAnalytics"); + UninstallPackage("DotNetNuke.Google Analytics", "Module"); - var portals = PortalController.Instance.GetPortals(); - url += "&no=" + portals.Count; - url += "&os=" + Globals.FormatVersion(Globals.OperatingSystemVersion, "00", 2, string.Empty); - url += "&net=" + Globals.FormatVersion(Globals.NETFrameworkVersion, "00", 2, string.Empty); - url += "&db=" + Globals.FormatVersion(Globals.DatabaseEngineVersion, "00", 2, string.Empty); - var source = Config.GetSetting("Source"); - if (!string.IsNullOrEmpty(source)) - { - url += "&src=" + source; - } - } + RemoveAdminPages("//Admin//AdvancedSettings"); + UninstallPackage("DotNetNuke.AdvancedSettings", "Module"); + UninstallPackage("DotNetNuke.ContentList", "Module"); - if (!string.IsNullOrEmpty(culture)) - { - url += "&culture=" + culture; - } - } + RemoveAdminPages("//Admin//Skins"); + UninstallPackage("DotNetNuke.Skins", "Module"); + UninstallPackage("DotNetNuke.Skin Designer", "Module"); + UninstallPackage("DotNetNuke.Banners", "Module"); - return url; + RemoveGettingStartedPages(); } - internal static string GetFileNameWithoutExtension(string scriptFile) + private static void UpgradeToVersion80026() { - return Path.GetFileNameWithoutExtension(scriptFile); + FixTabsMissingLocalizedFields(); } - public static string UpgradeRedirect() + private static void UpgradeToVersion80027() { - return UpgradeRedirect(ApplicationVersion, DotNetNukeContext.Current.Application.Type, DotNetNukeContext.Current.Application.Name, string.Empty); + RemoveAdminPages("//Admin//DynamicContentTypeManager"); + UninstallPackage("Dnn.DynamicContentManager", "Module"); + UninstallPackage("Dnn.DynamicContentViewer", "Module"); } - public static string UpgradeRedirect(Version version, string packageType, string packageName, string culture) + private static void UpgradeToVersion910() { - string url; - if (!string.IsNullOrEmpty(Config.GetSetting("UpdateServiceRedirect"))) - { - url = Config.GetSetting("UpdateServiceRedirect"); - } - else - { - url = DotNetNukeContext.Current.Application.UpgradeUrl + "/redirect.aspx"; - url += "?core=" + Globals.FormatVersion(Assembly.GetExecutingAssembly().GetName().Version, "00", 3, string.Empty); - url += "&version=" + Globals.FormatVersion(version, "00", 3, string.Empty); - url += "&type=" + packageType; - url += "&name=" + packageName; - if (!string.IsNullOrEmpty(culture)) - { - url += "&culture=" + culture; - } - } + RemoveHostPage("Host Settings"); + RemoveHostPage("Site Management"); + RemoveHostPage("Schedule"); + RemoveHostPage("Superuser Accounts"); + RemoveHostPage("Extensions"); + RemoveHostPage("Device Detection Management"); - return url; - } + RemoveAdminPages("//Admin//Extensions"); + RemoveAdminPages("//Admin//SiteSettings"); + RemoveAdminPages("//Admin//SecurityRoles"); + RemoveAdminPages("//Admin//Taxonomy"); + RemoveAdminPages("//Admin//SiteRedirectionManagement"); + RemoveAdminPages("//Admin//DevicePreviewManagement"); + RemoveAdminPages("//Admin//SearchAdmin"); - /// ----------------------------------------------------------------------------- - /// - /// UpgradeVersion upgrades a single version. - /// - /// - /// - /// The upgrade script file. - /// Write status to Response Stream?. - /// - /// ----------------------------------------------------------------------------- - public static string UpgradeVersion(string scriptFile, bool writeFeedback) - { - bool scriptExecuted; - return UpgradeVersion(scriptFile, writeFeedback, out scriptExecuted); - } + // Normal Modules + UninstallPackage("DotNetNuke.MobileManagement", "Module"); + UninstallPackage("DotNetNuke.Modules.PreviewProfileManagement", "Module"); - /// ----------------------------------------------------------------------------- - /// - /// UpgradeVersion upgrades a single version. - /// - /// - /// - /// The upgrade script file. - /// Write status to Response Stream?. - /// Identity whether the script file executed. - /// - /// ----------------------------------------------------------------------------- - public static string UpgradeVersion(string scriptFile, bool writeFeedback, out bool scriptExecuted) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); - var version = new Version(GetFileNameWithoutExtension(scriptFile)); - string exceptions = Null.NullString; - scriptExecuted = false; + UninstallPackage("DotNetNuke.Dashboard.WebServer", "DashboardControl"); + UninstallPackage("DotNetNuke.Dashboard.Database", "DashboardControl"); + UninstallPackage("DotNetNuke.Dashboard.Host", "DashboardControl"); + UninstallPackage("DotNetNuke.Dashboard.Portals", "DashboardControl"); + UninstallPackage("DotNetNuke.Dashboard.Modules", "DashboardControl"); + UninstallPackage("DotNetNuke.Dashboard.Skins", "DashboardControl"); + + // Admin Modules + UninstallPackage("DotNetNuke.HostSettings", "Module"); + UninstallPackage("DotNetNuke.Languages", "Module"); + UninstallPackage("DotNetNuke.Lists", "Module"); + UninstallPackage("DotNetNuke.LogViewer", "Module"); + UninstallPackage("DotNetNuke.RecycleBin", "Module"); + UninstallPackage("DotNetNuke.Sitemap", "Module"); + UninstallPackage("DotNetNuke.SiteWizard", "Module"); + UninstallPackage("Dnn.Themes", "Module"); // aka. Skin Management + UninstallPackage("DotNetNuke.Tabs", "Module"); - // verify script has not already been run - if (!Globals.FindDatabaseVersion(version.Major, version.Minor, version.Build)) - { - // execute script file (and version upgrades) for version - exceptions = ExecuteScript(scriptFile, writeFeedback); - scriptExecuted = true; + // at last remove "/Admin" / "/Host" pages + UninstallPackage("DotNetNuke.Portals", "Module"); + UninstallPackage("DotNetNuke.Scheduler", "Module"); + UninstallPackage("DotNetNuke.SearchAdmin", "Module"); + UninstallPackage("DotNetNuke.SQL", "Module"); + UninstallPackage("DotNetNuke.Extensions", "Module"); + UninstallPackage("DotNetNuke.Configuration Manager", "Module"); + UninstallPackage("DotNetNuke.Dashboard", "Module"); + UninstallPackage("DotNetNuke.Google Analytics", "Module"); + UninstallPackage("DotNetNuke.Taxonomy", "Module"); - // update the version - Globals.UpdateDataBaseVersion(version); + UninstallPackage("UrlManagement", "Library", false); + } - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true, - }; - log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version)); - if (exceptions.Length > 0) - { - log.AddProperty("Warnings", exceptions); - } - else - { - log.AddProperty("No Warnings", string.Empty); - } + private static void UpgradeToVersion920() + { + DataProvider.Instance().UnRegisterAssembly(Null.NullInteger, "SharpZipLib.dll"); + DataProvider.Instance().RegisterAssembly(Null.NullInteger, "ICSharpCode.SharpZipLib.dll", "0.86.0"); - LogController.Instance.AddLog(log); - } + RemoveAdminPages("//Admin//SearchEngineSiteMap"); + RemoveAdminPages("//Admin//Solutions"); + RemoveAdminPages("//Admin//BulkEmail"); - if (version.Revision > 0 && - version.Revision > Globals.GetLastAppliedIteration(version)) + RemoveHostPage("Marketplace"); + RemoveHostPage("Module Definitions"); + RemoveHostPage("Portals"); + + if (!HostTabExists("Superuser Accounts")) { - // execute script file (and version upgrades) for version - exceptions = ExecuteScript(scriptFile, writeFeedback); - scriptExecuted = true; + // add SuperUser Accounts module and tab + var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName("Security", Null.NullInteger); + if (desktopModule != null) + { + var moduleDefId = ModuleDefinitionController + .GetModuleDefinitionByFriendlyName("User Accounts", desktopModule.DesktopModuleID).ModuleDefID; - // update the increment - Globals.UpdateDataBaseVersionIncrement(version, version.Revision); + // Create New Host Page (or get existing one) + var newPage = AddHostPage("Superuser Accounts", "Manage host user accounts.", + "~/Icons/Sigma/Users_16X16_Standard.png", "~/Icons/Sigma/Users_32X32_Standard.png", false); - var log = new LogInfo - { - LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString(), - BypassBuffering = true, - }; - log.AddProperty("Upgraded DotNetNuke", "Version: " + Globals.FormatVersion(version) + ", Iteration:" + version.Revision); - if (exceptions.Length > 0) - { - log.AddProperty("Warnings", exceptions); - } - else - { - log.AddProperty("No Warnings", string.Empty); + // Add Module To Page + AddModuleToPage(newPage, moduleDefId, "SuperUser Accounts", "~/Icons/Sigma/Users_32X32_Standard.png"); } - - LogController.Instance.AddLog(log); } - if (string.IsNullOrEmpty(exceptions)) - { - DnnInstallLogger.InstallLogInfo(Localization.GetString("LogStart", Localization.GlobalResourceFile) + "UpgradeVersion:" + scriptFile); - } - else + var portalController = PortalController.Instance; + foreach (PortalInfo portal in portalController.GetPortals()) { - DnnInstallLogger.InstallLogError(exceptions); + if (!string.IsNullOrEmpty(portal.ProcessorPassword)) + { + portalController.UpdatePortalInfo(portal); + } } + } - return exceptions; + private static void UpgradeToVersion921() + { + UninstallPackage("jQuery", "Javascript_Library", true, "1.9.1"); + UninstallPackage("jQuery-UI", "Javascript_Library", true, "1.11.3"); + UninstallPackage("jQuery-Migrate", "Javascript_Library", true, "1.2.1"); } - public static bool UpdateNewtonsoftVersion() + private static void UpgradeToVersion930() { - try + var applicationName = System.Web.Security.Membership.ApplicationName; + if (string.IsNullOrWhiteSpace(applicationName)) { - // check whether current binding already specific to correct version. - if (NewtonsoftNeedUpdate()) + Logger.Warn("Unable to run orphaned user check. Application name is missing or not defined."); + return; + } + + using (var reader = DataProvider.Instance().ExecuteReader("DeleteOrphanedAspNetUsers", applicationName)) + { + while (reader.Read()) { - lock (_threadLocker) + var errorMsg = reader["ErrorMessage"]; + if (errorMsg != null) { - if (NewtonsoftNeedUpdate()) - { - var matchedFiles = Directory.GetFiles(Path.Combine(Globals.ApplicationMapPath, "Install\\Module"), "Newtonsoft.Json_*_Install.zip"); - if (matchedFiles.Length > 0) - { - return InstallPackage(matchedFiles[0], "Library", false); - } - } + Logger.Error("Failed to remove orphaned aspnet users. Error: " + + errorMsg.ToString()); } } } - catch (Exception ex) - { - Logger.Error(ex); - } - - return false; } - public static string ActivateLicense() + private static void UpgradeToVersion941() { - var isLicensable = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Professional.dll")) || File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")); - var activationResult = string.Empty; + // It's possible previous versions of DNN created invalid binding redirects with , which are ignored + // This finds these and removes them, adding a correct binding redirect if one doesn't exist + var webConfig = Config.Load(); - if (isLicensable) + var ns = new XmlNamespaceManager(webConfig.NameTable); + ns.AddNamespace("ab", "urn:schemas-microsoft-com:asm.v1"); + + var invalidDependentAssemblies = webConfig.SelectNodes("/configuration/runtime/ab:assemblyBinding/dependentAssembly", ns); + foreach (XmlNode dependentAssembly in invalidDependentAssemblies) { - var sku = File.Exists(HttpContext.Current.Server.MapPath("~\\bin\\DotNetNuke.Enterprise.dll")) ? "DNNENT" : "DNNPRO"; - HtmlUtils.WriteFeedback(HttpContext.Current.Response, 2, Localization.GetString("ActivatingLicense", Localization.GlobalResourceFile)); + var assemblyBindingElement = dependentAssembly.ParentNode; + var assemblyIdentity = dependentAssembly.ChildNodes.Cast().SingleOrDefault(n => n.LocalName.Equals("assemblyIdentity", StringComparison.Ordinal)); + if (assemblyIdentity == null) + { + assemblyBindingElement.RemoveChild(dependentAssembly); + continue; + } - var installConfig = InstallController.Instance.GetInstallConfig(); - var licenseConfig = (installConfig != null) ? installConfig.License : null; + var name = assemblyIdentity.Attributes["name"]?.Value; + var publicKeyToken = assemblyIdentity.Attributes["publicKeyToken"]?.Value; + if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(publicKeyToken)) + { + assemblyBindingElement.RemoveChild(dependentAssembly); + continue; + } - if (licenseConfig != null) + var dependentAssemblyXPath = $"/configuration/runtime/ab:assemblyBinding/ab:dependentAssembly[ab:assemblyIdentity/@name='{name}'][ab:assemblyIdentity/@publicKeyToken='{publicKeyToken}']"; + var validDependentAssembly = webConfig.SelectSingleNode(dependentAssemblyXPath, ns); + if (validDependentAssembly != null) { - dynamic licenseActivation = Reflection.CreateObject(Reflection.CreateType("DotNetNuke.Professional.LicenseActivation.ViewLicx")); - licenseActivation.AutoActivation(licenseConfig.AccountEmail, licenseConfig.InvoiceNumber, licenseConfig.WebServer, licenseConfig.LicenseType, sku); - activationResult = licenseActivation.LicenseResult; + // a valid dependentAssembly exists for this assembly, just remove the invalid element + assemblyBindingElement.RemoveChild(dependentAssembly); + continue; + } - // Log Event to Event Log - EventLogController.Instance.AddLog( - "License Activation", - "License Activated during install for: " + licenseConfig.AccountEmail + " | invoice: " + licenseConfig.InvoiceNumber, - EventLogController.EventLogType.HOST_ALERT); + // otherwise, replace the invalid dependentAssembly with a valid version of it + AssemblyName assemblyName; + try + { + assemblyName = AssemblyName.GetAssemblyName(Path.Combine(Globals.ApplicationMapPath, "bin", name + ".dll")); + } + catch + { + assemblyBindingElement.RemoveChild(dependentAssembly); + continue; } - } - return activationResult; - } + var validAssemblyIdentity = webConfig.CreateElement("assemblyIdentity", "urn:schemas-microsoft-com:asm.v1"); + validAssemblyIdentity.AddAttribute("name", name); + validAssemblyIdentity.AddAttribute("publicKeyToken", publicKeyToken); - protected static bool IsLanguageEnabled(int portalid, string code) - { - Locale enabledLanguage; - return LocaleController.Instance.GetLocales(portalid).TryGetValue(code, out enabledLanguage); - } + var validBindingRedirect = webConfig.CreateElement("bindingRedirect", "urn:schemas-microsoft-com:asm.v1"); + validBindingRedirect.AddAttribute("oldVersion", "0.0.0.0-32767.32767.32767.32767"); + validBindingRedirect.AddAttribute("newVersion", assemblyName.Version.ToString()); - public static bool RemoveInvalidAntiForgeryCookie() - { - // DNN-9394: when upgrade from old version which use MVC version below than 5, it may saved antiforgery cookie - // with a different cookie name which join the root path even equals to "/", then it will cause API request failed. - // we need remove the cookie during upgrade process. - var appPath = HttpRuntime.AppDomainAppVirtualPath; - if (appPath == "/" && HttpContext.Current != null) - { - var cookieSuffix = Convert.ToBase64String(Encoding.UTF8.GetBytes(appPath)).Replace('+', '.').Replace('/', '-').Replace('=', '_'); - var cookieName = $"__RequestVerificationToken_{cookieSuffix}"; - var invalidCookie = HttpContext.Current.Request.Cookies[cookieName]; - if (invalidCookie != null) - { - invalidCookie.Expires = DateTime.Now.AddYears(-1); - HttpContext.Current.Response.Cookies.Add(invalidCookie); + validDependentAssembly = webConfig.CreateElement("dependentAssembly", "urn:schemas-microsoft-com:asm.v1"); + validDependentAssembly.AppendChild(validAssemblyIdentity); + validDependentAssembly.AppendChild(validBindingRedirect); - return true; - } + assemblyBindingElement.ReplaceChild(validDependentAssembly, dependentAssembly); } - return false; + if (invalidDependentAssemblies.Count > 0) + { + Config.Save(webConfig); + } } - internal static void CheckFipsCompilanceAssemblies() + private static void UpgradeToVersion960() { - var currentVersion = Globals.FormatVersion(DotNetNukeContext.Current.Application.Version); - if (CryptoConfig.AllowOnlyFipsAlgorithms && HostController.Instance.GetString(FipsCompilanceAssembliesCheckedKey) != currentVersion) - { - var assemblyFolder = Path.Combine(Globals.ApplicationMapPath, FipsCompilanceAssembliesFolder); - var assemblyFiles = Directory.GetFiles(assemblyFolder, "*.dll", SearchOption.TopDirectoryOnly); - foreach (var assemblyFile in assemblyFiles) - { - FixFipsCompilanceAssembly(assemblyFile); - } - - HostController.Instance.Update(FipsCompilanceAssembliesCheckedKey, currentVersion); - - if (HttpContext.Current != null) - { - Globals.Redirect(HttpContext.Current.Request.RawUrl, true); - } - } + // Set default end user upload extension whitelist - ensure we don't add extensions that were not in the master list before + var toAdd = new List { ".export" }; + HostController.Instance.Update("FileExtensions", Host.AllowedExtensionWhitelist.ToStorageString(toAdd)); + var exts = new FileExtensionWhitelist("jpg,jpeg,jpe,gif,bmp,png,svg,doc,docx,xls,xlsx,ppt,pptx,pdf,txt,zip,rar,ico,avi,mpg,mpeg,mp3,wmv,mov,wav,mp4,webm,ogv,export"); + exts.RestrictBy(Host.AllowedExtensionWhitelist); + HostController.Instance.Update("DefaultEndUserExtensionWhitelist", exts.ToStorageString()); } private static void FixFipsCompilanceAssembly(string filePath) diff --git a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs index e30ce3fa263..068f990611e 100644 --- a/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs +++ b/DNN Platform/Library/Services/Url/FriendlyUrl/FriendlyUrlProvider.cs @@ -11,13 +11,13 @@ namespace DotNetNuke.Services.Url.FriendlyUrl using DotNetNuke.Entities.Tabs; public abstract class FriendlyUrlProvider - { - // return the provider + { + // return the provider public static FriendlyUrlProvider Instance() { return ComponentFactory.GetComponent(); - } - + } + public abstract string FriendlyUrl(TabInfo tab, string path); public abstract string FriendlyUrl(TabInfo tab, string path, string pageName); @@ -30,6 +30,6 @@ public virtual string FriendlyUrl(TabInfo tab, string path, string pageName, Por public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, IPortalSettings settings); - public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias); + public abstract string FriendlyUrl(TabInfo tab, string path, string pageName, string portalAlias); } } diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs index 97ec3cb659d..29524542b57 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePageHandler.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Services.UserProfile public class UserProfilePageHandler : IHttpHandler { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserProfilePageHandler)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(UserProfilePageHandler)); public bool IsReusable { @@ -22,8 +22,8 @@ public bool IsReusable { return true; } - } - + } + /// ----------------------------------------------------------------------------- /// /// This handler handles requests for LinkClick.aspx, but only those specifc @@ -92,7 +92,7 @@ public void ProcessRequest(HttpContext context) catch (Exception exc) { Logger.Debug(exc); - + // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(context.Request); } @@ -100,7 +100,7 @@ public void ProcessRequest(HttpContext context) // Redirect to Userprofile Page context.Response.Redirect(Globals.UserProfileURL(UserId), true); } - + private static int GetUserId(string username, int PortalId) { int _UserId = Null.NullInteger; @@ -114,7 +114,7 @@ private static int GetUserId(string username, int PortalId) // The user cannot be found (potential DOS) Exceptions.Exceptions.ProcessHttpException(); } - + return _UserId; } } diff --git a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs index 206c6a023b6..92d163a0189 100644 --- a/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs +++ b/DNN Platform/Library/Services/UserProfile/UserProfilePicHandler.cs @@ -18,8 +18,8 @@ namespace DotNetNuke.Services.UserProfile using DotNetNuke.Services.Localization.Internal; public class UserProfilePicHandler : IHttpHandler - { - private static object _locker = new object(); + { + private static object _locker = new object(); public bool IsReusable { @@ -27,8 +27,8 @@ public bool IsReusable { return false; } - } - + } + public void ProcessRequest(HttpContext context) { this.SetupCulture(); @@ -53,7 +53,7 @@ public void ProcessRequest(HttpContext context) { height = Convert.ToInt32(context.Request.QueryString["h"]); } - + if (!string.IsNullOrEmpty(context.Request.QueryString["size"])) { size = context.Request.QueryString["size"]; @@ -64,16 +64,16 @@ public void ProcessRequest(HttpContext context) Exceptions.Exceptions.ProcessHttpException(context.Request); } - if (height > 128) - { - height = 128; - } - - if (width > 128) - { - width = 128; - } - + if (height > 128) + { + height = 128; + } + + if (width > 128) + { + width = 128; + } + this.CalculateSize(ref height, ref width, ref size); PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); @@ -207,7 +207,7 @@ private void CalculateSize(ref int height, ref int width, ref string size) width = 128; size = "xl"; } - + // set a default if unprocessed if (string.IsNullOrEmpty(size)) { @@ -231,11 +231,11 @@ private bool IsImageExtension(string extension) private void SetupCulture() { PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings(); - if (settings == null) - { - return; - } - + if (settings == null) + { + return; + } + CultureInfo pageLocale = TestableLocalization.Instance.GetPageLocale(settings); if (pageLocale != null) { diff --git a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs index bcd881e1381..7ac2bad9dc1 100644 --- a/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs +++ b/DNN Platform/Library/Services/UserRequest/UserRequestIPAddressController.cs @@ -57,7 +57,7 @@ public string GetUserRequestIPAddress(HttpRequestBase request, IPAddressFamily i return userIPAddress; } - + protected override Func GetFactory() { return () => new UserRequestIPAddressController(); @@ -81,7 +81,7 @@ private bool ValidateIP(string ipString, IPAddressFamily ipFamily) return true; } } - + return false; } } diff --git a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs index 6ee82b41a23..a1a3643e916 100644 --- a/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs +++ b/DNN Platform/Library/Services/Users/PurgeDeletedUsers.cs @@ -40,7 +40,7 @@ public override void DoWork() thresholdDate = DateTime.Now.AddDays(-7 * settings.DataConsentDelay); break; } - + var deletedUsers = UserController.GetDeletedUsers(portal.PortalID); foreach (UserInfo user in deletedUsers) { @@ -53,7 +53,7 @@ public override void DoWork() } } } - + this.ScheduleHistoryItem.Succeeded = true; // REQUIRED this.ScheduleHistoryItem.AddLogNote("Purging deleted users task completed"); } diff --git a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs index 4ba5d8afaa4..08481874a85 100644 --- a/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs +++ b/DNN Platform/Library/Services/Zip/SharpZipLibRedirect.cs @@ -27,7 +27,7 @@ internal class SharpZipLibRedirect { private const string OldName = "SharpZipLib"; private const string NewName = "ICSharpCode.SharpZipLib"; - + internal static bool AlreadyRun { get; private set; } /// @@ -40,7 +40,7 @@ internal static void RegisterSharpZipLibRedirect() { return; } - + // stop any further attempts to access this AlreadyRun = true; diff --git a/DNN Platform/Library/UI/Containers/ActionBase.cs b/DNN Platform/Library/UI/Containers/ActionBase.cs index d07c7a51fe5..cdd7cff710c 100644 --- a/DNN Platform/Library/UI/Containers/ActionBase.cs +++ b/DNN Platform/Library/UI/Containers/ActionBase.cs @@ -49,6 +49,31 @@ public bool SupportsIcons } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the ActionManager instance for this Action control. + /// + /// An ActionManager object. + public ActionManager ActionManager + { + get + { + if (this._ActionManager == null) + { + this._ActionManager = new ActionManager(this); + } + + return this._ActionManager; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the ModuleControl instance for this Action control. + /// + /// An IModuleControl object. + public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets the Actions Collection. @@ -106,31 +131,6 @@ protected PortalSettings PortalSettings } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the ActionManager instance for this Action control. - /// - /// An ActionManager object. - public ActionManager ActionManager - { - get - { - if (this._ActionManager == null) - { - this._ActionManager = new ActionManager(this); - } - - return this._ActionManager; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the ModuleControl instance for this Action control. - /// - /// An IModuleControl object. - public IModuleControl ModuleControl { get; set; } - /// ----------------------------------------------------------------------------- /// /// DisplayControl determines whether the control should be displayed. diff --git a/DNN Platform/Library/UI/Containers/ActionButton.cs b/DNN Platform/Library/UI/Containers/ActionButton.cs index d6da3b1f1be..2fa226fe106 100644 --- a/DNN Platform/Library/UI/Containers/ActionButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionButton.cs @@ -22,8 +22,8 @@ namespace DotNetNuke.UI.Containers [Obsolete("This class has been deprecated in favour of the new ActionCommandButton and ActionButtonList.. Scheduled removal in v11.0.0.")] public class ActionButton : ActionBase { - private ActionButtonList _ButtonList; - + private ActionButtonList _ButtonList; + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Command Name. @@ -40,7 +40,7 @@ public string CommandName this.EnsureChildControls(); return this._ButtonList.CommandName; } - + set { this.EnsureChildControls(); @@ -64,7 +64,7 @@ public string CssClass this.EnsureChildControls(); return this._ButtonList.CssClass; } - + set { this.EnsureChildControls(); @@ -88,7 +88,7 @@ public bool DisplayLink this.EnsureChildControls(); return this._ButtonList.DisplayLink; } - + set { this.EnsureChildControls(); @@ -112,7 +112,7 @@ public bool DisplayIcon this.EnsureChildControls(); return this._ButtonList.DisplayIcon; } - + set { this.EnsureChildControls(); @@ -136,7 +136,7 @@ public string IconFile this.EnsureChildControls(); return this._ButtonList.ImageURL; } - + set { this.EnsureChildControls(); @@ -160,14 +160,14 @@ public string ButtonSeparator this.EnsureChildControls(); return this._ButtonList.ButtonSeparator; } - + set { this.EnsureChildControls(); this._ButtonList.ButtonSeparator = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// CreateChildControls builds the control tree. @@ -181,8 +181,8 @@ protected override void CreateChildControls() this._ButtonList.Action += this.Action_Click; this.Controls.Add(this._ButtonList); - } - + } + /// ----------------------------------------------------------------------------- /// /// Action_Click responds to an Action Event in the contained actionButtonList. @@ -191,6 +191,6 @@ protected override void CreateChildControls() 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 3fec63ab692..eaa08f68cca 100644 --- a/DNN Platform/Library/UI/Containers/ActionButtonList.cs +++ b/DNN Platform/Library/UI/Containers/ActionButtonList.cs @@ -27,6 +27,24 @@ public class ActionButtonList : CompositeControl, IActionControl public event ActionEventHandler Action; + /// ----------------------------------------------------------------------------- + /// + /// Gets the ActionManager instance for this Action control. + /// + /// An ActionManager object. + public ActionManager ActionManager + { + get + { + if (this._ActionManager == null) + { + this._ActionManager = new ActionManager(this); + } + + return this._ActionManager; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Separator between Buttons. @@ -65,24 +83,6 @@ 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. @@ -120,29 +120,29 @@ public bool DisplayLink /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control. + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An ActionManager object. - public ActionManager ActionManager + /// An IModuleControl object. + public IModuleControl ModuleControl { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ModuleActionCollection to bind to the list. + /// + /// A ModuleActionCollection. + protected ModuleActionCollection ModuleActions { get { - if (this._ActionManager == null) + if (this._ModuleActions == null) { - this._ActionManager = new ActionManager(this); + this._ModuleActions = this.ModuleControl.ModuleContext.Actions.GetActionsByCommandName(this.CommandName); } - return this._ActionManager; + return this._ModuleActions; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the ModuleControl instance for this Action control. - /// - /// An IModuleControl object. - public IModuleControl ModuleControl { get; set; } - /// ----------------------------------------------------------------------------- /// /// OnAction raises the Action Event. diff --git a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs index a5395382530..4010a70062b 100644 --- a/DNN Platform/Library/UI/Containers/ActionCommandButton.cs +++ b/DNN Platform/Library/UI/Containers/ActionCommandButton.cs @@ -23,52 +23,52 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public class ActionCommandButton : CommandButton, IActionControl - { + { private ActionManager _ActionManager; - private ModuleAction _ModuleAction; - + private ModuleAction _ModuleAction; + public event ActionEventHandler Action; - + /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the ModuleAction for this Action control. + /// Gets the ActionManager instance for this Action control. /// - /// A ModuleAction object. + /// An ActionManager object. /// ----------------------------------------------------------------------------- - public ModuleAction ModuleAction + public ActionManager ActionManager { get { - if (this._ModuleAction == null) + if (this._ActionManager == null) { - this._ModuleAction = this.ModuleControl.ModuleContext.Actions.GetActionByCommandName(this.CommandName); + this._ActionManager = new ActionManager(this); } - - return this._ModuleAction; - } - - set - { - this._ModuleAction = value; + + return this._ActionManager; } - } + } /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control. + /// Gets or sets and sets the ModuleAction for this Action control. /// - /// An ActionManager object. + /// A ModuleAction object. /// ----------------------------------------------------------------------------- - public ActionManager ActionManager + public ModuleAction ModuleAction { get { - if (this._ActionManager == null) + if (this._ModuleAction == null) { - this._ActionManager = new ActionManager(this); + this._ModuleAction = this.ModuleControl.ModuleContext.Actions.GetActionByCommandName(this.CommandName); } - - return this._ActionManager; + + return this._ModuleAction; + } + + set + { + this._ModuleAction = value; } } @@ -78,8 +78,8 @@ public ActionManager ActionManager /// /// An IModuleControl object. /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } - + public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- /// /// CreateChildControls builds the control tree. @@ -154,13 +154,13 @@ protected override void OnPreRender(EventArgs e) } } } - + this.ActionManager.GetClientScriptURL(this.ModuleAction, this); } else { this.Visible = false; } - } + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionManager.cs b/DNN Platform/Library/UI/Containers/ActionManager.cs index c1272643670..b0c87b52176 100644 --- a/DNN Platform/Library/UI/Containers/ActionManager.cs +++ b/DNN Platform/Library/UI/Containers/ActionManager.cs @@ -32,13 +32,13 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public class ActionManager - { + { private readonly PortalSettings PortalSettings = PortalController.Instance.GetCurrentPortalSettings(); private readonly HttpRequest Request = HttpContext.Current.Request; - private readonly HttpResponse Response = HttpContext.Current.Response; - + private readonly HttpResponse Response = HttpContext.Current.Response; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new ActionManager. /// @@ -46,8 +46,8 @@ public class ActionManager public ActionManager(IActionControl actionControl) { this.ActionControl = actionControl; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Action Control that is connected to this ActionManager instance. @@ -69,13 +69,13 @@ protected ModuleInstanceContext ModuleContext { return this.ActionControl.ModuleControl.ModuleContext; } - } - + } + /// ----------------------------------------------------------------------------- /// /// DisplayControl determines whether the associated Action control should be /// displayed. - /// + /// /// /// ----------------------------------------------------------------------------- public bool DisplayControl(DNNNodeCollection objNodes) @@ -101,7 +101,7 @@ public bool DisplayControl(DNNNodeCollection objNodes) } } } - + return false; } @@ -109,134 +109,19 @@ public bool DisplayControl(DNNNodeCollection objNodes) /// /// GetAction gets the action associated with the commandName. /// - /// The command name. + /// The command name. /// /// ----------------------------------------------------------------------------- public ModuleAction GetAction(string commandName) { return this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByCommandName(commandName); } - - private void ClearCache(ModuleAction Command) - { - // synchronize cache - ModuleController.SynchronizeModule(this.ModuleContext.ModuleId); - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } - - private void Delete(ModuleAction Command) - { - var module = ModuleController.Instance.GetModule(int.Parse(Command.CommandArgument), this.ModuleContext.TabId, true); - - // Check if this is the owner instance of a shared module. - var user = UserController.Instance.GetCurrentUserInfo(); - if (!module.IsShared) - { - foreach (ModuleInfo instance in ModuleController.Instance.GetTabModulesByModule(module.ModuleID)) - { - if (instance.IsShared) - { - // HARD Delete Shared Instance - ModuleController.Instance.DeleteTabModule(instance.TabID, instance.ModuleID, false); - EventLogController.Instance.AddLog(instance, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_DELETED); - } - } - } - - ModuleController.Instance.DeleteTabModule(this.ModuleContext.TabId, int.Parse(Command.CommandArgument), true); - EventLogController.Instance.AddLog(module, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_SENT_TO_RECYCLE_BIN); - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } - - private void DoAction(ModuleAction Command) - { - if (Command.NewWindow) - { - UrlUtils.OpenNewWindow(this.ActionControl.ModuleControl.Control.Page, this.GetType(), Command.Url); - } - else - { - this.Response.Redirect(Command.Url, true); - } - } - - private void Localize(ModuleAction Command) - { - ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); - - switch (Command.CommandName) - { - case ModuleActionType.LocalizeModule: - ModuleController.Instance.LocalizeModule(sourceModule, LocaleController.Instance.GetCurrentLocale(this.ModuleContext.PortalId)); - break; - case ModuleActionType.DeLocalizeModule: - ModuleController.Instance.DeLocalizeModule(sourceModule); - break; - } - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } - - private void Translate(ModuleAction Command) - { - ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); - switch (Command.CommandName) - { - case ModuleActionType.TranslateModule: - ModuleController.Instance.UpdateTranslationStatus(sourceModule, true); - break; - case ModuleActionType.UnTranslateModule: - ModuleController.Instance.UpdateTranslationStatus(sourceModule, false); - break; - } - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } - - private void MoveToPane(ModuleAction Command) - { - ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, -1, Command.CommandArgument); - ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } - - private void MoveUpDown(ModuleAction Command) - { - switch (Command.CommandName) - { - case ModuleActionType.MoveTop: - ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, 0, Command.CommandArgument); - break; - case ModuleActionType.MoveUp: - ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder - 3, Command.CommandArgument); - break; - case ModuleActionType.MoveDown: - ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder + 3, Command.CommandArgument); - break; - case ModuleActionType.MoveBottom: - ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, (this.ModuleContext.Configuration.PaneModuleCount * 2) + 1, Command.CommandArgument); - break; - } - - ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); - - // Redirect to the same page to pick up changes - this.Response.Redirect(this.Request.RawUrl, true); - } /// ----------------------------------------------------------------------------- /// /// GetAction gets the action associated with the id. /// - /// The Id. + /// The Id. /// /// ----------------------------------------------------------------------------- public ModuleAction GetAction(int id) @@ -262,7 +147,7 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) { Script = Script.Substring(JSPos + 11); } - + string FormatScript = "javascript: return {0};"; control.Attributes.Add("onClick", string.Format(FormatScript, Script)); } @@ -272,7 +157,7 @@ public void GetClientScriptURL(ModuleAction action, WebControl control) /// /// IsVisible determines whether the action control is Visible. /// - /// The Action. + /// The Action. /// /// ----------------------------------------------------------------------------- public bool IsVisible(ModuleAction action) @@ -293,7 +178,7 @@ public bool IsVisible(ModuleAction action) { _IsVisible = false; } - + return _IsVisible; } @@ -301,7 +186,7 @@ public bool IsVisible(ModuleAction action) /// /// ProcessAction processes the action. /// - /// The Id of the Action. + /// The Id of the Action. /// /// ----------------------------------------------------------------------------- public bool ProcessAction(string id) @@ -312,7 +197,7 @@ public bool ProcessAction(string id) { bProcessed = this.ProcessAction(this.ActionControl.ModuleControl.ModuleContext.Actions.GetActionByID(nid)); } - + return bProcessed; } @@ -320,7 +205,7 @@ public bool ProcessAction(string id) /// /// ProcessAction processes the action. /// - /// The Action. + /// The Action. /// /// ----------------------------------------------------------------------------- public bool ProcessAction(ModuleAction action) @@ -377,11 +262,126 @@ public bool ProcessAction(ModuleAction action) { bProcessed = false; } - + break; } - + return bProcessed; - } + } + + private void ClearCache(ModuleAction Command) + { + // synchronize cache + ModuleController.SynchronizeModule(this.ModuleContext.ModuleId); + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } + + private void Delete(ModuleAction Command) + { + var module = ModuleController.Instance.GetModule(int.Parse(Command.CommandArgument), this.ModuleContext.TabId, true); + + // Check if this is the owner instance of a shared module. + var user = UserController.Instance.GetCurrentUserInfo(); + if (!module.IsShared) + { + foreach (ModuleInfo instance in ModuleController.Instance.GetTabModulesByModule(module.ModuleID)) + { + if (instance.IsShared) + { + // HARD Delete Shared Instance + ModuleController.Instance.DeleteTabModule(instance.TabID, instance.ModuleID, false); + EventLogController.Instance.AddLog(instance, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_DELETED); + } + } + } + + ModuleController.Instance.DeleteTabModule(this.ModuleContext.TabId, int.Parse(Command.CommandArgument), true); + EventLogController.Instance.AddLog(module, this.PortalSettings, user.UserID, string.Empty, EventLogController.EventLogType.MODULE_SENT_TO_RECYCLE_BIN); + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } + + private void DoAction(ModuleAction Command) + { + if (Command.NewWindow) + { + UrlUtils.OpenNewWindow(this.ActionControl.ModuleControl.Control.Page, this.GetType(), Command.Url); + } + else + { + this.Response.Redirect(Command.Url, true); + } + } + + private void Localize(ModuleAction Command) + { + ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); + + switch (Command.CommandName) + { + case ModuleActionType.LocalizeModule: + ModuleController.Instance.LocalizeModule(sourceModule, LocaleController.Instance.GetCurrentLocale(this.ModuleContext.PortalId)); + break; + case ModuleActionType.DeLocalizeModule: + ModuleController.Instance.DeLocalizeModule(sourceModule); + break; + } + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } + + private void Translate(ModuleAction Command) + { + ModuleInfo sourceModule = ModuleController.Instance.GetModule(this.ModuleContext.ModuleId, this.ModuleContext.TabId, false); + switch (Command.CommandName) + { + case ModuleActionType.TranslateModule: + ModuleController.Instance.UpdateTranslationStatus(sourceModule, true); + break; + case ModuleActionType.UnTranslateModule: + ModuleController.Instance.UpdateTranslationStatus(sourceModule, false); + break; + } + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } + + private void MoveToPane(ModuleAction Command) + { + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, -1, Command.CommandArgument); + ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } + + private void MoveUpDown(ModuleAction Command) + { + switch (Command.CommandName) + { + case ModuleActionType.MoveTop: + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, 0, Command.CommandArgument); + break; + case ModuleActionType.MoveUp: + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder - 3, Command.CommandArgument); + break; + case ModuleActionType.MoveDown: + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, this.ModuleContext.Configuration.ModuleOrder + 3, Command.CommandArgument); + break; + case ModuleActionType.MoveBottom: + ModuleController.Instance.UpdateModuleOrder(this.ModuleContext.TabId, this.ModuleContext.ModuleId, (this.ModuleContext.Configuration.PaneModuleCount * 2) + 1, Command.CommandArgument); + break; + } + + ModuleController.Instance.UpdateTabModuleOrder(this.ModuleContext.TabId); + + // Redirect to the same page to pick up changes + this.Response.Redirect(this.Request.RawUrl, true); + } } } diff --git a/DNN Platform/Library/UI/Containers/ActionsMenu.cs b/DNN Platform/Library/UI/Containers/ActionsMenu.cs index cbfa0303de7..486fc52b542 100644 --- a/DNN Platform/Library/UI/Containers/ActionsMenu.cs +++ b/DNN Platform/Library/UI/Containers/ActionsMenu.cs @@ -28,15 +28,34 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public class ActionsMenu : Control, IActionControl - { + { private ActionManager _ActionManager; private ModuleAction _ActionRoot; private int _ExpandDepth = -1; private NavigationProvider _ProviderControl; - private string _ProviderName = "DNNMenuNavigationProvider"; - + private string _ProviderName = "DNNMenuNavigationProvider"; + public event ActionEventHandler Action; - + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ActionManager instance for this Action control. + /// + /// An ActionManager object. + /// ----------------------------------------------------------------------------- + public ActionManager ActionManager + { + get + { + if (this._ActionManager == null) + { + this._ActionManager = new ActionManager(this); + } + + return this._ActionManager; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and Sets the Expansion Depth for the Control. @@ -51,10 +70,10 @@ public int ExpandDepth { return -1; } - + return this._ExpandDepth; } - + set { this._ExpandDepth = value; @@ -68,39 +87,6 @@ public int ExpandDepth /// A String. /// ----------------------------------------------------------------------------- public string PathSystemScript { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the ActionRoot. - /// - /// A ModuleActionCollection. - /// ----------------------------------------------------------------------------- - protected ModuleAction ActionRoot - { - get - { - if (this._ActionRoot == null) - { - this._ActionRoot = new ModuleAction(this.ModuleControl.ModuleContext.GetNextActionID(), " ", string.Empty, string.Empty, "action.gif"); - } - - return this._ActionRoot; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Provider Control. - /// - /// A NavigationProvider. - /// ----------------------------------------------------------------------------- - protected NavigationProvider ProviderControl - { - get - { - return this._ProviderControl; - } - } /// ----------------------------------------------------------------------------- /// @@ -122,40 +108,54 @@ public string ProviderName { return this._ProviderName; } - + set { this._ProviderName = value; } - } + } /// ----------------------------------------------------------------------------- /// - /// Gets the ActionManager instance for this Action control. + /// Gets or sets and sets the ModuleControl instance for this Action control. /// - /// An ActionManager object. + /// An IModuleControl object. /// ----------------------------------------------------------------------------- - public ActionManager ActionManager + public IModuleControl ModuleControl { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the ActionRoot. + /// + /// A ModuleActionCollection. + /// ----------------------------------------------------------------------------- + protected ModuleAction ActionRoot { get { - if (this._ActionManager == null) + if (this._ActionRoot == null) { - this._ActionManager = new ActionManager(this); + this._ActionRoot = new ModuleAction(this.ModuleControl.ModuleContext.GetNextActionID(), " ", string.Empty, string.Empty, "action.gif"); } - - return this._ActionManager; + + return this._ActionRoot; } } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the ModuleControl instance for this Action control. + /// Gets the Provider Control. /// - /// An IModuleControl object. + /// A NavigationProvider. /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } - + protected NavigationProvider ProviderControl + { + get + { + return this._ProviderControl; + } + } + /// ----------------------------------------------------------------------------- /// /// BindMenu binds the Navigation Provider to the Node Collection. @@ -178,7 +178,49 @@ protected virtual void OnAction(ActionEventArgs e) this.Action(this, e); } } - + + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs during the controls initialisation phase. + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + this._ProviderControl = NavigationProvider.Instance(this.ProviderName); + this.ProviderControl.PopulateOnDemand += this.ProviderControl_PopulateOnDemand; + base.OnInit(e); + this.ProviderControl.ControlID = "ctl" + this.ID; + this.ProviderControl.Initialize(); + this.Controls.Add(this.ProviderControl.NavigationControl); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnLoad runs during the controls load phase. + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + // Add the Actions to the Action Root + this.ActionRoot.Actions.AddRange(this.ModuleControl.ModuleContext.Actions); + + // Set Menu Defaults + this.SetMenuDefaults(); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnPreRender runs during the controls pre-render phase. + /// + /// ----------------------------------------------------------------------------- + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + this.BindMenu(); + } + /// ----------------------------------------------------------------------------- /// /// BindMenu binds the Navigation Provider to the Node Collection. @@ -196,7 +238,7 @@ private void BindMenu(DNNNodeCollection objNodes) { this.ProcessNodes(objNode); } - + this.ProviderControl.Bind(objNodes); } } @@ -213,7 +255,7 @@ private void ProcessNodes(DNNNode objParent) { objParent.JSFunction = string.Format("if({0}){{{1}}};", objParent.JSFunction, this.Page.ClientScript.GetPostBackEventReference(this.ProviderControl.NavigationControl, objParent.ID)); } - + foreach (DNNNode objNode in objParent.DNNNodes) { this.ProcessNodes(objNode); @@ -257,50 +299,8 @@ private void SetMenuDefaults() { Exceptions.ProcessModuleLoadException(this, exc); } - } - - /// ----------------------------------------------------------------------------- - /// - /// OnInit runs during the controls initialisation phase. - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - this._ProviderControl = NavigationProvider.Instance(this.ProviderName); - this.ProviderControl.PopulateOnDemand += this.ProviderControl_PopulateOnDemand; - base.OnInit(e); - this.ProviderControl.ControlID = "ctl" + this.ID; - this.ProviderControl.Initialize(); - this.Controls.Add(this.ProviderControl.NavigationControl); } - /// ----------------------------------------------------------------------------- - /// - /// OnLoad runs during the controls load phase. - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - // Add the Actions to the Action Root - this.ActionRoot.Actions.AddRange(this.ModuleControl.ModuleContext.Actions); - - // Set Menu Defaults - this.SetMenuDefaults(); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnPreRender runs during the controls pre-render phase. - /// - /// ----------------------------------------------------------------------------- - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - this.BindMenu(); - } - /// ----------------------------------------------------------------------------- /// /// MenuItem_Click handles the Menu Click event. @@ -333,14 +333,14 @@ private void ProviderControl_PopulateOnDemand(NavigationEventArgs args) { objAction = this.ModuleControl.ModuleContext.Actions.GetActionByID(Convert.ToInt32(args.ID)); } - + if (args.Node == null) { args.Node = Navigation.GetActionNode(args.ID, this.ProviderControl.ID, objAction, this); } - + this.ProviderControl.ClearNodes(); // since we always bind we need to clear the nodes for providers that maintain their state this.BindMenu(Navigation.GetActionNodes(objAction, args.Node, this, this.ExpandDepth)); - } + } } } diff --git a/DNN Platform/Library/UI/Containers/Container.cs b/DNN Platform/Library/UI/Containers/Container.cs index 7ecdd5bf0dc..4b495e2ca00 100644 --- a/DNN Platform/Library/UI/Containers/Container.cs +++ b/DNN Platform/Library/UI/Containers/Container.cs @@ -77,31 +77,6 @@ public ModuleInfo ModuleConfiguration } } - /// - /// Gets the Content Pane Control (Id="ContentPane"). - /// - /// An HtmlContainerControl. - protected HtmlContainerControl ContentPane - { - get - { - return this._contentPane ?? (this._contentPane = this.FindControl(Globals.glbDefaultPane) as HtmlContainerControl); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Portal Settings for the current Portal. - /// - /// A PortalSettings object. - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the ModuleHost object that this container is displaying. @@ -151,6 +126,31 @@ public string ContainerPath internal bool InjectActionMenu { get; set; } + /// + /// Gets the Content Pane Control (Id="ContentPane"). + /// + /// An HtmlContainerControl. + protected HtmlContainerControl ContentPane + { + get + { + return this._contentPane ?? (this._contentPane = this.FindControl(Globals.glbDefaultPane) as HtmlContainerControl); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Portal Settings for the current Portal. + /// + /// A PortalSettings object. + protected PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + public void SetModuleConfiguration(ModuleInfo configuration) { this._moduleConfiguration = configuration; @@ -178,6 +178,28 @@ protected override void OnLoad(EventArgs e) this.InvokeContainerEvents(ContainerEventType.OnContainerLoad); } + /// ----------------------------------------------------------------------------- + /// + /// OnLoad runs just before the Container is rendered. + /// + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerPreRender); + } + + /// ----------------------------------------------------------------------------- + /// + /// OnUnLoad runs when the Container is unloaded. + /// + protected override void OnUnload(EventArgs e) + { + base.OnUnload(e); + + this.InvokeContainerEvents(ContainerEventType.OnContainerUnLoad); + } + private void AddAdministratorOnlyHighlighting(string message) { this.ContentPane.Controls.Add(new LiteralControl(string.Format("
    {0}
    ", message))); @@ -451,28 +473,6 @@ private void SetBorder() } } - /// ----------------------------------------------------------------------------- - /// - /// OnLoad runs just before the Container is rendered. - /// - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - this.InvokeContainerEvents(ContainerEventType.OnContainerPreRender); - } - - /// ----------------------------------------------------------------------------- - /// - /// OnUnLoad runs when the Container is unloaded. - /// - protected override void OnUnload(EventArgs e) - { - base.OnUnload(e); - - this.InvokeContainerEvents(ContainerEventType.OnContainerUnLoad); - } - private void InvokeContainerEvents(ContainerEventType containerEventType) { SharedList list = ((NaiveLockingList)DotNetNukeContext.Current.ContainerEventListeners).SharedList; diff --git a/DNN Platform/Library/UI/Containers/IActionControl.cs b/DNN Platform/Library/UI/Containers/IActionControl.cs index e5428c256e7..7d8d7bb61ba 100644 --- a/DNN Platform/Library/UI/Containers/IActionControl.cs +++ b/DNN Platform/Library/UI/Containers/IActionControl.cs @@ -18,9 +18,9 @@ namespace DotNetNuke.UI.Containers public interface IActionControl { event ActionEventHandler Action; - + ActionManager ActionManager { get; } - + IModuleControl ModuleControl { get; set; } } } diff --git a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs index bad4b26280f..80390a86a8c 100644 --- a/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs +++ b/DNN Platform/Library/UI/ControlPanels/ControlPanelBase.cs @@ -40,6 +40,11 @@ protected enum ViewPermissionType Edit = 1, } + public virtual bool IncludeInControlHierarchy + { + get { return true; } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Local ResourceFile for the Control Panel. @@ -69,9 +74,10 @@ public string LocalResourceFile } } - public virtual bool IncludeInControlHierarchy + public virtual bool IsDockable { - get { return true; } + get { return false; } + set { } } /// ----------------------------------------------------------------------------- @@ -115,12 +121,6 @@ protected PortalSettings.Mode UserMode } } - public virtual bool IsDockable - { - get { return false; } - set { } - } - internal static bool IsModuleAdminInternal() { bool _IsModuleAdmin = Null.NullBoolean; @@ -356,35 +356,6 @@ 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. @@ -458,5 +429,34 @@ protected override void OnInit(EventArgs e) base.OnInit(e); } } + + /// ----------------------------------------------------------------------------- + /// + /// 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; + } } } diff --git a/DNN Platform/Library/UI/ControlUtilities.cs b/DNN Platform/Library/UI/ControlUtilities.cs index 3099949d7cd..0914cc20085 100644 --- a/DNN Platform/Library/UI/ControlUtilities.cs +++ b/DNN Platform/Library/UI/ControlUtilities.cs @@ -10,8 +10,8 @@ namespace DotNetNuke.UI public class ControlUtilities { - public static T FindParentControl(Control control) - where T : Control + public static T FindParentControl(Control control) + where T : Control { T parent = default(T); if (control.Parent == null) @@ -30,12 +30,12 @@ public static T FindParentControl(Control control) parent = FindParentControl(control.Parent); } } - + return parent; } - public static T FindControl(Control control, string id, bool recursive) - where T : Control + public static T FindControl(Control control, string id, bool recursive) + where T : Control { T target = null; if (control.Parent != null) @@ -51,29 +51,29 @@ public static T FindControl(Control control, string id, bool recursive) return target; } - public static T FindFirstDescendent(Control control) - where T : Control - { + public static T FindFirstDescendent(Control control) + where T : Control + { return FindFirstDescendent(control, idx => idx is T); } - public static T FindFirstDescendent(Control control, Predicate predicate) - where T : Control - { - if (predicate(control)) - { - return control as T; - } - - foreach (Control childControl in control.Controls) - { - T descendent = FindFirstDescendent(childControl, predicate); - if (descendent != null) - { - return descendent; - } - } - + public static T FindFirstDescendent(Control control, Predicate predicate) + where T : Control + { + if (predicate(control)) + { + return control as T; + } + + foreach (Control childControl in control.Controls) + { + T descendent = FindFirstDescendent(childControl, predicate); + if (descendent != null) + { + return descendent; + } + } + return null; } @@ -87,8 +87,8 @@ public static T FindFirstDescendent(Control control, Predicate predi /// control. /// A Control of type T. /// ----------------------------------------------------------------------------- - public static T LoadControl(TemplateControl containerControl, string ControlSrc) - where T : Control + public static T LoadControl(TemplateControl containerControl, string ControlSrc) + where T : Control { T ctrl; @@ -104,7 +104,7 @@ public static T LoadControl(TemplateControl containerControl, string ControlS Type objType = Reflection.CreateType(ControlSrc); ctrl = (T)containerControl.LoadControl(objType, null); } - + return ctrl; } } diff --git a/DNN Platform/Library/UI/FavIcon.cs b/DNN Platform/Library/UI/FavIcon.cs index 96b6723baa8..34193cd6218 100644 --- a/DNN Platform/Library/UI/FavIcon.cs +++ b/DNN Platform/Library/UI/FavIcon.cs @@ -19,9 +19,9 @@ public class FavIcon { private const string SettingName = "FavIconPath"; - private readonly int _portalId; - - /// + private readonly int _portalId; + + /// /// Initializes a new instance of the class. /// Initializes a FavIcon instance. /// diff --git a/DNN Platform/Library/UI/Modules/CachedModuleControl.cs b/DNN Platform/Library/UI/Modules/CachedModuleControl.cs index 5c92862b2dd..a2604802fbb 100644 --- a/DNN Platform/Library/UI/Modules/CachedModuleControl.cs +++ b/DNN Platform/Library/UI/Modules/CachedModuleControl.cs @@ -21,10 +21,10 @@ namespace DotNetNuke.UI.Modules public class CachedModuleControl : Literal, IModuleControl { private string _localResourceFile; - private ModuleInstanceContext _moduleContext; - + private ModuleInstanceContext _moduleContext; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new CachedModuleControl. /// @@ -33,8 +33,8 @@ public class CachedModuleControl : Literal, IModuleControl public CachedModuleControl(string cachedContent) { this.Text = cachedContent; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the underlying base control for this ModuleControl. @@ -77,6 +77,25 @@ public string ControlName } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Module Context for this control. + /// + /// A ModuleInstanceContext. + /// ----------------------------------------------------------------------------- + public ModuleInstanceContext ModuleContext + { + get + { + if (this._moduleContext == null) + { + this._moduleContext = new ModuleInstanceContext(this); + } + + return this._moduleContext; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the local resource file for this control. @@ -97,33 +116,14 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Module Context for this control. - /// - /// A ModuleInstanceContext. - /// ----------------------------------------------------------------------------- - public ModuleInstanceContext ModuleContext - { - get - { - if (this._moduleContext == null) - { - this._moduleContext = new ModuleInstanceContext(this); - } - - return this._moduleContext; - } - } } } diff --git a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs index ad72fade265..ad6e247d266 100644 --- a/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs +++ b/DNN Platform/Library/UI/Modules/Html5/Html5HostControl.cs @@ -93,8 +93,8 @@ private string GetFileContent(string filepath) private bool FileExists(string filepath) { var cacheKey = string.Format(DataCache.SpaModulesFileExistsCacheKey, filepath); - return CBO.GetCachedObject( - new CacheItemArgs( + return CBO.GetCachedObject( + new CacheItemArgs( cacheKey, DataCache.SpaModulesHtmlFileTimeOut, DataCache.SpaModulesHtmlFileCachePriority), diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs index a69c0bf5e18..4861e1bdb58 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleContextPropertyAccess.cs @@ -45,7 +45,7 @@ public string GetProperty(string propertyName, string format, CultureInfo format { return (string)this._moduleContext.Settings[propertyName]; } - + break; } diff --git a/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs b/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs index 9b8a69e0be2..acf229a5aca 100644 --- a/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs +++ b/DNN Platform/Library/UI/Modules/Html5/ModuleLocalizationPropertyAccess.cs @@ -43,7 +43,7 @@ protected override string ProcessToken(ModuleLocalizationDto model, UserInfo acc var path = this._html5File.Replace(fileName, string.Empty); resourceFile = Path.Combine(path, Localization.LocalResourceDirectory + "/", Path.ChangeExtension(fileName, "resx")); } - + if (!string.IsNullOrEmpty(model.Key)) { returnValue = Localization.GetString(model.Key, resourceFile); diff --git a/DNN Platform/Library/UI/Modules/IModuleControl.cs b/DNN Platform/Library/UI/Modules/IModuleControl.cs index 270279f573c..3ca6034e4f6 100644 --- a/DNN Platform/Library/UI/Modules/IModuleControl.cs +++ b/DNN Platform/Library/UI/Modules/IModuleControl.cs @@ -17,13 +17,13 @@ namespace DotNetNuke.UI.Modules public interface IModuleControl { Control Control { get; } - + string ControlPath { get; } - + string ControlName { get; } - - string LocalResourceFile { get; set; } - + ModuleInstanceContext ModuleContext { get; } + + string LocalResourceFile { get; set; } } } diff --git a/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs index 93a7bb0ab82..9f5f21fd34a 100644 --- a/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/IModuleControlFactory.cs @@ -11,11 +11,11 @@ namespace DotNetNuke.UI.Modules public interface IModuleControlFactory { Control CreateControl(TemplateControl containerControl, string controlKey, string controlSrc); - + Control CreateModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration); - + ModuleControlBase CreateModuleControl(ModuleInfo moduleConfiguration); - + Control CreateSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc); } } diff --git a/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs b/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs index 85826533093..c32c6beb0ff 100644 --- a/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs +++ b/DNN Platform/Library/UI/Modules/IModuleControlPipeline.cs @@ -12,13 +12,13 @@ namespace DotNetNuke.UI.Modules public interface IModuleControlPipeline { Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlKey, string controlSrc); - + Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration); - + Control LoadSettingsControl(TemplateControl containerControl, ModuleInfo moduleConfiguration, string controlSrc); - + Control CreateCachedControl(string cachedContent, ModuleInfo moduleConfiguration); - + Control CreateModuleControl(ModuleInfo moduleConfiguration); } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlBase.cs b/DNN Platform/Library/UI/Modules/ModuleControlBase.cs index dbb705f5cc5..65a53c52584 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlBase.cs @@ -21,8 +21,8 @@ namespace DotNetNuke.UI.Modules public class ModuleControlBase : Control, IModuleControl { private string _localResourceFile; - private ModuleInstanceContext _moduleContext; - + private ModuleInstanceContext _moduleContext; + /// ----------------------------------------------------------------------------- /// /// Gets the underlying base control for this ModuleControl. @@ -65,6 +65,25 @@ public string ControlName } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Module Context for this control. + /// + /// A ModuleInstanceContext. + /// ----------------------------------------------------------------------------- + public ModuleInstanceContext ModuleContext + { + get + { + if (this._moduleContext == null) + { + this._moduleContext = new ModuleInstanceContext(this); + } + + return this._moduleContext; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the local resource file for this control. @@ -84,33 +103,14 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets the Module Context for this control. - /// - /// A ModuleInstanceContext. - /// ----------------------------------------------------------------------------- - public ModuleInstanceContext ModuleContext - { - get - { - if (this._moduleContext == null) - { - this._moduleContext = new ModuleInstanceContext(this); - } - - return this._moduleContext; - } - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs index f78fee1d849..1c80c0a07fa 100644 --- a/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs +++ b/DNN Platform/Library/UI/Modules/ModuleControlFactory.cs @@ -22,11 +22,11 @@ public class ModuleControlFactory [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) { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); @@ -49,22 +49,22 @@ public static Control LoadModuleControl(TemplateControl containerControl, Module } } - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } [Obsolete("This implementation has moved to DotNetNuke.ModulePipeline.ModuleControlFactory. Scheduled removal in v11.0.0.")] public static Control LoadModuleControl(TemplateControl containerControl, ModuleInfo moduleConfiguration) { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(moduleConfiguration.ModuleControl.ControlSrc); @@ -87,63 +87,22 @@ public static Control LoadModuleControl(TemplateControl containerControl, Module } } - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - - 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) + if (TracelLogger.IsDebugEnabled) { - 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; + TracelLogger.Debug($"ModuleControlFactory.LoadModuleControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); } - return controlFactory; + return control; } [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) { - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl Start (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + Control control = null; IModuleControlFactory controlFactory = GetModuleControlFactory(controlSrc); @@ -170,11 +129,11 @@ public static Control LoadSettingsControl(TemplateControl containerControl, Modu } } - if (TracelLogger.IsDebugEnabled) - { - TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); - } - + if (TracelLogger.IsDebugEnabled) + { + TracelLogger.Debug($"ModuleControlFactory.LoadSettingsControl End (TabId:{moduleConfiguration.TabID},ModuleId:{moduleConfiguration.ModuleID}): ModuleControlSource:{moduleConfiguration.ModuleControl.ControlSrc}"); + } + return control; } @@ -198,7 +157,7 @@ public static Control CreateModuleControl(ModuleInfo moduleConfiguration) case ".mvc": var segments = moduleConfiguration.ModuleControl.ControlSrc.Replace(".mvc", string.Empty).Split('/'); - moduleControl.LocalResourceFile = string.Format( + moduleControl.LocalResourceFile = string.Format( "~/DesktopModules/MVC/{0}/{1}/{2}.resx", moduleConfiguration.DesktopModule.FolderName, Localization.LocalResourceDirectory, @@ -210,8 +169,49 @@ public static Control CreateModuleControl(ModuleInfo moduleConfiguration) Path.GetFileName(moduleConfiguration.ModuleControl.ControlSrc); break; } - + return moduleControl; } + + [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; + } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleHost.cs b/DNN Platform/Library/UI/Modules/ModuleHost.cs index 8612a41aaba..6f4ff45b727 100644 --- a/DNN Platform/Library/UI/Modules/ModuleHost.cs +++ b/DNN Platform/Library/UI/Modules/ModuleHost.cs @@ -53,10 +53,11 @@ public sealed class ModuleHost : Panel private static readonly Regex CdfMatchRegex = new Regex( @"<\!--CDF\((?JAVASCRIPT|CSS|JS-LIBRARY)\|(?.+?)(\|(?.+?)\|(?\d+?))?\)-->", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private readonly ModuleInfo _moduleConfiguration; + private readonly IModuleControlPipeline _moduleControlPipeline = Globals.DependencyProvider.GetRequiredService(); private Control _control; private bool _isCached; - private readonly IModuleControlPipeline _moduleControlPipeline = Globals.DependencyProvider.GetRequiredService(); /// ----------------------------------------------------------------------------- /// @@ -73,8 +74,6 @@ public ModuleHost(ModuleInfo moduleConfiguration, Skins.Skin skin, Containers.Co this.Skin = skin; } - public Containers.Container Container { get; private set; } - /// ----------------------------------------------------------------------------- /// /// Gets the attached ModuleControl. @@ -102,6 +101,8 @@ public PortalSettings PortalSettings } } + public Containers.Container Container { get; private set; } + public Skins.Skin Skin { get; private set; } /// ----------------------------------------------------------------------------- @@ -175,6 +176,50 @@ protected override void OnPreRender(EventArgs e) } } + /// ----------------------------------------------------------------------------- + /// + /// RenderContents renders the contents of the control to the output stream. + /// + protected override void RenderContents(HtmlTextWriter writer) + { + if (this._isCached) + { + // Render the cached control to the output stream + base.RenderContents(writer); + } + else + { + if (this.SupportsCaching() && IsViewMode(this._moduleConfiguration, this.PortalSettings) && !Globals.IsAdminControl() && !this.IsVersionRequest()) + { + // Render to cache + var tempWriter = new StringWriter(); + + this._control.RenderControl(new HtmlTextWriter(tempWriter)); + string cachedOutput = tempWriter.ToString(); + + if (!string.IsNullOrEmpty(cachedOutput) && (!HttpContext.Current.Request.Browser.Crawler)) + { + // Save content to cache + var moduleContent = Encoding.UTF8.GetBytes(cachedOutput); + var cache = ModuleCachingProvider.Instance(this._moduleConfiguration.GetEffectiveCacheMethod()); + + var varyBy = new SortedDictionary { { "locale", Thread.CurrentThread.CurrentUICulture.ToString() } }; + + var cacheKey = cache.GenerateCacheKey(this._moduleConfiguration.TabModuleID, varyBy); + cache.SetModule(this._moduleConfiguration.TabModuleID, cacheKey, new TimeSpan(0, 0, this._moduleConfiguration.CacheTime), moduleContent); + } + + // Render the cached content to Response + writer.Write(cachedOutput); + } + else + { + // Render the control to Response + base.RenderContents(writer); + } + } + } + private static void InjectMessageControl(Control container) { // inject a message placeholder for common module messaging - UI.Skins.Skin.AddModuleMessage @@ -527,49 +572,5 @@ private void RestoreCachedClientResourceRegistrations(string cachedContent) } } } - - /// ----------------------------------------------------------------------------- - /// - /// RenderContents renders the contents of the control to the output stream. - /// - protected override void RenderContents(HtmlTextWriter writer) - { - if (this._isCached) - { - // Render the cached control to the output stream - base.RenderContents(writer); - } - else - { - if (this.SupportsCaching() && IsViewMode(this._moduleConfiguration, this.PortalSettings) && !Globals.IsAdminControl() && !this.IsVersionRequest()) - { - // Render to cache - var tempWriter = new StringWriter(); - - this._control.RenderControl(new HtmlTextWriter(tempWriter)); - string cachedOutput = tempWriter.ToString(); - - if (!string.IsNullOrEmpty(cachedOutput) && (!HttpContext.Current.Request.Browser.Crawler)) - { - // Save content to cache - var moduleContent = Encoding.UTF8.GetBytes(cachedOutput); - var cache = ModuleCachingProvider.Instance(this._moduleConfiguration.GetEffectiveCacheMethod()); - - var varyBy = new SortedDictionary { { "locale", Thread.CurrentThread.CurrentUICulture.ToString() } }; - - var cacheKey = cache.GenerateCacheKey(this._moduleConfiguration.TabModuleID, varyBy); - cache.SetModule(this._moduleConfiguration.TabModuleID, cacheKey, new TimeSpan(0, 0, this._moduleConfiguration.CacheTime), moduleContent); - } - - // Render the cached content to Response - writer.Write(cachedOutput); - } - else - { - // Render the control to Response - base.RenderContents(writer); - } - } - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs index be2a6f48656..d9a72aba2f3 100644 --- a/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs +++ b/DNN Platform/Library/UI/Modules/ModuleInstanceContext.cs @@ -47,47 +47,6 @@ public ModuleInstanceContext(IModuleControl moduleControl) this._moduleControl = moduleControl; } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Actions for this module context. - /// - /// ----------------------------------------------------------------------------- - public ModuleActionCollection Actions - { - get - { - if (this._actions == null) - { - this.LoadActions(HttpContext.Current.Request); - } - - return this._actions; - } - - set - { - this._actions = value; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the Module Configuration (ModuleInfo) for this context. - /// - /// ----------------------------------------------------------------------------- - public ModuleInfo Configuration - { - get - { - return this._configuration; - } - - set - { - this._configuration = value; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether the EditMode property is used to determine whether the user is in the @@ -102,13 +61,6 @@ public bool EditMode } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the HelpUrl for this context. - /// - /// ----------------------------------------------------------------------------- - public string HelpURL { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the module is Editable (in Admin mode). @@ -156,32 +108,6 @@ public bool IsHostMenu } } - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets and sets the module ID for this context. - /// - /// ----------------------------------------------------------------------------- - public int ModuleId - { - get - { - if (this._configuration != null) - { - return this._configuration.ModuleID; - } - - return Null.NullInteger; - } - - set - { - if (this._configuration != null) - { - this._configuration.ModuleID = value; - } - } - } - public PortalAliasInfo PortalAlias { get @@ -249,6 +175,80 @@ public int TabId } } + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Actions for this module context. + /// + /// ----------------------------------------------------------------------------- + public ModuleActionCollection Actions + { + get + { + if (this._actions == null) + { + this.LoadActions(HttpContext.Current.Request); + } + + return this._actions; + } + + set + { + this._actions = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the Module Configuration (ModuleInfo) for this context. + /// + /// ----------------------------------------------------------------------------- + public ModuleInfo Configuration + { + get + { + return this._configuration; + } + + set + { + this._configuration = value; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the HelpUrl for this context. + /// + /// ----------------------------------------------------------------------------- + public string HelpURL { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the module ID for this context. + /// + /// ----------------------------------------------------------------------------- + public int ModuleId + { + get + { + if (this._configuration != null) + { + return this._configuration.ModuleID; + } + + return Null.NullInteger; + } + + set + { + if (this._configuration != null) + { + this._configuration.ModuleID = value; + } + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the tabnmodule ID for this context. @@ -285,6 +285,79 @@ 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"); + } + + public string EditUrl(string keyName, string keyValue, string controlKey) + { + var parameters = new string[] { }; + return this.EditUrl(keyName, keyValue, controlKey, parameters); + } + + public string EditUrl(string keyName, string keyValue, string controlKey, params string[] additionalParameters) + { + string key = controlKey; + if (string.IsNullOrEmpty(key)) + { + key = "Edit"; + } + + string moduleIdParam = string.Empty; + if (this.Configuration != null) + { + moduleIdParam = string.Format("mid={0}", this.Configuration.ModuleID); + } + + string[] parameters; + if (!string.IsNullOrEmpty(keyName) && !string.IsNullOrEmpty(keyValue)) + { + parameters = new string[2 + additionalParameters.Length]; + parameters[0] = moduleIdParam; + parameters[1] = string.Format("{0}={1}", keyName, keyValue); + Array.Copy(additionalParameters, 0, parameters, 2, additionalParameters.Length); + } + else + { + parameters = new string[1 + additionalParameters.Length]; + parameters[0] = moduleIdParam; + Array.Copy(additionalParameters, 0, parameters, 1, additionalParameters.Length); + } + + return this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, key, false, parameters); + } + + public string NavigateUrl(int tabID, string controlKey, bool pageRedirect, params string[] additionalParameters) + { + return this.NavigateUrl(tabID, controlKey, Globals.glbDefaultPage, pageRedirect, additionalParameters); + } + + public string NavigateUrl(int tabID, string controlKey, string pageName, bool pageRedirect, params string[] additionalParameters) + { + var isSuperTab = TestableGlobals.Instance.IsHostTab(tabID); + var settings = PortalController.Instance.GetCurrentPortalSettings(); + var language = Globals.GetCultureCode(tabID, isSuperTab, settings); + var url = TestableGlobals.Instance.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); + + // Making URLs call popups + if (this.PortalSettings != null && this.PortalSettings.EnablePopUps) + { + if (!UIUtilities.IsLegacyUI(this.ModuleId, controlKey, this.PortalId) && url.Contains("ctl")) + { + url = UrlUtils.PopUpUrl(url, null, this.PortalSettings, false, pageRedirect); + } + } + + return url; + } + + public int GetNextActionID() + { + this._nextActionId += 1; + return this._nextActionId; + } + private static string FilterUrl(HttpRequest request) { return request.RawUrl.Replace("\"", string.Empty); @@ -748,78 +821,5 @@ private bool SupportShowInPopup(string url) return (isSecureConnection && url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) || (!isSecureConnection && url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)); } - - public string EditUrl(string keyName, string keyValue) - { - return this.EditUrl(keyName, keyValue, "Edit"); - } - - public string EditUrl(string keyName, string keyValue, string controlKey) - { - var parameters = new string[] { }; - return this.EditUrl(keyName, keyValue, controlKey, parameters); - } - - public string EditUrl(string keyName, string keyValue, string controlKey, params string[] additionalParameters) - { - string key = controlKey; - if (string.IsNullOrEmpty(key)) - { - key = "Edit"; - } - - string moduleIdParam = string.Empty; - if (this.Configuration != null) - { - moduleIdParam = string.Format("mid={0}", this.Configuration.ModuleID); - } - - string[] parameters; - if (!string.IsNullOrEmpty(keyName) && !string.IsNullOrEmpty(keyValue)) - { - parameters = new string[2 + additionalParameters.Length]; - parameters[0] = moduleIdParam; - parameters[1] = string.Format("{0}={1}", keyName, keyValue); - Array.Copy(additionalParameters, 0, parameters, 2, additionalParameters.Length); - } - else - { - parameters = new string[1 + additionalParameters.Length]; - parameters[0] = moduleIdParam; - Array.Copy(additionalParameters, 0, parameters, 1, additionalParameters.Length); - } - - return this.NavigateUrl(this.PortalSettings.ActiveTab.TabID, key, false, parameters); - } - - public string NavigateUrl(int tabID, string controlKey, bool pageRedirect, params string[] additionalParameters) - { - return this.NavigateUrl(tabID, controlKey, Globals.glbDefaultPage, pageRedirect, additionalParameters); - } - - public string NavigateUrl(int tabID, string controlKey, string pageName, bool pageRedirect, params string[] additionalParameters) - { - var isSuperTab = TestableGlobals.Instance.IsHostTab(tabID); - var settings = PortalController.Instance.GetCurrentPortalSettings(); - var language = Globals.GetCultureCode(tabID, isSuperTab, settings); - var url = TestableGlobals.Instance.NavigateURL(tabID, isSuperTab, settings, controlKey, language, pageName, additionalParameters); - - // Making URLs call popups - if (this.PortalSettings != null && this.PortalSettings.EnablePopUps) - { - if (!UIUtilities.IsLegacyUI(this.ModuleId, controlKey, this.PortalId) && url.Contains("ctl")) - { - url = UrlUtils.PopUpUrl(url, null, this.PortalSettings, false, pageRedirect); - } - } - - return url; - } - - public int GetNextActionID() - { - this._nextActionId += 1; - return this._nextActionId; - } } } diff --git a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs index 6bb4821d45d..79cf9c2d1d1 100644 --- a/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ModuleUserControlBase.cs @@ -23,7 +23,7 @@ public class ModuleUserControlBase : UserControl, IModuleControl { private string _localResourceFile; private ModuleInstanceContext _moduleContext; - + /// ----------------------------------------------------------------------------- /// /// Gets the underlying base control for this ModuleControl. @@ -66,15 +66,24 @@ public string ControlName } } - protected string LocalizeString(string key) + /// ----------------------------------------------------------------------------- + /// + /// Gets the Module Context for this control. + /// + /// A ModuleInstanceContext. + /// ----------------------------------------------------------------------------- + public ModuleInstanceContext ModuleContext { - return Localization.GetString(key, this.LocalResourceFile); - } + get + { + if (this._moduleContext == null) + { + this._moduleContext = new ModuleInstanceContext(this); + } - protected string LocalizeSafeJsString(string key) - { - return Localization.GetSafeJSString(key, this.LocalResourceFile); - } + return this._moduleContext; + } + } /// ----------------------------------------------------------------------------- /// @@ -95,33 +104,24 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets the Module Context for this control. - /// - /// A ModuleInstanceContext. - /// ----------------------------------------------------------------------------- - public ModuleInstanceContext ModuleContext + protected string LocalizeString(string key) { - get - { - if (this._moduleContext == null) - { - this._moduleContext = new ModuleInstanceContext(this); - } - - return this._moduleContext; - } - } + return Localization.GetString(key, this.LocalResourceFile); + } + + protected string LocalizeSafeJsString(string key) + { + return Localization.GetSafeJSString(key, this.LocalResourceFile); + } } } diff --git a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs index 572f4ae279f..c58eb32a306 100644 --- a/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs +++ b/DNN Platform/Library/UI/Modules/ProfileModuleUserControlBase.cs @@ -20,8 +20,8 @@ public abstract class ProfileModuleUserControlBase : ModuleUserControlBase, IPro public ProfileModuleUserControlBase() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - + } + public abstract bool DisplayModule { get; } public int ProfileUserId @@ -35,10 +35,10 @@ public int ProfileUserId return UserController.Instance.GetCurrentUserInfo().UserID; } - } - + } + protected INavigationManager NavigationManager { get; } - + protected bool IsUser { get { return this.ProfileUserId == this.ModuleContext.PortalSettings.UserId; } @@ -47,8 +47,8 @@ protected bool IsUser protected UserInfo ProfileUser { get { return UserController.GetUserById(this.ModuleContext.PortalId, this.ProfileUserId); } - } - + } + protected override void OnInit(EventArgs e) { if (string.IsNullOrEmpty(this.Request.Params["UserId"]) && @@ -58,7 +58,7 @@ protected override void OnInit(EventArgs e) try { // Clicked on breadcrumb - don't know which user - this.Response.Redirect( + 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); @@ -70,8 +70,8 @@ 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. @@ -89,6 +89,6 @@ private string GetRedirectUrl() } return redirectUrl; - } + } } } diff --git a/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs b/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs index ac946737dfa..0ef6523752e 100644 --- a/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs +++ b/DNN Platform/Library/UI/Modules/StandardModuleInjectionFilter.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.UI.Modules using DotNetNuke.Security.Permissions; public class StandardModuleInjectionFilter : IModuleInjectionFilter - { + { public bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) { return ModulePermissionController.CanViewModule(module) @@ -19,6 +19,6 @@ public bool CanInjectModule(ModuleInfo module, PortalSettings portalSettings) && ((module.StartDate < DateTime.Now && module.EndDate > DateTime.Now) || Globals.IsLayoutMode() || Globals.IsEditMode()); - } + } } } diff --git a/DNN Platform/Library/UI/Navigation.cs b/DNN Platform/Library/UI/Navigation.cs index f6f4ee449c8..d87989a1ab5 100644 --- a/DNN Platform/Library/UI/Navigation.cs +++ b/DNN Platform/Library/UI/Navigation.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.UI using DotNetNuke.UI.WebControls; public class Navigation - { + { public enum NavNodeOptions { IncludeSelf = 1, @@ -28,16 +28,16 @@ public enum NavNodeOptions IncludeSiblings = 4, MarkPendingNodes = 8, IncludeHiddenNodes = 16, - } - + } + public enum ToolTipSource { TabName, Title, Description, None, - } - + } + public static bool CanShowTab(TabInfo objTab, bool isAdminMode, bool showDisabled) { return CanShowTab(objTab, isAdminMode, showDisabled, false); @@ -52,7 +52,227 @@ public static bool CanShowTab(TabInfo tab, bool isAdminMode, bool showDisabled, (tab.EndDate > DateTime.Now || tab.EndDate == Null.NullDate)) || isAdminMode) && TabPermissionController.CanNavigateToPage(tab); } - + + /// ----------------------------------------------------------------------------- + /// + /// Allows for DNNNode object to be easily obtained based off of passed in ID. + /// + /// NodeID to retrieve. + /// Namespace for node collection (usually control's ClientID). + /// Root Action object used in searching. + /// ActionControl to base actions off of. + /// DNNNode. + /// + /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. + /// + /// ----------------------------------------------------------------------------- + public static DNNNode GetActionNode(string strID, string strNamespace, ModuleAction objActionRoot, Control objControl) + { + DNNNodeCollection objNodes = GetActionNodes(objActionRoot, objControl, -1); + DNNNode objNode = objNodes.FindNode(strID); + var objReturnNodes = new DNNNodeCollection(strNamespace); + objReturnNodes.Import(objNode); + objReturnNodes[0].ID = strID; + return objReturnNodes[0]; + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the actions associated + /// to a module based off of the current user's context. + /// + /// Root module action. + /// ActionControl to base actions off of. + /// + /// + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Control objControl) + { + return GetActionNodes(objActionRoot, objControl, -1); + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the actions associated + /// to a module based off of the current user's context. + /// + /// Root module action. + /// ActionControl to base actions off of. + /// How many levels deep should be populated. + /// + /// + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Control objControl, int intDepth) + { + var objCol = new DNNNodeCollection(objControl.ClientID); + + var objActionControl = objControl as IActionControl; + if (objActionControl != null) + { + if (objActionRoot.Visible) + { + objCol.Add(); + DNNNode objRoot = objCol[0]; + objRoot.ID = objActionRoot.ID.ToString(); + objRoot.Key = objActionRoot.ID.ToString(); + objRoot.Text = objActionRoot.Title; + objRoot.NavigateURL = objActionRoot.Url; + objRoot.Image = objActionRoot.Icon; + objRoot.Enabled = false; + AddChildActions(objActionRoot, objRoot, objRoot.ParentNode, objActionControl, intDepth); + } + } + + return objCol; + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the actions associated + /// to a module based off of the current user's context. + /// + /// Root module action. + /// Root node on which to populate children. + /// ActionControl to base actions off of. + /// How many levels deep should be populated. + /// + /// + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, DNNNode objRootNode, Control objControl, int intDepth) + { + DNNNodeCollection objCol = objRootNode.ParentNode.DNNNodes; + var objActionControl = objControl as IActionControl; + if (objActionControl != null) + { + AddChildActions(objActionRoot, objRootNode, objRootNode, objActionControl, intDepth); + } + + return objCol; + } + + /// ----------------------------------------------------------------------------- + /// + /// Allows for DNNNode object to be easily obtained based off of passed in ID. + /// + /// NodeID to retrieve. + /// Namespace for node collection (usually control's ClientID). + /// DNNNode. + /// + /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. + /// + /// ----------------------------------------------------------------------------- + public static DNNNode GetNavigationNode(string strID, string strNamespace) + { + DNNNodeCollection objNodes = GetNavigationNodes(strNamespace); + DNNNode objNode = objNodes.FindNode(strID); + var objReturnNodes = new DNNNodeCollection(strNamespace); + objReturnNodes.Import(objNode); + objReturnNodes[0].ID = strID; + return objReturnNodes[0]; + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the pages/tabs included in + /// the current context's (user) navigation hierarchy. + /// + /// Namespace (typically control's ClientID) of node collection to create. + /// Collection of DNNNodes. + /// + /// Returns all navigation nodes for a given user. + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetNavigationNodes(string strNamespace) + { + return GetNavigationNodes(strNamespace, ToolTipSource.None, -1, -1, 0); + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the pages/tabs included in + /// the current context's (user) navigation hierarchy. + /// + /// Namespace (typically control's ClientID) of node collection to create. + /// Enumerator to determine what text to display in the tooltips. + /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). + /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). + /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). + /// Collection of DNNNodes. + /// + /// Returns a subset of navigation nodes based off of passed in starting node id and depth. + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetNavigationNodes(string strNamespace, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) + { + var objCol = new DNNNodeCollection(strNamespace); + return GetNavigationNodes(new DNNNode(objCol.XMLNode), eToolTips, intStartTabId, intDepth, intNavNodeOptions); + } + + /// ----------------------------------------------------------------------------- + /// + /// This function provides a central location to obtain a generic node collection of the pages/tabs included in + /// the current context's (user) navigation hierarchy. + /// + /// Node in which to add children to. + /// Enumerator to determine what text to display in the tooltips. + /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). + /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). + /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). + /// Collection of DNNNodes. + /// + /// Returns a subset of navigation nodes based off of passed in starting node id and depth. + /// + /// ----------------------------------------------------------------------------- + public static DNNNodeCollection GetNavigationNodes(DNNNode objRootNode, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) + { + var objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var objBreadCrumbs = new Hashtable(); + var objTabLookup = new Hashtable(); + var objRootNodes = objRootNode.DNNNodes; + var intLastBreadCrumbId = 0; + + //--- cache breadcrumbs in hashtable so we can easily set flag on node denoting it as a breadcrumb node (without looping multiple times) --- + foreach (TabInfo tabInfo in objPortalSettings.ActiveTab.BreadCrumbs) + { + objBreadCrumbs.Add(tabInfo.TabID, 1); + intLastBreadCrumbId = tabInfo.TabID; + } + + var portalTabs = TabController.GetTabsBySortOrder(objPortalSettings.PortalId, objPortalSettings.CultureCode, true); + var hostTabs = TabController.GetTabsBySortOrder(Null.NullInteger, Localization.SystemLocale, true); + + var cachedPortalTabs = new List(portalTabs); + foreach (var objTab in cachedPortalTabs) + { + objTabLookup.Add(objTab.TabID, objTab); + } + + var cachedHostTabs = new List(hostTabs); + foreach (var objTab in cachedHostTabs) + { + objTabLookup.Add(objTab.TabID, objTab); + } + + // convert dnn nodes to dictionary. + var nodesDict = new Dictionary(); + SaveDnnNodesToDictionary(nodesDict, objRootNodes); + + foreach (var objTab in cachedPortalTabs) + { + ProcessTab(objRootNode, objTab, objTabLookup, objBreadCrumbs, intLastBreadCrumbId, eToolTips, intStartTabId, intDepth, intNavNodeOptions, nodesDict); + } + + foreach (var objTab in cachedHostTabs) + { + ProcessTab(objRootNode, objTab, objTabLookup, objBreadCrumbs, intLastBreadCrumbId, eToolTips, intStartTabId, intDepth, intNavNodeOptions, nodesDict); + } + + return objRootNodes; + } + /// ----------------------------------------------------------------------------- /// /// Recursive function to add module's actions to the DNNNodeCollection based off of passed in ModuleActions. @@ -123,7 +343,7 @@ private static void AddChildActions(ModuleAction parentAction, DNNNode parentNod node.ClickAction = eClickAction.PostBack; } } - + node.Image = action.Icon; if (action.HasChildren()) // if action has children then call function recursively { @@ -167,12 +387,12 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl objNode.Selected = true; } } - + if (objTab.DisableLink) { objNode.Enabled = false; } - + objNode.ID = objTab.TabID.ToString(); objNode.Key = objNode.ID; objNode.Text = objTab.LocalizedTabName; @@ -192,7 +412,7 @@ private static void AddNode(TabInfo objTab, DNNNodeCollection objNodes, Hashtabl objNode.ToolTip = objTab.Description; break; } - + bool newWindow = false; if (objTab.TabSettings["LinkNewWindow"] != null && bool.TryParse((string)objTab.TabSettings["LinkNewWindow"], out newWindow) && newWindow) { @@ -221,7 +441,7 @@ private static bool IsActionPending(DNNNode objParentNode, DNNNode objRootNode, { return false; } - + return true; } @@ -269,7 +489,7 @@ private static bool IsTabPending(TabInfo objTab, DNNNode objParentNode, DNNNode { return false; } - + //--- These checks below are here so tree becomes expands to selected node --- if (blnPOD) { @@ -292,7 +512,7 @@ private static bool IsTabPending(TabInfo objTab, DNNNode objParentNode, DNNNode return false; } } - + return true; } @@ -321,7 +541,7 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob { objParentNode = objRootNode; } - + objParentNodes = objParentNode.DNNNodes; if (objTab.TabID == intStartTabId) { @@ -338,7 +558,7 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob } } } - + if ((intNavNodeOptions & (int)NavNodeOptions.IncludeSelf) != 0) { // if we are including our self (starting tab) then add @@ -379,226 +599,6 @@ private static void ProcessTab(DNNNode objRootNode, TabInfo objTab, Hashtable ob } } } - } - - /// ----------------------------------------------------------------------------- - /// - /// Allows for DNNNode object to be easily obtained based off of passed in ID. - /// - /// NodeID to retrieve. - /// Namespace for node collection (usually control's ClientID). - /// Root Action object used in searching. - /// ActionControl to base actions off of. - /// DNNNode. - /// - /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. - /// - /// ----------------------------------------------------------------------------- - public static DNNNode GetActionNode(string strID, string strNamespace, ModuleAction objActionRoot, Control objControl) - { - DNNNodeCollection objNodes = GetActionNodes(objActionRoot, objControl, -1); - DNNNode objNode = objNodes.FindNode(strID); - var objReturnNodes = new DNNNodeCollection(strNamespace); - objReturnNodes.Import(objNode); - objReturnNodes[0].ID = strID; - return objReturnNodes[0]; - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context. - /// - /// Root module action. - /// ActionControl to base actions off of. - /// - /// - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Control objControl) - { - return GetActionNodes(objActionRoot, objControl, -1); - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context. - /// - /// Root module action. - /// ActionControl to base actions off of. - /// How many levels deep should be populated. - /// - /// - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, Control objControl, int intDepth) - { - var objCol = new DNNNodeCollection(objControl.ClientID); - - var objActionControl = objControl as IActionControl; - if (objActionControl != null) - { - if (objActionRoot.Visible) - { - objCol.Add(); - DNNNode objRoot = objCol[0]; - objRoot.ID = objActionRoot.ID.ToString(); - objRoot.Key = objActionRoot.ID.ToString(); - objRoot.Text = objActionRoot.Title; - objRoot.NavigateURL = objActionRoot.Url; - objRoot.Image = objActionRoot.Icon; - objRoot.Enabled = false; - AddChildActions(objActionRoot, objRoot, objRoot.ParentNode, objActionControl, intDepth); - } - } - - return objCol; - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the actions associated - /// to a module based off of the current user's context. - /// - /// Root module action. - /// Root node on which to populate children. - /// ActionControl to base actions off of. - /// How many levels deep should be populated. - /// - /// - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetActionNodes(ModuleAction objActionRoot, DNNNode objRootNode, Control objControl, int intDepth) - { - DNNNodeCollection objCol = objRootNode.ParentNode.DNNNodes; - var objActionControl = objControl as IActionControl; - if (objActionControl != null) - { - AddChildActions(objActionRoot, objRootNode, objRootNode, objActionControl, intDepth); - } - - return objCol; - } - - /// ----------------------------------------------------------------------------- - /// - /// Allows for DNNNode object to be easily obtained based off of passed in ID. - /// - /// NodeID to retrieve. - /// Namespace for node collection (usually control's ClientID). - /// DNNNode. - /// - /// Primary purpose of this is to obtain the DNNNode needed for the events exposed by the NavigationProvider. - /// - /// ----------------------------------------------------------------------------- - public static DNNNode GetNavigationNode(string strID, string strNamespace) - { - DNNNodeCollection objNodes = GetNavigationNodes(strNamespace); - DNNNode objNode = objNodes.FindNode(strID); - var objReturnNodes = new DNNNodeCollection(strNamespace); - objReturnNodes.Import(objNode); - objReturnNodes[0].ID = strID; - return objReturnNodes[0]; - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy. - /// - /// Namespace (typically control's ClientID) of node collection to create. - /// Collection of DNNNodes. - /// - /// Returns all navigation nodes for a given user. - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetNavigationNodes(string strNamespace) - { - return GetNavigationNodes(strNamespace, ToolTipSource.None, -1, -1, 0); - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy. - /// - /// Namespace (typically control's ClientID) of node collection to create. - /// Enumerator to determine what text to display in the tooltips. - /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). - /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). - /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). - /// Collection of DNNNodes. - /// - /// Returns a subset of navigation nodes based off of passed in starting node id and depth. - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetNavigationNodes(string strNamespace, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) - { - var objCol = new DNNNodeCollection(strNamespace); - return GetNavigationNodes(new DNNNode(objCol.XMLNode), eToolTips, intStartTabId, intDepth, intNavNodeOptions); - } - - /// ----------------------------------------------------------------------------- - /// - /// This function provides a central location to obtain a generic node collection of the pages/tabs included in - /// the current context's (user) navigation hierarchy. - /// - /// Node in which to add children to. - /// Enumerator to determine what text to display in the tooltips. - /// If using Populate On Demand, then this is the tab id of the root element to retrieve (-1 for no POD). - /// If Populate On Demand is enabled, then this parameter determines the number of nodes to retrieve beneath the starting tab passed in (intStartTabId) (-1 for no POD). - /// Bitwise integer containing values to determine what nodes to display (self, siblings, parent). - /// Collection of DNNNodes. - /// - /// Returns a subset of navigation nodes based off of passed in starting node id and depth. - /// - /// ----------------------------------------------------------------------------- - public static DNNNodeCollection GetNavigationNodes(DNNNode objRootNode, ToolTipSource eToolTips, int intStartTabId, int intDepth, int intNavNodeOptions) - { - var objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var objBreadCrumbs = new Hashtable(); - var objTabLookup = new Hashtable(); - var objRootNodes = objRootNode.DNNNodes; - var intLastBreadCrumbId = 0; - - //--- cache breadcrumbs in hashtable so we can easily set flag on node denoting it as a breadcrumb node (without looping multiple times) --- - foreach (TabInfo tabInfo in objPortalSettings.ActiveTab.BreadCrumbs) - { - objBreadCrumbs.Add(tabInfo.TabID, 1); - intLastBreadCrumbId = tabInfo.TabID; - } - - var portalTabs = TabController.GetTabsBySortOrder(objPortalSettings.PortalId, objPortalSettings.CultureCode, true); - var hostTabs = TabController.GetTabsBySortOrder(Null.NullInteger, Localization.SystemLocale, true); - - var cachedPortalTabs = new List(portalTabs); - foreach (var objTab in cachedPortalTabs) - { - objTabLookup.Add(objTab.TabID, objTab); - } - - var cachedHostTabs = new List(hostTabs); - foreach (var objTab in cachedHostTabs) - { - objTabLookup.Add(objTab.TabID, objTab); - } - - // convert dnn nodes to dictionary. - var nodesDict = new Dictionary(); - SaveDnnNodesToDictionary(nodesDict, objRootNodes); - - foreach (var objTab in cachedPortalTabs) - { - ProcessTab(objRootNode, objTab, objTabLookup, objBreadCrumbs, intLastBreadCrumbId, eToolTips, intStartTabId, intDepth, intNavNodeOptions, nodesDict); - } - - foreach (var objTab in cachedHostTabs) - { - ProcessTab(objRootNode, objTab, objTabLookup, objBreadCrumbs, intLastBreadCrumbId, eToolTips, intStartTabId, intDepth, intNavNodeOptions, nodesDict); - } - - return objRootNodes; } private static void SaveDnnNodesToDictionary(IDictionary nodesDict, DNNNodeCollection nodes) @@ -615,6 +615,6 @@ private static void SaveDnnNodesToDictionary(IDictionary nodesD SaveDnnNodesToDictionary(nodesDict, node.DNNNodes); } } - } + } } } diff --git a/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs b/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs index 81262dac75d..34869d98d53 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ControlPanel.cs @@ -30,10 +30,10 @@ protected override void OnInit(EventArgs e) if (objControlPanel.IncludeInControlHierarchy) { objControlPanel.IsDockable = this.IsDockable; - if (!Host.ControlPanel.EndsWith("controlbar.ascx", StringComparison.InvariantCultureIgnoreCase)) - { - this.Controls.Add(objControlPanel); - } + if (!Host.ControlPanel.EndsWith("controlbar.ascx", StringComparison.InvariantCultureIgnoreCase)) + { + this.Controls.Add(objControlPanel); + } else { if (objForm != null) diff --git a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs index d2087f7a31d..9af56da6a8e 100644 --- a/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs +++ b/DNN Platform/Library/UI/Skins/Controls/LanguageTokenReplace.cs @@ -36,9 +36,9 @@ public LanguageTokenReplace() public class LanguagePropertyAccess : IPropertyAccess { - public LanguageTokenReplace objParent; private const string FlagIconPhysicalLocation = @"~\images\Flags"; private const string NonExistingFlagIconFileName = "none.gif"; + public LanguageTokenReplace objParent; private readonly PortalSettings objPortal; public LanguagePropertyAccess(LanguageTokenReplace parent, PortalSettings settings) diff --git a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs index 763d6372de9..6503bdbf5a0 100644 --- a/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs +++ b/DNN Platform/Library/UI/Skins/Controls/ModuleMessage.cs @@ -14,27 +14,19 @@ namespace DotNetNuke.UI.Skins.Controls /// /// public class ModuleMessage : SkinObjectBase - { + { protected Panel dnnSkinMessage; protected Label lblHeading; protected Label lblMessage; - + protected Control scrollScript; + public enum ModuleMessageType { GreenSuccess, YellowWarning, RedError, BlueInfo, - } - protected Control scrollScript; - - public string Text { get; set; } - - public string Heading { get; set; } - - public ModuleMessageType IconType { get; set; } - - public string IconImage { get; set; } + } /// /// Gets a value indicating whether check this message is shown as page message or module message. @@ -45,8 +37,16 @@ public bool IsModuleMessage { return this.Parent.ID == "MessagePlaceHolder"; } - } - + } + + public string Text { get; set; } + + public string Heading { get; set; } + + public ModuleMessageType IconType { get; set; } + + public string IconImage { get; set; } + /// /// The Page_Load server event handler on this page is used /// to populate the role information for the page. @@ -88,7 +88,7 @@ protected override void OnLoad(EventArgs e) break; } } - + this.lblMessage.Text = strMessage; if (!string.IsNullOrEmpty(this.Heading)) @@ -109,6 +109,6 @@ protected override void OnPreRender(EventArgs e) // set the scroll js only shown for module message and in postback mode. this.scrollScript.Visible = this.IsPostBack && this.IsModuleMessage; - } + } } } diff --git a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs index 7d654302961..7efcf84ff7f 100644 --- a/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs +++ b/DNN Platform/Library/UI/Skins/Controls/SkinsEditControl.cs @@ -29,20 +29,20 @@ namespace DotNetNuke.UI.Skins.Controls [ToolboxData("<{0}:SkinsEditControl runat=server>")] public class SkinsEditControl : EditControl, IPostBackEventHandler { - private string _AddedItem = Null.NullString; - + private string _AddedItem = Null.NullString; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a SkinsEditControl. /// /// ----------------------------------------------------------------------------- public SkinsEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a SkinsEditControl. /// @@ -51,8 +51,31 @@ public SkinsEditControl() public SkinsEditControl(string type) { this.SystemType = type; - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets oldStringValue returns the String representation of the OldValue. + /// + /// A String representing the OldValue. + /// ----------------------------------------------------------------------------- + protected string OldStringValue + { + get + { + string strValue = Null.NullString; + if (this.OldDictionaryValue != null) + { + foreach (string Skin in this.OldDictionaryValue.Values) + { + strValue += Skin + ","; + } + } + + return strValue; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets dictionaryValue returns the Dictionary(Of Integer, String) representation of the Value. @@ -65,7 +88,7 @@ protected Dictionary DictionaryValue { return this.Value as Dictionary; } - + set { this.Value = value; @@ -84,36 +107,13 @@ protected Dictionary OldDictionaryValue { return this.OldValue as Dictionary; } - + set { this.OldValue = value; } } - /// ----------------------------------------------------------------------------- - /// - /// Gets oldStringValue returns the String representation of the OldValue. - /// - /// A String representing the OldValue. - /// ----------------------------------------------------------------------------- - protected string OldStringValue - { - get - { - string strValue = Null.NullString; - if (this.OldDictionaryValue != null) - { - foreach (string Skin in this.OldDictionaryValue.Values) - { - strValue += Skin + ","; - } - } - - return strValue; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets stringValue is the value of the control expressed as a String. @@ -132,10 +132,10 @@ protected override string StringValue strValue += Skin + ","; } } - + return strValue; } - + set { this.Value = value; @@ -148,13 +148,13 @@ protected string AddedItem { return this._AddedItem; } - + set { this._AddedItem = value; } - } - + } + public void RaisePostBackEvent(string eventArgument) { PropertyEditorEventArgs args; @@ -176,8 +176,8 @@ public void RaisePostBackEvent(string eventArgument) this.OnItemAdded(args); break; } - } - + } + public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { bool dataChanged = false; @@ -196,17 +196,17 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo 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 @@ -257,7 +257,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) } } } - + if (this.DictionaryValue != null) { foreach (KeyValuePair kvp in this.DictionaryValue) @@ -286,14 +286,14 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skin" + kvp.Key); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); writer.WriteBreak(); } - + writer.WriteBreak(); // Create Add Row @@ -320,7 +320,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + "_skinnew"); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); @@ -347,6 +347,6 @@ protected override void RenderViewMode(HtmlTextWriter writer) writer.WriteBreak(); } } - } + } } } diff --git a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs index 4e4f10cc2c8..fa233b89833 100644 --- a/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs +++ b/DNN Platform/Library/UI/Skins/EventListeners/SkinEventListener.cs @@ -13,7 +13,7 @@ public SkinEventListener(SkinEventType type, SkinEventHandler e) } public SkinEventType EventType { get; private set; } - + public SkinEventHandler SkinEvent { get; private set; } } } diff --git a/DNN Platform/Library/UI/Skins/NavObjectBase.cs b/DNN Platform/Library/UI/Skins/NavObjectBase.cs index 1572bd43272..767fc7ef1f1 100644 --- a/DNN Platform/Library/UI/Skins/NavObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/NavObjectBase.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.UI.Skins using DotNetNuke.UI.WebControls; public class NavObjectBase : SkinObjectBase - { + { private readonly List m_objCustomAttributes = new List(); private bool m_blnPopulateNodesFromClient = true; private int m_intExpandDepth = -1; @@ -96,10 +96,10 @@ public class NavObjectBase : SkinObjectBase private string m_strStyleSelectionColor; private string m_strStyleSelectionForeColor; private string m_strToolTip = string.Empty; - private string m_strWorkImage; - - // JH - 2/5/07 - support for custom attributes - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + private string m_strWorkImage; + + // JH - 2/5/07 - support for custom attributes + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [PersistenceMode(PersistenceMode.InnerProperty)] public List CustomAttributes { @@ -117,7 +117,7 @@ public string ProviderName { return this.m_strProviderName; } - + set { this.m_strProviderName = value; @@ -130,7 +130,7 @@ public string Level { return this.m_strLevel; } - + set { this.m_strLevel = value; @@ -143,28 +143,20 @@ public string ToolTip { return this.m_strToolTip; } - + set { this.m_strToolTip = value; } } - protected NavigationProvider Control - { - get - { - return this.m_objControl; - } - } - public bool PopulateNodesFromClient { get { return this.m_blnPopulateNodesFromClient; } - + set { this.m_blnPopulateNodesFromClient = value; @@ -177,7 +169,7 @@ public int ExpandDepth { return this.m_intExpandDepth; } - + set { this.m_intExpandDepth = value; @@ -190,7 +182,7 @@ public int StartTabId { return this.m_intStartTabId; } - + set { this.m_intStartTabId = value; @@ -210,7 +202,7 @@ public string PathSystemImage return this.Control.PathSystemImage; } } - + set { value = this.GetPath(value); @@ -238,7 +230,7 @@ public string PathImage return this.Control.PathImage; } } - + set { value = this.GetPath(value); @@ -266,7 +258,7 @@ public string WorkImage return this.Control.WorkImage; } } - + set { if (this.Control == null) @@ -293,7 +285,7 @@ public string PathSystemScript return this.Control.PathSystemScript; } } - + set { if (this.Control == null) @@ -328,10 +320,10 @@ public string ControlOrientation break; } } - + return retValue; } - + set { if (this.Control == null) @@ -380,10 +372,10 @@ public string ControlAlignment break; } } - + return retValue; } - + set { if (this.Control == null) @@ -424,7 +416,7 @@ public string ForceCrawlerDisplay return this.Control.ForceCrawlerDisplay; } } - + set { if (this.Control == null) @@ -451,7 +443,7 @@ public string ForceDownLevel return this.Control.ForceDownLevel; } } - + set { if (this.Control == null) @@ -478,7 +470,7 @@ public string MouseOutHideDelay return this.Control.MouseOutHideDelay.ToString(); } } - + set { if (this.Control == null) @@ -516,10 +508,10 @@ public string MouseOverDisplay break; } } - + return retValue; } - + set { if (this.Control == null) @@ -565,10 +557,10 @@ public string MouseOverAction break; } } - + return retValue; } - + set { if (this.Control == null) @@ -602,7 +594,7 @@ public string IndicateChildren return this.Control.IndicateChildren.ToString(); } } - + set { if (this.Control == null) @@ -629,7 +621,7 @@ public string IndicateChildImageRoot return this.Control.IndicateChildImageRoot; } } - + set { value = this.GetPath(value); @@ -657,7 +649,7 @@ public string IndicateChildImageSub return this.Control.IndicateChildImageSub; } } - + set { value = this.GetPath(value); @@ -685,7 +677,7 @@ public string IndicateChildImageExpandedRoot return this.Control.IndicateChildImageExpandedRoot; } } - + set { value = this.GetPath(value); @@ -713,7 +705,7 @@ public string IndicateChildImageExpandedSub return this.Control.IndicateChildImageExpandedSub; } } - + set { value = this.GetPath(value); @@ -741,7 +733,7 @@ public string NodeLeftHTMLRoot return this.Control.NodeLeftHTMLRoot; } } - + set { value = this.GetPath(value); @@ -769,7 +761,7 @@ public string NodeRightHTMLRoot return this.Control.NodeRightHTMLRoot; } } - + set { value = this.GetPath(value); @@ -797,7 +789,7 @@ public string NodeLeftHTMLSub return this.Control.NodeLeftHTMLSub; } } - + set { value = this.GetPath(value); @@ -825,7 +817,7 @@ public string NodeRightHTMLSub return this.Control.NodeRightHTMLSub; } } - + set { value = this.GetPath(value); @@ -853,7 +845,7 @@ public string NodeLeftHTMLBreadCrumbRoot return this.Control.NodeLeftHTMLBreadCrumbRoot; } } - + set { value = this.GetPath(value); @@ -881,7 +873,7 @@ public string NodeLeftHTMLBreadCrumbSub return this.Control.NodeLeftHTMLBreadCrumbSub; } } - + set { value = this.GetPath(value); @@ -909,7 +901,7 @@ public string NodeRightHTMLBreadCrumbRoot return this.Control.NodeRightHTMLBreadCrumbRoot; } } - + set { value = this.GetPath(value); @@ -937,7 +929,7 @@ public string NodeRightHTMLBreadCrumbSub return this.Control.NodeRightHTMLBreadCrumbSub; } } - + set { value = this.GetPath(value); @@ -965,7 +957,7 @@ public string SeparatorHTML return this.Control.SeparatorHTML; } } - + set { value = this.GetPath(value); @@ -993,7 +985,7 @@ public string SeparatorLeftHTML return this.Control.SeparatorLeftHTML; } } - + set { value = this.GetPath(value); @@ -1021,7 +1013,7 @@ public string SeparatorRightHTML return this.Control.SeparatorRightHTML; } } - + set { value = this.GetPath(value); @@ -1049,7 +1041,7 @@ public string SeparatorLeftHTMLActive return this.Control.SeparatorLeftHTMLActive; } } - + set { value = this.GetPath(value); @@ -1077,7 +1069,7 @@ public string SeparatorRightHTMLActive return this.Control.SeparatorRightHTMLActive; } } - + set { value = this.GetPath(value); @@ -1105,7 +1097,7 @@ public string SeparatorLeftHTMLBreadCrumb return this.Control.SeparatorLeftHTMLBreadCrumb; } } - + set { value = this.GetPath(value); @@ -1133,7 +1125,7 @@ public string SeparatorRightHTMLBreadCrumb return this.Control.SeparatorRightHTMLBreadCrumb; } } - + set { value = this.GetPath(value); @@ -1161,7 +1153,7 @@ public string CSSControl return this.Control.CSSControl; } } - + set { if (this.Control == null) @@ -1188,7 +1180,7 @@ public string CSSContainerRoot return this.Control.CSSContainerRoot; } } - + set { if (this.Control == null) @@ -1215,7 +1207,7 @@ public string CSSNode return this.Control.CSSNode; } } - + set { if (this.Control == null) @@ -1242,7 +1234,7 @@ public string CSSIcon return this.Control.CSSIcon; } } - + set { if (this.Control == null) @@ -1269,7 +1261,7 @@ public string CSSContainerSub return this.Control.CSSContainerSub; } } - + set { if (this.Control == null) @@ -1296,7 +1288,7 @@ public string CSSNodeHover return this.Control.CSSNodeHover; } } - + set { if (this.Control == null) @@ -1323,7 +1315,7 @@ public string CSSBreak return this.Control.CSSBreak; } } - + set { if (this.Control == null) @@ -1350,7 +1342,7 @@ public string CSSIndicateChildSub return this.Control.CSSIndicateChildSub; } } - + set { if (this.Control == null) @@ -1377,7 +1369,7 @@ public string CSSIndicateChildRoot return this.Control.CSSIndicateChildRoot; } } - + set { if (this.Control == null) @@ -1404,7 +1396,7 @@ public string CSSBreadCrumbRoot return this.Control.CSSBreadCrumbRoot; } } - + set { if (this.Control == null) @@ -1431,7 +1423,7 @@ public string CSSBreadCrumbSub return this.Control.CSSBreadCrumbSub; } } - + set { if (this.Control == null) @@ -1458,7 +1450,7 @@ public string CSSNodeRoot return this.Control.CSSNodeRoot; } } - + set { if (this.Control == null) @@ -1485,7 +1477,7 @@ public string CSSNodeSelectedRoot return this.Control.CSSNodeSelectedRoot; } } - + set { if (this.Control == null) @@ -1512,7 +1504,7 @@ public string CSSNodeSelectedSub return this.Control.CSSNodeSelectedSub; } } - + set { if (this.Control == null) @@ -1539,7 +1531,7 @@ public string CSSNodeHoverRoot return this.Control.CSSNodeHoverRoot; } } - + set { if (this.Control == null) @@ -1566,7 +1558,7 @@ public string CSSNodeHoverSub return this.Control.CSSNodeHoverSub; } } - + set { if (this.Control == null) @@ -1593,7 +1585,7 @@ public string CSSSeparator return this.Control.CSSSeparator; } } - + set { if (this.Control == null) @@ -1620,7 +1612,7 @@ public string CSSLeftSeparator return this.Control.CSSLeftSeparator; } } - + set { if (this.Control == null) @@ -1647,7 +1639,7 @@ public string CSSRightSeparator return this.Control.CSSRightSeparator; } } - + set { if (this.Control == null) @@ -1674,7 +1666,7 @@ public string CSSLeftSeparatorSelection return this.Control.CSSLeftSeparatorSelection; } } - + set { if (this.Control == null) @@ -1701,7 +1693,7 @@ public string CSSRightSeparatorSelection return this.Control.CSSRightSeparatorSelection; } } - + set { if (this.Control == null) @@ -1728,7 +1720,7 @@ public string CSSLeftSeparatorBreadCrumb return this.Control.CSSLeftSeparatorBreadCrumb; } } - + set { if (this.Control == null) @@ -1755,7 +1747,7 @@ public string CSSRightSeparatorBreadCrumb return this.Control.CSSRightSeparatorBreadCrumb; } } - + set { if (this.Control == null) @@ -1782,7 +1774,7 @@ public string StyleBackColor return this.Control.StyleBackColor; } } - + set { if (this.Control == null) @@ -1809,7 +1801,7 @@ public string StyleForeColor return this.Control.StyleForeColor; } } - + set { if (this.Control == null) @@ -1836,7 +1828,7 @@ public string StyleHighlightColor return this.Control.StyleHighlightColor; } } - + set { if (this.Control == null) @@ -1863,7 +1855,7 @@ public string StyleIconBackColor return this.Control.StyleIconBackColor; } } - + set { if (this.Control == null) @@ -1890,7 +1882,7 @@ public string StyleSelectionBorderColor return this.Control.StyleSelectionBorderColor; } } - + set { if (this.Control == null) @@ -1917,7 +1909,7 @@ public string StyleSelectionColor return this.Control.StyleSelectionColor; } } - + set { if (this.Control == null) @@ -1944,7 +1936,7 @@ public string StyleSelectionForeColor return this.Control.StyleSelectionForeColor; } } - + set { if (this.Control == null) @@ -1971,7 +1963,7 @@ public string StyleControlHeight return this.Control.StyleControlHeight.ToString(); } } - + set { if (this.Control == null) @@ -1998,7 +1990,7 @@ public string StyleBorderWidth return this.Control.StyleBorderWidth.ToString(); } } - + set { if (this.Control == null) @@ -2025,7 +2017,7 @@ public string StyleNodeHeight return this.Control.StyleNodeHeight.ToString(); } } - + set { if (this.Control == null) @@ -2052,7 +2044,7 @@ public string StyleIconWidth return this.Control.StyleIconWidth.ToString(); } } - + set { if (this.Control == null) @@ -2079,7 +2071,7 @@ public string StyleFontNames return this.Control.StyleFontNames; } } - + set { if (this.Control == null) @@ -2106,7 +2098,7 @@ public string StyleFontSize return this.Control.StyleFontSize.ToString(); } } - + set { if (this.Control == null) @@ -2133,7 +2125,7 @@ public string StyleFontBold return this.Control.StyleFontBold; } } - + set { if (this.Control == null) @@ -2160,7 +2152,7 @@ public string EffectsShadowColor return this.Control.EffectsShadowColor; } } - + set { if (this.Control == null) @@ -2187,7 +2179,7 @@ public string EffectsStyle return this.Control.EffectsStyle; } } - + set { if (this.Control == null) @@ -2214,7 +2206,7 @@ public string EffectsShadowStrength return this.Control.EffectsShadowStrength.ToString(); } } - + set { if (this.Control == null) @@ -2241,7 +2233,7 @@ public string EffectsTransition return this.Control.EffectsTransition; } } - + set { if (this.Control == null) @@ -2268,7 +2260,7 @@ public string EffectsDuration return this.Control.EffectsDuration.ToString(); } } - + set { if (this.Control == null) @@ -2295,7 +2287,7 @@ public string EffectsShadowDirection return this.Control.EffectsShadowDirection; } } - + set { if (this.Control == null) @@ -2307,8 +2299,16 @@ public string EffectsShadowDirection this.Control.EffectsShadowDirection = value; } } - } - + } + + protected NavigationProvider Control + { + get + { + return this.m_objControl; + } + } + public DNNNodeCollection GetNavigationNodes(DNNNode objNode) { int intRootParent = this.PortalSettings.ActiveTab.TabID; @@ -2332,11 +2332,11 @@ public DNNNodeCollection GetNavigationNodes(DNNNode objNode) break; } - if (this.ShowHiddenTabs) - { - intNavNodeOptions += (int)Navigation.NavNodeOptions.IncludeHiddenNodes; - } - + if (this.ShowHiddenTabs) + { + intNavNodeOptions += (int)Navigation.NavNodeOptions.IncludeHiddenNodes; + } + switch (this.ToolTip.ToLowerInvariant()) { case "name": @@ -2352,22 +2352,22 @@ public DNNNodeCollection GetNavigationNodes(DNNNode objNode) eToolTips = Navigation.ToolTipSource.None; break; } - + if (this.PopulateNodesFromClient && this.Control.SupportsPopulateOnDemand) { intNavNodeOptions += (int)Navigation.NavNodeOptions.MarkPendingNodes; } - + if (this.PopulateNodesFromClient && this.Control.SupportsPopulateOnDemand == false) { this.ExpandDepth = -1; } - + if (this.StartTabId != -1) { intRootParent = this.StartTabId; } - + if (objNode != null) { intRootParent = Convert.ToInt32(objNode.ID); @@ -2378,10 +2378,10 @@ public DNNNodeCollection GetNavigationNodes(DNNNode objNode) { objNodes = Navigation.GetNavigationNodes(this.Control.ClientID, eToolTips, intRootParent, intDepth, intNavNodeOptions); } - + return objNodes; - } - + } + protected string GetValue(string strVal, string strDefault) { if (string.IsNullOrEmpty(strVal)) @@ -2400,41 +2400,41 @@ protected void InitializeNavControl(Control objParent, string strDefaultProvider { this.ProviderName = strDefaultProvider; } - + this.m_objControl = NavigationProvider.Instance(this.ProviderName); this.Control.ControlID = "ctl" + this.ID; this.Control.Initialize(); this.AssignControlProperties(); objParent.Controls.Add(this.Control.NavigationControl); - } + } protected void Bind(DNNNodeCollection objNodes) { this.Control.Bind(objNodes); } - + private void AssignControlProperties() { if (!string.IsNullOrEmpty(this.m_strPathSystemImage)) { this.Control.PathSystemImage = this.m_strPathSystemImage; } - + if (!string.IsNullOrEmpty(this.m_strPathImage)) { this.Control.PathImage = this.m_strPathImage; } - + if (!string.IsNullOrEmpty(this.m_strPathSystemScript)) { this.Control.PathSystemScript = this.m_strPathSystemScript; } - + if (!string.IsNullOrEmpty(this.m_strWorkImage)) { this.Control.WorkImage = this.m_strWorkImage; } - + if (!string.IsNullOrEmpty(this.m_strControlOrientation)) { switch (this.m_strControlOrientation.ToLowerInvariant()) @@ -2447,7 +2447,7 @@ private void AssignControlProperties() break; } } - + if (!string.IsNullOrEmpty(this.m_strControlAlignment)) { switch (this.m_strControlAlignment.ToLowerInvariant()) @@ -2466,14 +2466,14 @@ private void AssignControlProperties() break; } } - + this.Control.ForceCrawlerDisplay = this.GetValue(this.m_strForceCrawlerDisplay, "False"); this.Control.ForceDownLevel = this.GetValue(this.m_strForceDownLevel, "False"); if (!string.IsNullOrEmpty(this.m_strMouseOutHideDelay)) { this.Control.MouseOutHideDelay = Convert.ToDecimal(this.m_strMouseOutHideDelay); } - + if (!string.IsNullOrEmpty(this.m_strMouseOverDisplay)) { switch (this.m_strMouseOverDisplay.ToLowerInvariant()) @@ -2489,7 +2489,7 @@ private void AssignControlProperties() break; } } - + if (Convert.ToBoolean(this.GetValue(this.m_strMouseOverAction, "True"))) { this.Control.MouseOverAction = NavigationProvider.HoverAction.Expand; @@ -2498,318 +2498,318 @@ private void AssignControlProperties() { this.Control.MouseOverAction = NavigationProvider.HoverAction.None; } - + this.Control.IndicateChildren = Convert.ToBoolean(this.GetValue(this.m_strIndicateChildren, "True")); if (!string.IsNullOrEmpty(this.m_strIndicateChildImageRoot)) { this.Control.IndicateChildImageRoot = this.m_strIndicateChildImageRoot; } - + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageSub)) { this.Control.IndicateChildImageSub = this.m_strIndicateChildImageSub; } - + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageExpandedRoot)) { this.Control.IndicateChildImageExpandedRoot = this.m_strIndicateChildImageExpandedRoot; } - + if (!string.IsNullOrEmpty(this.m_strIndicateChildImageExpandedSub)) { this.Control.IndicateChildImageExpandedSub = this.m_strIndicateChildImageExpandedSub; } - + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLRoot)) { this.Control.NodeLeftHTMLRoot = this.m_strNodeLeftHTMLRoot; } - + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLRoot)) { this.Control.NodeRightHTMLRoot = this.m_strNodeRightHTMLRoot; } - + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLSub)) { this.Control.NodeLeftHTMLSub = this.m_strNodeLeftHTMLSub; } - + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLSub)) { this.Control.NodeRightHTMLSub = this.m_strNodeRightHTMLSub; } - + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLBreadCrumbRoot)) { this.Control.NodeLeftHTMLBreadCrumbRoot = this.m_strNodeLeftHTMLBreadCrumbRoot; } - + if (!string.IsNullOrEmpty(this.m_strNodeLeftHTMLBreadCrumbSub)) { this.Control.NodeLeftHTMLBreadCrumbSub = this.m_strNodeLeftHTMLBreadCrumbSub; } - + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLBreadCrumbRoot)) { this.Control.NodeRightHTMLBreadCrumbRoot = this.m_strNodeRightHTMLBreadCrumbRoot; } - + if (!string.IsNullOrEmpty(this.m_strNodeRightHTMLBreadCrumbSub)) { this.Control.NodeRightHTMLBreadCrumbSub = this.m_strNodeRightHTMLBreadCrumbSub; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorHTML)) { this.Control.SeparatorHTML = this.m_strSeparatorHTML; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTML)) { this.Control.SeparatorLeftHTML = this.m_strSeparatorLeftHTML; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTML)) { this.Control.SeparatorRightHTML = this.m_strSeparatorRightHTML; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTMLActive)) { this.Control.SeparatorLeftHTMLActive = this.m_strSeparatorLeftHTMLActive; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTMLActive)) { this.Control.SeparatorRightHTMLActive = this.m_strSeparatorRightHTMLActive; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorLeftHTMLBreadCrumb)) { this.Control.SeparatorLeftHTMLBreadCrumb = this.m_strSeparatorLeftHTMLBreadCrumb; } - + if (!string.IsNullOrEmpty(this.m_strSeparatorRightHTMLBreadCrumb)) { this.Control.SeparatorRightHTMLBreadCrumb = this.m_strSeparatorRightHTMLBreadCrumb; } - + if (!string.IsNullOrEmpty(this.m_strCSSControl)) { this.Control.CSSControl = this.m_strCSSControl; } - + if (!string.IsNullOrEmpty(this.m_strCSSContainerRoot)) { this.Control.CSSContainerRoot = this.m_strCSSContainerRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSNode)) { this.Control.CSSNode = this.m_strCSSNode; } - + if (!string.IsNullOrEmpty(this.m_strCSSIcon)) { this.Control.CSSIcon = this.m_strCSSIcon; } - + if (!string.IsNullOrEmpty(this.m_strCSSContainerSub)) { this.Control.CSSContainerSub = this.m_strCSSContainerSub; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeHover)) { this.Control.CSSNodeHover = this.m_strCSSNodeHover; } - + if (!string.IsNullOrEmpty(this.m_strCSSBreak)) { this.Control.CSSBreak = this.m_strCSSBreak; } - + if (!string.IsNullOrEmpty(this.m_strCSSIndicateChildSub)) { this.Control.CSSIndicateChildSub = this.m_strCSSIndicateChildSub; } - + if (!string.IsNullOrEmpty(this.m_strCSSIndicateChildRoot)) { this.Control.CSSIndicateChildRoot = this.m_strCSSIndicateChildRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSBreadCrumbRoot)) { this.Control.CSSBreadCrumbRoot = this.m_strCSSBreadCrumbRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSBreadCrumbSub)) { this.Control.CSSBreadCrumbSub = this.m_strCSSBreadCrumbSub; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeRoot)) { this.Control.CSSNodeRoot = this.m_strCSSNodeRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeSelectedRoot)) { this.Control.CSSNodeSelectedRoot = this.m_strCSSNodeSelectedRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeSelectedSub)) { this.Control.CSSNodeSelectedSub = this.m_strCSSNodeSelectedSub; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeHoverRoot)) { this.Control.CSSNodeHoverRoot = this.m_strCSSNodeHoverRoot; } - + if (!string.IsNullOrEmpty(this.m_strCSSNodeHoverSub)) { this.Control.CSSNodeHoverSub = this.m_strCSSNodeHoverSub; } - + if (!string.IsNullOrEmpty(this.m_strCSSSeparator)) { this.Control.CSSSeparator = this.m_strCSSSeparator; } - + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparator)) { this.Control.CSSLeftSeparator = this.m_strCSSLeftSeparator; } - + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparator)) { this.Control.CSSRightSeparator = this.m_strCSSRightSeparator; } - + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparatorSelection)) { this.Control.CSSLeftSeparatorSelection = this.m_strCSSLeftSeparatorSelection; } - + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparatorSelection)) { this.Control.CSSRightSeparatorSelection = this.m_strCSSRightSeparatorSelection; } - + if (!string.IsNullOrEmpty(this.m_strCSSLeftSeparatorBreadCrumb)) { this.Control.CSSLeftSeparatorBreadCrumb = this.m_strCSSLeftSeparatorBreadCrumb; } - + if (!string.IsNullOrEmpty(this.m_strCSSRightSeparatorBreadCrumb)) { this.Control.CSSRightSeparatorBreadCrumb = this.m_strCSSRightSeparatorBreadCrumb; } - + if (!string.IsNullOrEmpty(this.m_strStyleBackColor)) { this.Control.StyleBackColor = this.m_strStyleBackColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleForeColor)) { this.Control.StyleForeColor = this.m_strStyleForeColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleHighlightColor)) { this.Control.StyleHighlightColor = this.m_strStyleHighlightColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleIconBackColor)) { this.Control.StyleIconBackColor = this.m_strStyleIconBackColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleSelectionBorderColor)) { this.Control.StyleSelectionBorderColor = this.m_strStyleSelectionBorderColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleSelectionColor)) { this.Control.StyleSelectionColor = this.m_strStyleSelectionColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleSelectionForeColor)) { this.Control.StyleSelectionForeColor = this.m_strStyleSelectionForeColor; } - + if (!string.IsNullOrEmpty(this.m_strStyleControlHeight)) { this.Control.StyleControlHeight = Convert.ToDecimal(this.m_strStyleControlHeight); } - + if (!string.IsNullOrEmpty(this.m_strStyleBorderWidth)) { this.Control.StyleBorderWidth = Convert.ToDecimal(this.m_strStyleBorderWidth); } - + if (!string.IsNullOrEmpty(this.m_strStyleNodeHeight)) { this.Control.StyleNodeHeight = Convert.ToDecimal(this.m_strStyleNodeHeight); } - + if (!string.IsNullOrEmpty(this.m_strStyleIconWidth)) { this.Control.StyleIconWidth = Convert.ToDecimal(this.m_strStyleIconWidth); } - + if (!string.IsNullOrEmpty(this.m_strStyleFontNames)) { this.Control.StyleFontNames = this.m_strStyleFontNames; } - + if (!string.IsNullOrEmpty(this.m_strStyleFontSize)) { this.Control.StyleFontSize = Convert.ToDecimal(this.m_strStyleFontSize); } - + if (!string.IsNullOrEmpty(this.m_strStyleFontBold)) { this.Control.StyleFontBold = this.m_strStyleFontBold; } - + if (!string.IsNullOrEmpty(this.m_strEffectsShadowColor)) { this.Control.EffectsShadowColor = this.m_strEffectsShadowColor; } - + if (!string.IsNullOrEmpty(this.m_strEffectsStyle)) { this.Control.EffectsStyle = this.m_strEffectsStyle; } - + if (!string.IsNullOrEmpty(this.m_strEffectsShadowStrength)) { this.Control.EffectsShadowStrength = Convert.ToInt32(this.m_strEffectsShadowStrength); } - + if (!string.IsNullOrEmpty(this.m_strEffectsTransition)) { this.Control.EffectsTransition = this.m_strEffectsTransition; } - + if (!string.IsNullOrEmpty(this.m_strEffectsDuration)) { this.Control.EffectsDuration = Convert.ToDouble(this.m_strEffectsDuration); } - + if (!string.IsNullOrEmpty(this.m_strEffectsShadowDirection)) { this.Control.EffectsShadowDirection = this.m_strEffectsShadowDirection; } - + this.Control.CustomAttributes = this.CustomAttributes; } @@ -2834,9 +2834,9 @@ private string GetPath(string strPath) return this.ResolveUrl(strPath); } } - + return strPath; - } + } } public class CustomAttribute diff --git a/DNN Platform/Library/UI/Skins/Pane.cs b/DNN Platform/Library/UI/Skins/Pane.cs index 3cf8eac8836..edfc70f6cb7 100644 --- a/DNN Platform/Library/UI/Skins/Pane.cs +++ b/DNN Platform/Library/UI/Skins/Pane.cs @@ -37,13 +37,13 @@ namespace DotNetNuke.UI.Skins /// /// ----------------------------------------------------------------------------- public class Pane - { + { private const string CPaneOutline = "paneOutline"; private HtmlGenericControl _containerWrapperControl; - private Dictionary _containers; - + private Dictionary _containers; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new Pane object from the Control in the Skin. /// @@ -52,14 +52,14 @@ public class Pane public Pane(HtmlContainerControl pane) { this.PaneControl = pane; - + // Disable ViewState (we enable it later in the process) this.PaneControl.ViewStateMode = ViewStateMode.Disabled; this.Name = pane.ID; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new Pane object from the Control in the Skin. /// @@ -70,8 +70,8 @@ public Pane(string name, HtmlContainerControl pane) { this.PaneControl = pane; this.Name = name; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of Containers. @@ -87,31 +87,31 @@ public Pane(string name, HtmlContainerControl pane) /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the name (ID) of the Pane. + /// Gets the PortalSettings of the Portal. /// /// ----------------------------------------------------------------------------- - protected string Name { get; set; } + protected PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the HtmlContainerControl. + /// Gets or sets and sets the name (ID) of the Pane. /// /// ----------------------------------------------------------------------------- - protected HtmlContainerControl PaneControl { get; set; } + protected string Name { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets the PortalSettings of the Portal. + /// Gets or sets and sets the HtmlContainerControl. /// /// ----------------------------------------------------------------------------- - protected PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - + protected HtmlContainerControl PaneControl { get; set; } + /// ----------------------------------------------------------------------------- /// /// InjectModule injects a Module (and its container) into the Pane. @@ -175,7 +175,7 @@ public void InjectModule(ModuleInfo module) // 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); @@ -229,7 +229,7 @@ public void InjectModule(ModuleInfo module) // only display the error to administrators this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, Skin.MODULELOAD_ERROR, lex).Container); } - + Exceptions.LogException(exc); throw lex; } @@ -263,7 +263,7 @@ public void ProcessPane() { 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); @@ -282,7 +282,7 @@ public void ProcessPane() { this.PaneControl.Attributes.Remove("style"); } - + if (this.PaneControl.Attributes["class"] != null) { this.PaneControl.Attributes["class"] = this.PaneControl.Attributes["class"] + " DNNEmptyPane"; @@ -307,7 +307,7 @@ public void ProcessPane() } } } - } + } private bool CanCollapsePane() { @@ -339,10 +339,10 @@ private bool CanCollapsePane() // Pane contains more than 1 control canCollapsePane = false; } - + return canCollapsePane; - } - + } + /// ----------------------------------------------------------------------------- /// /// LoadContainerByPath gets the Container from its Url(Path). @@ -367,10 +367,10 @@ private Containers.Container LoadContainerByPath(string containerPath) { containerPath = containerPath.Remove(0, Globals.ApplicationPath.Length); } - + container = ControlUtilities.LoadControl(this.PaneControl.Page, containerPath); container.ContainerSrc = containerSrc; - + // call databind so that any server logic in the container is executed container.DataBind(); } @@ -383,10 +383,10 @@ private Containers.Container LoadContainerByPath(string containerPath) // only display the error to administrators this._containerWrapperControl.Controls.Add(new ErrorContainer(this.PortalSettings, string.Format(Skin.CONTAINERLOAD_ERROR, containerPath), lex).Container); } - + Exceptions.LogException(lex); } - + return container; } @@ -408,7 +408,7 @@ private Containers.Container LoadContainerFromCookie(HttpRequest request) container = this.LoadContainerByPath(SkinController.FormatSkinSrc(cookie.Value + ".ascx", this.PortalSettings)); } } - + return container; } @@ -439,7 +439,7 @@ private Containers.Container LoadContainerFromPane() containerSrc = SkinController.FormatSkinSrc(containerSrc, this.PortalSettings); container = this.LoadContainerByPath(containerSrc); } - + return container; } @@ -458,7 +458,7 @@ private Containers.Container LoadContainerFromQueryString(ModuleInfo module, Htt string containerSrc = SkinController.FormatSkinSrc(Globals.QueryStringDecode(request.QueryString["ContainerSrc"]) + ".ascx", this.PortalSettings); container = this.LoadContainerByPath(containerSrc); } - + return container; } @@ -472,7 +472,7 @@ private Containers.Container LoadNoContainer(ModuleInfo module) { // always display container if the current user is the administrator or the module is being used in an admin case bool displayTitle = ModulePermissionController.CanEditModuleContent(module) || Globals.IsAdminSkin(); - + // unless the administrator is in view mode if (displayTitle) { @@ -484,7 +484,7 @@ private Containers.Container LoadNoContainer(ModuleInfo module) container = this.LoadContainerByPath(SkinController.FormatSkinSrc(noContainerSrc, this.PortalSettings)); } } - + return container; } @@ -497,7 +497,7 @@ private Containers.Container LoadModuleContainer(ModuleInfo module) if (this.PortalSettings.EnablePopUps && UrlUtils.InPopUp()) { containerSrc = module.ContainerPath + "popUpContainer.ascx"; - + // Check Skin for a popup Container if (module.ContainerSrc == this.PortalSettings.ActiveTab.ContainerSrc) { @@ -569,13 +569,13 @@ private Containers.Container LoadModuleContainer(ModuleInfo module) // set container id to an explicit short name to reduce page payload container.ID = "ctr"; - + // make the container id unique for the page if (module.ModuleID > -1) { container.ID += module.ModuleID.ToString(); } - + return container; } @@ -601,16 +601,16 @@ private void ModuleMoveToPanePostBack(ClientAPIPostBackEventArgs args) this.PaneControl.Page.Response.Redirect(this.PaneControl.Page.Request.RawUrl, true); } } - + private bool IsVesionableModule(ModuleInfo moduleInfo) - { + { if (string.IsNullOrEmpty(moduleInfo.DesktopModule.BusinessControllerClass)) { return false; - } - - object controller = Framework.Reflection.CreateObject(moduleInfo.DesktopModule.BusinessControllerClass, string.Empty); + } + + 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 c6c70050034..59ea9494ea1 100644 --- a/DNN Platform/Library/UI/Skins/Skin.cs +++ b/DNN Platform/Library/UI/Skins/Skin.cs @@ -58,28 +58,19 @@ 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"); - - private readonly ModuleCommunicate _communicator = new ModuleCommunicate(); - - // ReSharper restore InconsistentNaming private ArrayList _actionEventListeners; private Control _controlPanel; - private Dictionary _panes; - + private Dictionary _panes; + public Skin() { this.ModuleControlPipeline = Globals.DependencyProvider.GetRequiredService(); this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a Dictionary of Panes. @@ -95,6 +86,20 @@ public Dictionary Panes } } + /// ----------------------------------------------------------------------------- + /// + /// Gets the Path for this skin. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string SkinPath + { + get + { + return this.TemplateSourceDirectory + "/"; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets an ArrayList of ActionEventListeners. @@ -106,13 +111,21 @@ public ArrayList ActionEventListeners { return this._actionEventListeners ?? (this._actionEventListeners = new ArrayList()); } - + set { this._actionEventListeners = value; } } - + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets the Source for this skin. + /// + /// A String. + /// ----------------------------------------------------------------------------- + public string SkinSrc { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets the ControlPanel container. @@ -127,7 +140,7 @@ internal Control ControlPanel return this._controlPanel ?? (this._controlPanel = this.FindControl("ControlPanel")); } } - + /// ----------------------------------------------------------------------------- /// /// Gets the ModuleCommunicate instance for the skin. @@ -139,520 +152,423 @@ internal ModuleCommunicate Communicator { return this._communicator; } - } + } protected IModuleControlPipeline ModuleControlPipeline { get; } - - protected INavigationManager NavigationManager { get; } + + protected INavigationManager NavigationManager { get; } + + 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); + } /// ----------------------------------------------------------------------------- /// - /// Gets the Path for this skin. + /// AddModuleMessage adds a Moduel Message control to the Skin. /// - /// A String. + /// The Message Text. + /// The current control. + /// The type of the message. /// ----------------------------------------------------------------------------- - public string SkinPath + public static void AddModuleMessage(Control control, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - get - { - return this.TemplateSourceDirectory + "/"; - } + AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); } /// ----------------------------------------------------------------------------- /// - /// Gets or sets the Source for this skin. + /// AddModuleMessage adds a Moduel Message control to the Skin. /// - /// A String. + /// The Message Heading. + /// The Message Text. + /// The current control. + /// The type of the message. /// ----------------------------------------------------------------------------- - public string SkinSrc { get; set; } - - public static void AddModuleMessage(PortalModuleBase control, string message, ModuleMessage.ModuleMessageType moduleMessageType) + public static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); + AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); } - public static void AddModuleMessage(PortalModuleBase control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + /// ----------------------------------------------------------------------------- + /// + /// AddPageMessage adds a Page Message control to the Skin. + /// + /// The Message Heading. + /// The Icon to diplay. + /// The Message Text. + /// The Page. + /// ----------------------------------------------------------------------------- + public static void AddPageMessage(Page page, string heading, string message, string iconSrc) { - AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); + AddPageMessage(page, heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconSrc); } - + /// ----------------------------------------------------------------------------- /// - /// OnInit runs when the Skin is initialised. + /// AddPageMessage adds a Page Message control to the Skin. /// + /// The Message Heading. + /// The Icon to diplay. + /// The Message Text. + /// The skin. /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) + public static void AddPageMessage(Skin skin, string heading, string message, string iconSrc) { - 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(); + AddPageMessage(skin, heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconSrc); } /// ----------------------------------------------------------------------------- /// - /// OnLoad runs when the Skin is loaded. + /// AddPageMessage adds a Page Message control to the Skin. /// + /// The Message Heading. + /// The Message Text. + /// The skin. + /// The type of the message. /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) + public static void AddPageMessage(Skin skin, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - base.OnLoad(e); - - this.InvokeSkinEvents(SkinEventType.OnSkinLoad); + AddPageMessage(skin, heading, message, moduleMessageType, Null.NullString); } - - private static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) + + /// ----------------------------------------------------------------------------- + /// + /// AddPageMessage adds a Page Message control to the Skin. + /// + /// The Message Heading. + /// The Message Text. + /// The Page. + /// The type of the message. + /// ----------------------------------------------------------------------------- + public static void AddPageMessage(Page page, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - if (control != null) - { - if (!string.IsNullOrEmpty(message)) - { - var messagePlaceHolder = ControlUtilities.FindControl(control, "MessagePlaceHolder", true); - if (messagePlaceHolder != null) - { - messagePlaceHolder.Visible = true; - ModuleMessage moduleMessage = GetModuleMessageControl(heading, message, moduleMessageType, iconSrc); - messagePlaceHolder.Controls.Add(moduleMessage); - } - } - } + AddPageMessage(page, heading, message, moduleMessageType, Null.NullString); } - private static void AddPageMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) + /// ----------------------------------------------------------------------------- + /// + /// GetModuleMessageControl gets an existing Message Control and sets its properties. + /// + /// The Message Heading. + /// The Message Text. + /// The Message Icon. + /// + /// ----------------------------------------------------------------------------- + public static ModuleMessage GetModuleMessageControl(string heading, string message, string iconImage) { - if (!string.IsNullOrEmpty(message)) - { - Control contentPane = FindControlRecursive(control, Globals.glbDefaultPane); - - if (contentPane != null) - { - ModuleMessage moduleMessage = GetModuleMessageControl(heading, message, moduleMessageType, iconSrc); - contentPane.Controls.AddAt(0, moduleMessage); - } - } + return GetModuleMessageControl(heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconImage); } - private static Control FindControlRecursive(Control rootControl, string controlId) + /// ----------------------------------------------------------------------------- + /// + /// GetModuleMessageControl gets an existing Message Control and sets its properties. + /// + /// The Message Heading. + /// The Message Text. + /// The type of message. + /// + /// ----------------------------------------------------------------------------- + public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) { - if (rootControl.ID == controlId) - { - return rootControl; - } - - foreach (Control controlToSearch in rootControl.Controls) - { - Control controlToReturn = FindControlRecursive(controlToSearch, controlId); - if (controlToReturn != null) - { - return controlToReturn; - } - } - - return null; + return GetModuleMessageControl(heading, message, moduleMessageType, Null.NullString); } - private static Skin LoadSkin(PageBase page, string skinPath) + /// ----------------------------------------------------------------------------- + /// + /// GetModuleMessageControl gets an existing Message Control and sets its properties. + /// + /// The Message Heading. + /// The Message Text. + /// The Message Icon. + /// The type of message. + /// + /// ----------------------------------------------------------------------------- + public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconImage) { - 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; + // Use this to get a module message control + // with a standard DotNetNuke icon + var s = new Skin(); + var moduleMessage = (ModuleMessage)s.LoadControl("~/admin/skins/ModuleMessage.ascx"); + moduleMessage.Heading = heading; + moduleMessage.Text = message; + moduleMessage.IconImage = iconImage; + moduleMessage.IconType = moduleMessageType; + return moduleMessage; } - - private bool CheckExpired() + + /// ----------------------------------------------------------------------------- + /// + /// GetParentSkin gets the Parent Skin for a control. + /// + /// The control whose Parent Skin is requested. + /// + /// ----------------------------------------------------------------------------- + public static Skin GetParentSkin(PortalModuleBase module) { - bool blnExpired = false; - if (this.PortalSettings.ExpiryDate != Null.NullDate) + return GetParentSkin(module as Control); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetParentSkin gets the Parent Skin for a control. + /// + /// The control whose Parent Skin is requested. + /// + /// ----------------------------------------------------------------------------- + public static Skin GetParentSkin(Control control) + { + return ControlUtilities.FindParentControl(control); + } + + /// ----------------------------------------------------------------------------- + /// + /// GetPopUpSkin gets the Skin that is used in modal popup. + /// + /// The Page. + /// + /// ----------------------------------------------------------------------------- + public static Skin GetPopUpSkin(PageBase page) + { + Skin skin = null; + + // attempt to find and load a popup skin from the assigned skinned source + string skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; + if (!string.IsNullOrEmpty(skinSource)) { - if (Convert.ToDateTime(this.PortalSettings.ExpiryDate) < DateTime.Now && !Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) + skinSource = SkinController.FormatSkinSrc(SkinController.FormatSkinPath(skinSource) + "popUpSkin.ascx", page.PortalSettings); + + if (File.Exists(HttpContext.Current.Server.MapPath(SkinController.FormatSkinSrc(skinSource, page.PortalSettings)))) { - blnExpired = true; + skin = LoadSkin(page, skinSource); } } - - return blnExpired; - } - - private Pane GetPane(ModuleInfo module) - { - Pane pane; - bool found = this.Panes.TryGetValue(module.PaneName.ToLowerInvariant(), out pane); - if (!found) + // error loading popup skin - load default popup skin + if (skin == null) { - this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); + skinSource = Globals.HostPath + "Skins/_default/popUpSkin.ascx"; + skin = LoadSkin(page, skinSource); } - return pane; + // set skin path + page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); + + // set skin id to an explicit short name to reduce page payload and make it standards compliant + skin.ID = "dnn"; + + return skin; } - private void InjectControlPanel() + /// ----------------------------------------------------------------------------- + /// + /// GetSkin gets the Skin. + /// + /// The Page. + /// + /// ----------------------------------------------------------------------------- + public static Skin GetSkin(PageBase page) { - // if querystring dnnprintmode=true, controlpanel will not be shown - if (this.Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp() && this.Request.QueryString["hidecommandbar"] != "true") + Skin skin = null; + string skinSource = Null.NullString; + + // skin preview + if (page.Request.QueryString["SkinSrc"] != null) { - if (Host.AllowControlPanelToDetermineVisibility || (ControlPanelBase.IsPageAdminInternal() || ControlPanelBase.IsModuleAdminInternal())) - { - // ControlPanel processing - var controlPanel = ControlUtilities.LoadControl(this, Host.ControlPanel); - var form = (HtmlForm)this.Parent.FindControl("Form"); + skinSource = SkinController.FormatSkinSrc(Globals.QueryStringDecode(page.Request.QueryString["SkinSrc"]) + ".ascx", page.PortalSettings); + skin = LoadSkin(page, skinSource); + } - if (controlPanel.IncludeInControlHierarchy) + // load user skin ( based on cookie ) + if (skin == null) + { + HttpCookie skinCookie = page.Request.Cookies["_SkinSrc" + page.PortalSettings.PortalId]; + if (skinCookie != null) + { + if (!string.IsNullOrEmpty(skinCookie.Value)) { - // inject ControlPanel control into skin - if (this.ControlPanel == null || HostController.Instance.GetBoolean("IgnoreControlPanelWrapper", false)) - { - if (form != null) - { - form.Controls.AddAt(0, controlPanel); - } - else - { - this.Page.Controls.AddAt(0, controlPanel); - } - } - else - { - this.ControlPanel.Controls.Add(controlPanel); - } - - // register admin.css - ClientResourceManager.RegisterAdminStylesheet(this.Page, Globals.HostPath + "admin.css"); + skinSource = SkinController.FormatSkinSrc(skinCookie.Value + ".ascx", page.PortalSettings); + skin = LoadSkin(page, skinSource); } } } - } - - private void InvokeSkinEvents(SkinEventType skinEventType) - { - SharedList list = ((NaiveLockingList)DotNetNukeContext.Current.SkinEventListeners).SharedList; - using (list.GetReadLock()) + // load assigned skin + if (skin == null) { - foreach (var listener in list.Where(x => x.EventType == skinEventType)) + // DNN-6170 ensure skin value is culture specific + // skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; + skinSource = Globals.IsAdminSkin() ? PortalController.GetPortalSetting("DefaultAdminSkin", page.PortalSettings.PortalId, + Host.DefaultPortalSkin, page.PortalSettings.CultureCode) : page.PortalSettings.ActiveTab.SkinSrc; + if (!string.IsNullOrEmpty(skinSource)) { - listener.SkinEvent.Invoke(this, new SkinEventArgs(this)); + skinSource = SkinController.FormatSkinSrc(skinSource, page.PortalSettings); + skin = LoadSkin(page, skinSource); } } - } - private void LoadPanes() - { - // iterate page controls - foreach (Control ctlControl in this.Controls) + // error loading skin - load default + if (skin == null) { - var objPaneControl = ctlControl as HtmlContainerControl; + skinSource = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalSkin(), page.PortalSettings); + skin = LoadSkin(page, skinSource); + } - // Panes must be runat=server controls so they have to have an ID - if (objPaneControl != null && !string.IsNullOrEmpty(objPaneControl.ID)) - { - // load the skin panes - switch (objPaneControl.TagName.ToLowerInvariant()) - { - case "td": - case "div": - case "span": - case "p": - case "section": - case "header": - case "footer": - case "main": - case "article": - case "aside": - // content pane - if (!objPaneControl.ID.Equals("controlpanel", StringComparison.InvariantCultureIgnoreCase)) - { - // Add to the PortalSettings (for use in the Control Panel) - this.PortalSettings.ActiveTab.Panes.Add(objPaneControl.ID); + // set skin path + page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); - // Add to the Panes collection - this.Panes.Add(objPaneControl.ID.ToLowerInvariant(), new Pane(objPaneControl)); - } - else - { - // Control Panel pane - this._controlPanel = objPaneControl; - } - - break; - } - } - } + // set skin id to an explicit short name to reduce page payload and make it standards compliant + skin.ID = "dnn"; + + return skin; } - private bool ProcessModule(ModuleInfo module) + public static List GetInstalledSkins() { - var success = true; - if (ModuleInjectionManager.CanInjectModule(module, this.PortalSettings)) + var list = new List(); + foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) { - // We need to ensure that Content Item exists since in old versions Content Items are not needed for modules - this.EnsureContentItemForModule(module); - - Pane pane = this.GetPane(module); - - if (pane != null) - { - success = this.InjectModule(pane, module); - } - else + if (!folder.EndsWith(Globals.glbHostSkinFolder)) { - var lex = new ModuleLoadException(Localization.GetString("PaneNotFound.Error")); - this.Controls.Add(new ErrorContainer(this.PortalSettings, MODULELOAD_ERROR, lex).Container); - Exceptions.LogException(lex); + var skin = new InstalledSkinInfo(); + skin.SkinName = folder.Substring(folder.LastIndexOf("\\") + 1); + skin.InUse = isFallbackSkin(folder) || !SkinController.CanDeleteSkin(folder, string.Empty); + list.Add(skin); } } - - return success; + + return list; } + /// ----------------------------------------------------------------------------- /// - /// Handle access denied errors by displaying an error message - /// or by performing a redirect to a predefined "access denied URL". + /// InjectModule injects the module into the Pane. /// - /// - private void HandleAccesDenied(bool redirect = false) + /// The module to inject. + /// The pane. + /// + /// ----------------------------------------------------------------------------- + public bool InjectModule(Pane pane, ModuleInfo module) { - var message = Localization.GetString("TabAccess.Error"); - if (redirect) - { - var redirectUrl = Globals.AccessDeniedURL(message); - this.Response.Redirect(redirectUrl, true); - } - else - { - AddPageMessage(this, string.Empty, message, ModuleMessage.ModuleMessageType.YellowWarning); - } - } + bool bSuccess = true; - private bool ProcessMasterModules() - { - bool success = true; - if (TabPermissionController.CanViewPage()) + // try to inject the module into the pane + try { - // We need to ensure that Content Item exists since in old versions Content Items are not needed for tabs - this.EnsureContentItemForTab(this.PortalSettings.ActiveTab); - - // Versioning checks. - if (!TabController.CurrentPage.HasAVisibleVersion) - { - this.HandleAccesDenied(true); - } - - int urlVersion; - if (TabVersionUtils.TryGetUrlVersion(out urlVersion)) - { - if (!TabVersionUtils.CanSeeVersionedPages()) - { - this.HandleAccesDenied(false); - return true; - } - - if (TabVersionController.Instance.GetTabVersions(TabController.CurrentPage.TabID).All(tabVersion => tabVersion.Version != urlVersion)) - { - this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.ErrorPage404, string.Empty, "status=404")); - } - } - - // check portal expiry date - if (!this.CheckExpired()) + if (this.PortalSettings.ActiveTab.TabID == this.PortalSettings.UserTabId || this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.UserTabId) { - if ((this.PortalSettings.ActiveTab.StartDate < DateAndTime.Now && this.PortalSettings.ActiveTab.EndDate > DateAndTime.Now) || TabPermissionController.CanAdminPage() || Globals.IsLayoutMode()) - { - foreach (var objModule in PortalSettingsController.Instance().GetTabModules(this.PortalSettings)) - { - success = this.ProcessModule(objModule); - } - } - else + var profileModule = this.ModuleControlPipeline.LoadModuleControl(this.Page, module) as IProfileModule; + if (profileModule == null || profileModule.DisplayModule) { - this.HandleAccesDenied(false); + pane.InjectModule(module); } } else { - AddPageMessage( - this, - string.Empty, - string.Format(Localization.GetString("ContractExpired.Error"), this.PortalSettings.PortalName, Globals.GetMediumDate(this.PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), this.PortalSettings.Email), - ModuleMessage.ModuleMessageType.RedError); + pane.InjectModule(module); } } - else + catch (ThreadAbortException) { - // If request localized page which haven't complete translate yet, redirect to default language version. - var redirectUrl = Globals.AccessDeniedURL(Localization.GetString("TabAccess.Error")); - - // Current locale will use default if did'nt find any - Locale currentLocale = LocaleController.Instance.GetCurrentLocale(this.PortalSettings.PortalId); - if (this.PortalSettings.ContentLocalizationEnabled && - TabController.CurrentPage.CultureCode != currentLocale.Code) - { - redirectUrl = new LanguageTokenReplace { Language = currentLocale.Code }.ReplaceEnvironmentTokens("[URL]"); - } - - this.Response.Redirect(redirectUrl, true); + // Response.Redirect may called in module control's OnInit method, so it will cause ThreadAbortException, no need any action here. } - - return success; - } - - private void EnsureContentItemForTab(Entities.Tabs.TabInfo tabInfo) - { - // If tab exists but ContentItem not, then we create it - if (tabInfo.ContentItemId == Null.NullInteger && tabInfo.TabID != Null.NullInteger) + catch (Exception ex) { - TabController.Instance.CreateContentItem(tabInfo); - TabController.Instance.UpdateTab(tabInfo); + Exceptions.LogException(ex); + bSuccess = false; } - } - private void EnsureContentItemForModule(ModuleInfo module) - { - // If module exists but ContentItem not, then we create it - if (module.ContentItemId == Null.NullInteger && module.ModuleID != Null.NullInteger) - { - ModuleController.Instance.CreateContentItem(module); - ModuleController.Instance.UpdateModule(module); - } + return bSuccess; } - private void ProcessPanes() + /// ----------------------------------------------------------------------------- + /// + /// RegisterModuleActionEvent registers a Module Action Event. + /// + /// The ID of the module. + /// An Action Event Handler. + /// ----------------------------------------------------------------------------- + public void RegisterModuleActionEvent(int moduleId, ActionEventHandler e) { - foreach (KeyValuePair kvp in this.Panes) - { - kvp.Value.ProcessPane(); - } + this.ActionEventListeners.Add(new ModuleActionEventListener(moduleId, e)); } - private bool ProcessSlaveModule() + /// ----------------------------------------------------------------------------- + /// + /// OnInit runs when the Skin is initialised. + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) { - var success = true; - var key = UIUtilities.GetControlKey(); - var moduleId = UIUtilities.GetModuleId(key); - var slaveModule = UIUtilities.GetSlaveModule(moduleId, key, this.PortalSettings.ActiveTab.TabID); + base.OnInit(e); - Pane pane; - this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); - slaveModule.PaneName = Globals.glbDefaultPane; - slaveModule.ContainerSrc = this.PortalSettings.ActiveTab.ContainerSrc; - if (string.IsNullOrEmpty(slaveModule.ContainerSrc)) - { - slaveModule.ContainerSrc = this.PortalSettings.DefaultPortalContainer; - } - - slaveModule.ContainerSrc = SkinController.FormatSkinSrc(slaveModule.ContainerSrc, this.PortalSettings); - slaveModule.ContainerPath = SkinController.FormatSkinPath(slaveModule.ContainerSrc); + // Load the Panes + this.LoadPanes(); - var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID); - if (moduleControl != null) + // 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) { - slaveModule.ModuleControlId = moduleControl.ModuleControlID; - slaveModule.IconFile = moduleControl.IconFile; + AddPageMessage(this, Localization.GetString("CriticalError.Error"), " ", ModuleMessage.ModuleMessageType.RedError); - string permissionKey; - switch (slaveModule.ModuleControl.ControlSrc) + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser) { - case "Admin/Modules/ModuleSettings.ascx": - permissionKey = "MANAGE"; - break; - case "Admin/Modules/Import.ascx": - permissionKey = "IMPORT"; - break; - case "Admin/Modules/Export.ascx": - permissionKey = "EXPORT"; - break; - default: - permissionKey = "CONTENT"; - break; - } + ServicesFramework.Instance.RequestAjaxScriptSupport(); + ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); - if (ModulePermissionController.HasModuleAccess(slaveModule.ModuleControl.ControlType, permissionKey, slaveModule)) - { - success = this.InjectModule(pane, slaveModule); + JavaScript.RequestRegistration(CommonJs.jQueryUI); + JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn_dom); + ClientResourceManager.RegisterScript(this.Page, "~/resources/shared/scripts/dnn.logViewer.js"); } - else + } + + 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)) { - this.Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("ModuleAccess.Error")), true); + 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(); } - return success; - } + // 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); + } /// ----------------------------------------------------------------------------- /// @@ -709,348 +625,432 @@ protected override void OnUnload(EventArgs e) base.OnUnload(e); this.InvokeSkinEvents(SkinEventType.OnSkinUnLoad); - } + } - /// ----------------------------------------------------------------------------- - /// - /// AddModuleMessage adds a Moduel Message control to the Skin. - /// - /// The Message Text. - /// The current control. - /// The type of the message. - /// ----------------------------------------------------------------------------- - public static void AddModuleMessage(Control control, string message, ModuleMessage.ModuleMessageType moduleMessageType) + private static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) { - AddModuleMessage(control, string.Empty, message, moduleMessageType, Null.NullString); + if (control != null) + { + if (!string.IsNullOrEmpty(message)) + { + var messagePlaceHolder = ControlUtilities.FindControl(control, "MessagePlaceHolder", true); + if (messagePlaceHolder != null) + { + messagePlaceHolder.Visible = true; + ModuleMessage moduleMessage = GetModuleMessageControl(heading, message, moduleMessageType, iconSrc); + messagePlaceHolder.Controls.Add(moduleMessage); + } + } + } } - /// ----------------------------------------------------------------------------- - /// - /// AddModuleMessage adds a Moduel Message control to the Skin. - /// - /// The Message Heading. - /// The Message Text. - /// The current control. - /// The type of the message. - /// ----------------------------------------------------------------------------- - public static void AddModuleMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + private static void AddPageMessage(Control control, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconSrc) { - AddModuleMessage(control, heading, message, moduleMessageType, Null.NullString); - } + if (!string.IsNullOrEmpty(message)) + { + Control contentPane = FindControlRecursive(control, Globals.glbDefaultPane); - /// ----------------------------------------------------------------------------- - /// - /// AddPageMessage adds a Page Message control to the Skin. - /// - /// The Message Heading. - /// The Icon to diplay. - /// The Message Text. - /// The Page. - /// ----------------------------------------------------------------------------- - public static void AddPageMessage(Page page, string heading, string message, string iconSrc) - { - AddPageMessage(page, heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconSrc); + if (contentPane != null) + { + ModuleMessage moduleMessage = GetModuleMessageControl(heading, message, moduleMessageType, iconSrc); + contentPane.Controls.AddAt(0, moduleMessage); + } + } } - /// ----------------------------------------------------------------------------- - /// - /// AddPageMessage adds a Page Message control to the Skin. - /// - /// The Message Heading. - /// The Icon to diplay. - /// The Message Text. - /// The skin. - /// ----------------------------------------------------------------------------- - public static void AddPageMessage(Skin skin, string heading, string message, string iconSrc) + private static Control FindControlRecursive(Control rootControl, string controlId) { - AddPageMessage(skin, heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconSrc); - } + if (rootControl.ID == controlId) + { + return rootControl; + } - /// ----------------------------------------------------------------------------- - /// - /// AddPageMessage adds a Page Message control to the Skin. - /// - /// The Message Heading. - /// The Message Text. - /// The skin. - /// The type of the message. - /// ----------------------------------------------------------------------------- - public static void AddPageMessage(Skin skin, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) - { - AddPageMessage(skin, heading, message, moduleMessageType, Null.NullString); + foreach (Control controlToSearch in rootControl.Controls) + { + Control controlToReturn = FindControlRecursive(controlToSearch, controlId); + if (controlToReturn != null) + { + return controlToReturn; + } + } + + return null; } - /// ----------------------------------------------------------------------------- - /// - /// AddPageMessage adds a Page Message control to the Skin. - /// - /// The Message Heading. - /// The Message Text. - /// The Page. - /// The type of the message. - /// ----------------------------------------------------------------------------- - public static void AddPageMessage(Page page, string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + private static Skin LoadSkin(PageBase page, string skinPath) { - AddPageMessage(page, heading, message, moduleMessageType, Null.NullString); + 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; } - /// ----------------------------------------------------------------------------- - /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties. - /// - /// The Message Heading. - /// The Message Text. - /// The Message Icon. - /// - /// ----------------------------------------------------------------------------- - public static ModuleMessage GetModuleMessageControl(string heading, string message, string iconImage) + private static bool isFallbackSkin(string skinPath) { - return GetModuleMessageControl(heading, message, ModuleMessage.ModuleMessageType.GreenSuccess, iconImage); + SkinDefaults defaultSkin = SkinDefaults.GetSkinDefaults(SkinDefaultType.SkinInfo); + string defaultSkinPath = (Globals.HostMapPath + SkinController.RootSkin + defaultSkin.Folder).Replace("/", "\\"); + if (defaultSkinPath.EndsWith("\\")) + { + defaultSkinPath = defaultSkinPath.Substring(0, defaultSkinPath.Length - 1); + } + + return skinPath.IndexOf(defaultSkinPath, StringComparison.CurrentCultureIgnoreCase) != -1; } - /// ----------------------------------------------------------------------------- - /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties. - /// - /// The Message Heading. - /// The Message Text. - /// The type of message. - /// - /// ----------------------------------------------------------------------------- - public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType) + private bool CheckExpired() { - return GetModuleMessageControl(heading, message, moduleMessageType, Null.NullString); + bool blnExpired = false; + if (this.PortalSettings.ExpiryDate != Null.NullDate) + { + if (Convert.ToDateTime(this.PortalSettings.ExpiryDate) < DateTime.Now && !Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) + { + blnExpired = true; + } + } + + return blnExpired; } - /// ----------------------------------------------------------------------------- - /// - /// GetModuleMessageControl gets an existing Message Control and sets its properties. - /// - /// The Message Heading. - /// The Message Text. - /// The Message Icon. - /// The type of message. - /// - /// ----------------------------------------------------------------------------- - public static ModuleMessage GetModuleMessageControl(string heading, string message, ModuleMessage.ModuleMessageType moduleMessageType, string iconImage) + private Pane GetPane(ModuleInfo module) { - // Use this to get a module message control - // with a standard DotNetNuke icon - var s = new Skin(); - var moduleMessage = (ModuleMessage)s.LoadControl("~/admin/skins/ModuleMessage.ascx"); - moduleMessage.Heading = heading; - moduleMessage.Text = message; - moduleMessage.IconImage = iconImage; - moduleMessage.IconType = moduleMessageType; - return moduleMessage; + Pane pane; + bool found = this.Panes.TryGetValue(module.PaneName.ToLowerInvariant(), out pane); + + if (!found) + { + this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); + } + + return pane; } - /// ----------------------------------------------------------------------------- - /// - /// GetParentSkin gets the Parent Skin for a control. - /// - /// The control whose Parent Skin is requested. - /// - /// ----------------------------------------------------------------------------- - public static Skin GetParentSkin(PortalModuleBase module) + private void InjectControlPanel() { - return GetParentSkin(module as Control); + // if querystring dnnprintmode=true, controlpanel will not be shown + if (this.Request.QueryString["dnnprintmode"] != "true" && !UrlUtils.InPopUp() && this.Request.QueryString["hidecommandbar"] != "true") + { + if (Host.AllowControlPanelToDetermineVisibility || (ControlPanelBase.IsPageAdminInternal() || ControlPanelBase.IsModuleAdminInternal())) + { + // ControlPanel processing + var controlPanel = ControlUtilities.LoadControl(this, Host.ControlPanel); + var form = (HtmlForm)this.Parent.FindControl("Form"); + + if (controlPanel.IncludeInControlHierarchy) + { + // inject ControlPanel control into skin + if (this.ControlPanel == null || HostController.Instance.GetBoolean("IgnoreControlPanelWrapper", false)) + { + if (form != null) + { + form.Controls.AddAt(0, controlPanel); + } + else + { + this.Page.Controls.AddAt(0, controlPanel); + } + } + else + { + this.ControlPanel.Controls.Add(controlPanel); + } + + // register admin.css + ClientResourceManager.RegisterAdminStylesheet(this.Page, Globals.HostPath + "admin.css"); + } + } + } } - /// ----------------------------------------------------------------------------- - /// - /// GetParentSkin gets the Parent Skin for a control. - /// - /// The control whose Parent Skin is requested. - /// - /// ----------------------------------------------------------------------------- - public static Skin GetParentSkin(Control control) + private void InvokeSkinEvents(SkinEventType skinEventType) { - return ControlUtilities.FindParentControl(control); + SharedList list = ((NaiveLockingList)DotNetNukeContext.Current.SkinEventListeners).SharedList; + + using (list.GetReadLock()) + { + foreach (var listener in list.Where(x => x.EventType == skinEventType)) + { + listener.SkinEvent.Invoke(this, new SkinEventArgs(this)); + } + } } - /// ----------------------------------------------------------------------------- - /// - /// GetPopUpSkin gets the Skin that is used in modal popup. - /// - /// The Page. - /// - /// ----------------------------------------------------------------------------- - public static Skin GetPopUpSkin(PageBase page) + private void LoadPanes() { - Skin skin = null; - - // attempt to find and load a popup skin from the assigned skinned source - string skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; - if (!string.IsNullOrEmpty(skinSource)) + // iterate page controls + foreach (Control ctlControl in this.Controls) { - skinSource = SkinController.FormatSkinSrc(SkinController.FormatSkinPath(skinSource) + "popUpSkin.ascx", page.PortalSettings); + var objPaneControl = ctlControl as HtmlContainerControl; - if (File.Exists(HttpContext.Current.Server.MapPath(SkinController.FormatSkinSrc(skinSource, page.PortalSettings)))) + // Panes must be runat=server controls so they have to have an ID + if (objPaneControl != null && !string.IsNullOrEmpty(objPaneControl.ID)) { - skin = LoadSkin(page, skinSource); + // load the skin panes + switch (objPaneControl.TagName.ToLowerInvariant()) + { + case "td": + case "div": + case "span": + case "p": + case "section": + case "header": + case "footer": + case "main": + case "article": + case "aside": + // content pane + if (!objPaneControl.ID.Equals("controlpanel", StringComparison.InvariantCultureIgnoreCase)) + { + // Add to the PortalSettings (for use in the Control Panel) + this.PortalSettings.ActiveTab.Panes.Add(objPaneControl.ID); + + // Add to the Panes collection + this.Panes.Add(objPaneControl.ID.ToLowerInvariant(), new Pane(objPaneControl)); + } + else + { + // Control Panel pane + this._controlPanel = objPaneControl; + } + + break; + } } } + } - // error loading popup skin - load default popup skin - if (skin == null) + private bool ProcessModule(ModuleInfo module) + { + var success = true; + if (ModuleInjectionManager.CanInjectModule(module, this.PortalSettings)) { - skinSource = Globals.HostPath + "Skins/_default/popUpSkin.ascx"; - skin = LoadSkin(page, skinSource); + // We need to ensure that Content Item exists since in old versions Content Items are not needed for modules + this.EnsureContentItemForModule(module); + + Pane pane = this.GetPane(module); + + if (pane != null) + { + success = this.InjectModule(pane, module); + } + else + { + var lex = new ModuleLoadException(Localization.GetString("PaneNotFound.Error")); + this.Controls.Add(new ErrorContainer(this.PortalSettings, MODULELOAD_ERROR, lex).Container); + Exceptions.LogException(lex); + } } - // set skin path - page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); - - // set skin id to an explicit short name to reduce page payload and make it standards compliant - skin.ID = "dnn"; - - return skin; + return success; } - /// ----------------------------------------------------------------------------- /// - /// GetSkin gets the Skin. + /// Handle access denied errors by displaying an error message + /// or by performing a redirect to a predefined "access denied URL". /// - /// The Page. - /// - /// ----------------------------------------------------------------------------- - public static Skin GetSkin(PageBase page) + /// + private void HandleAccesDenied(bool redirect = false) { - Skin skin = null; - string skinSource = Null.NullString; - - // skin preview - if (page.Request.QueryString["SkinSrc"] != null) + var message = Localization.GetString("TabAccess.Error"); + if (redirect) { - skinSource = SkinController.FormatSkinSrc(Globals.QueryStringDecode(page.Request.QueryString["SkinSrc"]) + ".ascx", page.PortalSettings); - skin = LoadSkin(page, skinSource); + var redirectUrl = Globals.AccessDeniedURL(message); + this.Response.Redirect(redirectUrl, true); + } + else + { + AddPageMessage(this, string.Empty, message, ModuleMessage.ModuleMessageType.YellowWarning); } + } - // load user skin ( based on cookie ) - if (skin == null) + private bool ProcessMasterModules() + { + bool success = true; + if (TabPermissionController.CanViewPage()) { - HttpCookie skinCookie = page.Request.Cookies["_SkinSrc" + page.PortalSettings.PortalId]; - if (skinCookie != null) + // We need to ensure that Content Item exists since in old versions Content Items are not needed for tabs + this.EnsureContentItemForTab(this.PortalSettings.ActiveTab); + + // Versioning checks. + if (!TabController.CurrentPage.HasAVisibleVersion) { - if (!string.IsNullOrEmpty(skinCookie.Value)) + this.HandleAccesDenied(true); + } + + int urlVersion; + if (TabVersionUtils.TryGetUrlVersion(out urlVersion)) + { + if (!TabVersionUtils.CanSeeVersionedPages()) { - skinSource = SkinController.FormatSkinSrc(skinCookie.Value + ".ascx", page.PortalSettings); - skin = LoadSkin(page, skinSource); + this.HandleAccesDenied(false); + return true; + } + + if (TabVersionController.Instance.GetTabVersions(TabController.CurrentPage.TabID).All(tabVersion => tabVersion.Version != urlVersion)) + { + this.Response.Redirect(this.NavigationManager.NavigateURL(this.PortalSettings.ErrorPage404, string.Empty, "status=404")); } } - } - // load assigned skin - if (skin == null) - { - // DNN-6170 ensure skin value is culture specific - // skinSource = Globals.IsAdminSkin() ? SkinController.FormatSkinSrc(page.PortalSettings.DefaultAdminSkin, page.PortalSettings) : page.PortalSettings.ActiveTab.SkinSrc; - skinSource = Globals.IsAdminSkin() ? PortalController.GetPortalSetting("DefaultAdminSkin", page.PortalSettings.PortalId, - Host.DefaultPortalSkin, page.PortalSettings.CultureCode) : page.PortalSettings.ActiveTab.SkinSrc; - if (!string.IsNullOrEmpty(skinSource)) + // check portal expiry date + if (!this.CheckExpired()) { - skinSource = SkinController.FormatSkinSrc(skinSource, page.PortalSettings); - skin = LoadSkin(page, skinSource); + if ((this.PortalSettings.ActiveTab.StartDate < DateAndTime.Now && this.PortalSettings.ActiveTab.EndDate > DateAndTime.Now) || TabPermissionController.CanAdminPage() || Globals.IsLayoutMode()) + { + foreach (var objModule in PortalSettingsController.Instance().GetTabModules(this.PortalSettings)) + { + success = this.ProcessModule(objModule); + } + } + else + { + this.HandleAccesDenied(false); + } + } + else + { + AddPageMessage( + this, + string.Empty, + string.Format(Localization.GetString("ContractExpired.Error"), this.PortalSettings.PortalName, Globals.GetMediumDate(this.PortalSettings.ExpiryDate.ToString(CultureInfo.InvariantCulture)), this.PortalSettings.Email), + ModuleMessage.ModuleMessageType.RedError); } } - - // error loading skin - load default - if (skin == null) + else { - skinSource = SkinController.FormatSkinSrc(SkinController.GetDefaultPortalSkin(), page.PortalSettings); - skin = LoadSkin(page, skinSource); + // If request localized page which haven't complete translate yet, redirect to default language version. + var redirectUrl = Globals.AccessDeniedURL(Localization.GetString("TabAccess.Error")); + + // Current locale will use default if did'nt find any + Locale currentLocale = LocaleController.Instance.GetCurrentLocale(this.PortalSettings.PortalId); + if (this.PortalSettings.ContentLocalizationEnabled && + TabController.CurrentPage.CultureCode != currentLocale.Code) + { + redirectUrl = new LanguageTokenReplace { Language = currentLocale.Code }.ReplaceEnvironmentTokens("[URL]"); + } + + this.Response.Redirect(redirectUrl, true); } - // set skin path - page.PortalSettings.ActiveTab.SkinPath = SkinController.FormatSkinPath(skinSource); + return success; + } - // set skin id to an explicit short name to reduce page payload and make it standards compliant - skin.ID = "dnn"; + private void EnsureContentItemForTab(Entities.Tabs.TabInfo tabInfo) + { + // If tab exists but ContentItem not, then we create it + if (tabInfo.ContentItemId == Null.NullInteger && tabInfo.TabID != Null.NullInteger) + { + TabController.Instance.CreateContentItem(tabInfo); + TabController.Instance.UpdateTab(tabInfo); + } + } - return skin; + private void EnsureContentItemForModule(ModuleInfo module) + { + // If module exists but ContentItem not, then we create it + if (module.ContentItemId == Null.NullInteger && module.ModuleID != Null.NullInteger) + { + ModuleController.Instance.CreateContentItem(module); + ModuleController.Instance.UpdateModule(module); + } } - public static List GetInstalledSkins() + private void ProcessPanes() { - var list = new List(); - foreach (string folder in Directory.GetDirectories(Path.Combine(Globals.HostMapPath, "Skins"))) + foreach (KeyValuePair kvp in this.Panes) { - 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); - } + kvp.Value.ProcessPane(); } - - return list; - } + } - /// ----------------------------------------------------------------------------- - /// - /// InjectModule injects the module into the Pane. - /// - /// The module to inject. - /// The pane. - /// - /// ----------------------------------------------------------------------------- - public bool InjectModule(Pane pane, ModuleInfo module) + private bool ProcessSlaveModule() { - bool bSuccess = true; + var success = true; + var key = UIUtilities.GetControlKey(); + var moduleId = UIUtilities.GetModuleId(key); + var slaveModule = UIUtilities.GetSlaveModule(moduleId, key, this.PortalSettings.ActiveTab.TabID); - // try to inject the module into the pane - try + Pane pane; + this.Panes.TryGetValue(Globals.glbDefaultPane.ToLowerInvariant(), out pane); + slaveModule.PaneName = Globals.glbDefaultPane; + slaveModule.ContainerSrc = this.PortalSettings.ActiveTab.ContainerSrc; + if (string.IsNullOrEmpty(slaveModule.ContainerSrc)) { - if (this.PortalSettings.ActiveTab.TabID == this.PortalSettings.UserTabId || this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.UserTabId) + slaveModule.ContainerSrc = this.PortalSettings.DefaultPortalContainer; + } + + slaveModule.ContainerSrc = SkinController.FormatSkinSrc(slaveModule.ContainerSrc, this.PortalSettings); + slaveModule.ContainerPath = SkinController.FormatSkinPath(slaveModule.ContainerSrc); + + var moduleControl = ModuleControlController.GetModuleControlByControlKey(key, slaveModule.ModuleDefID); + if (moduleControl != null) + { + slaveModule.ModuleControlId = moduleControl.ModuleControlID; + slaveModule.IconFile = moduleControl.IconFile; + + string permissionKey; + switch (slaveModule.ModuleControl.ControlSrc) { - var profileModule = this.ModuleControlPipeline.LoadModuleControl(this.Page, module) as IProfileModule; - if (profileModule == null || profileModule.DisplayModule) - { - pane.InjectModule(module); - } + case "Admin/Modules/ModuleSettings.ascx": + permissionKey = "MANAGE"; + break; + case "Admin/Modules/Import.ascx": + permissionKey = "IMPORT"; + break; + case "Admin/Modules/Export.ascx": + permissionKey = "EXPORT"; + break; + default: + permissionKey = "CONTENT"; + break; + } + + if (ModulePermissionController.HasModuleAccess(slaveModule.ModuleControl.ControlType, permissionKey, slaveModule)) + { + success = this.InjectModule(pane, slaveModule); } else { - pane.InjectModule(module); + this.Response.Redirect(Globals.AccessDeniedURL(Localization.GetString("ModuleAccess.Error")), 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 ex) - { - Exceptions.LogException(ex); - bSuccess = false; - } - - return bSuccess; - } - /// ----------------------------------------------------------------------------- - /// - /// RegisterModuleActionEvent registers a Module Action Event. - /// - /// The ID of the module. - /// An Action Event Handler. - /// ----------------------------------------------------------------------------- - public void RegisterModuleActionEvent(int moduleId, ActionEventHandler e) - { - this.ActionEventListeners.Add(new ModuleActionEventListener(moduleId, e)); + return success; } - private static bool isFallbackSkin(string skinPath) - { - SkinDefaults defaultSkin = SkinDefaults.GetSkinDefaults(SkinDefaultType.SkinInfo); - string defaultSkinPath = (Globals.HostMapPath + SkinController.RootSkin + defaultSkin.Folder).Replace("/", "\\"); - if (defaultSkinPath.EndsWith("\\")) - { - defaultSkinPath = defaultSkinPath.Substring(0, defaultSkinPath.Length - 1); - } - - return skinPath.IndexOf(defaultSkinPath, StringComparison.CurrentCultureIgnoreCase) != -1; - } + // 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"); + + private readonly ModuleCommunicate _communicator = new ModuleCommunicate(); + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Library/UI/Skins/SkinControl.cs b/DNN Platform/Library/UI/Skins/SkinControl.cs index e007bf65ee9..1e378724f82 100644 --- a/DNN Platform/Library/UI/Skins/SkinControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinControl.cs @@ -17,25 +17,25 @@ namespace DotNetNuke.UI.Skins using DotNetNuke.UI.WebControls; public class SkinControl : UserControlBase - { + { protected DropDownList cboSkin; protected CommandButton cmdPreview; + protected RadioButton optHost; + protected RadioButton optSite; private string _DefaultKey = "System"; private string _SkinRoot; private string _SkinSrc; private string _Width = string.Empty; private string _localResourceFile; private PortalInfo _objPortal; - protected RadioButton optHost; - protected RadioButton optSite; - + public string DefaultKey { get { return this._DefaultKey; } - + set { this._DefaultKey = value; @@ -48,7 +48,7 @@ public string Width { return Convert.ToString(this.ViewState["SkinControlWidth"]); } - + set { this._Width = value; @@ -61,7 +61,7 @@ public string SkinRoot { return Convert.ToString(this.ViewState["SkinRoot"]); } - + set { this._SkinRoot = value; @@ -81,7 +81,7 @@ public string SkinSrc return string.Empty; } } - + set { this._SkinSrc = value; @@ -101,26 +101,26 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } - } - + } + /// /// The Page_Load server event handler on this page is used /// to populate the role information for the page. /// protected override void OnLoad(EventArgs e) { - base.OnLoad(e); + base.OnLoad(e); this.optHost.CheckedChanged += this.optHost_CheckedChanged; this.optSite.CheckedChanged += this.optSite_CheckedChanged; - this.cmdPreview.Click += this.cmdPreview_Click; + this.cmdPreview.Click += this.cmdPreview_Click; try { if (this.Request.QueryString["pid"] != null && (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID) || UserController.Instance.GetCurrentUserInfo().IsSuperUser)) @@ -131,7 +131,7 @@ protected override void OnLoad(EventArgs e) { this._objPortal = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); } - + if (!this.Page.IsPostBack) { // save persistent values @@ -170,7 +170,7 @@ protected override void OnLoad(EventArgs e) this.optSite.Checked = true; } } - + this.LoadSkins(); } } @@ -184,7 +184,32 @@ protected void optHost_CheckedChanged(object sender, EventArgs e) { this.LoadSkins(); } - + + protected void optSite_CheckedChanged(object sender, EventArgs e) + { + this.LoadSkins(); + } + + protected void cmdPreview_Click(object sender, EventArgs e) + { + if (!string.IsNullOrEmpty(this.SkinSrc)) + { + string strType = this.SkinRoot.Substring(0, this.SkinRoot.Length - 1); + + string strURL = Globals.ApplicationURL() + "&" + strType + "Src=" + Globals.QueryStringEncode(this.SkinSrc.Replace(".ascx", string.Empty)); + + if (this.SkinRoot == SkinController.RootContainer) + { + if (this.Request.QueryString["ModuleId"] != null) + { + strURL += "&ModuleId=" + this.Request.QueryString["ModuleId"]; + } + } + + this.Response.Redirect(strURL, true); + } + } + private void LoadSkins() { this.cboSkin.Items.Clear(); @@ -208,7 +233,7 @@ private void LoadSkins() } 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++) { @@ -218,31 +243,6 @@ private void LoadSkins() break; } } - } - - protected void optSite_CheckedChanged(object sender, EventArgs e) - { - this.LoadSkins(); } - - protected void cmdPreview_Click(object sender, EventArgs e) - { - if (!string.IsNullOrEmpty(this.SkinSrc)) - { - string strType = this.SkinRoot.Substring(0, this.SkinRoot.Length - 1); - - string strURL = Globals.ApplicationURL() + "&" + strType + "Src=" + Globals.QueryStringEncode(this.SkinSrc.Replace(".ascx", string.Empty)); - - if (this.SkinRoot == SkinController.RootContainer) - { - if (this.Request.QueryString["ModuleId"] != null) - { - strURL += "&ModuleId=" + this.Request.QueryString["ModuleId"]; - } - } - - this.Response.Redirect(strURL, true); - } - } } } diff --git a/DNN Platform/Library/UI/Skins/SkinController.cs b/DNN Platform/Library/UI/Skins/SkinController.cs index 70fb637fcd1..270015cdaae 100644 --- a/DNN Platform/Library/UI/Skins/SkinController.cs +++ b/DNN Platform/Library/UI/Skins/SkinController.cs @@ -37,12 +37,12 @@ public class 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 ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinController)); private static readonly Regex GdirRegex = new Regex("\\[g]", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly Regex SdirRegex = new Regex("\\[s]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex LdirRegex = new Regex("\\[l]", RegexOptions.IgnoreCase | RegexOptions.Compiled); - + private static readonly Regex LdirRegex = new Regex("\\[l]", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static string RootSkin { get @@ -57,8 +57,8 @@ public static string RootContainer { return "Containers"; } - } - + } + public static int AddSkin(int skinPackageID, string skinSrc) { return DataProvider.Instance().AddSkin(skinPackageID, skinSrc); @@ -69,62 +69,6 @@ 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")) - { - string folder = skinFolder.Substring(skinFolder.LastIndexOf("\\") + 1); - - string key = (skinPrefix == PortalSystemSkinPrefix || skinPrefix == PortalSkinPrefix ? "Site: " : "Host: ") - + FormatSkinName(folder, Path.GetFileNameWithoutExtension(skinFile)); - string value = skinPrefix + skinRoot + "/" + folder + "/" + Path.GetFileName(skinFile); - skins.Add(new KeyValuePair(key, value)); - } - } - - private static List> GetHostSkins(string skinRoot) - { - var skins = new List>(); - - string root = Globals.HostMapPath + skinRoot; - if (Directory.Exists(root)) - { - foreach (string skinFolder in Directory.GetDirectories(root)) - { - if (!skinFolder.EndsWith(Globals.glbHostSkinFolder)) - { - AddSkinFiles(skins, skinRoot, skinFolder, GlobalSkinPrefix); - } - } - } - - return skins; - } - - private static List> GetPortalSkins(PortalInfo portalInfo, string skinRoot) - { - var skins = new List>(); - - if (portalInfo != null) - { - ProcessSkinsFolder(skins, portalInfo.HomeSystemDirectoryMapPath + skinRoot, skinRoot, PortalSystemSkinPrefix); - ProcessSkinsFolder(skins, portalInfo.HomeDirectoryMapPath + skinRoot, skinRoot, PortalSkinPrefix); // to be compliant with all versions - } - - return skins; - } - - private static void ProcessSkinsFolder(List> skins, string skinsFolder, string skinRoot, string skinPrefix) - { - if (Directory.Exists(skinsFolder)) - { - foreach (string skinFolder in Directory.GetDirectories(skinsFolder)) - { - AddSkinFiles(skins, skinRoot, skinFolder, skinPrefix); - } - } - } public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) { @@ -146,7 +90,7 @@ public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) skinType = "L"; skinFolder = folderPath.ToLowerInvariant().Replace(portalHomeDirMapPath.ToLowerInvariant(), string.Empty).Replace("\\", "/"); } - + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); string skin = "[" + skinType.ToLowerInvariant() + "]" + skinFolder.ToLowerInvariant(); @@ -166,13 +110,13 @@ public static bool CanDeleteSkin(string folderPath, string portalHomeDirMapPath) canDelete = false; } } - + if (canDelete) { // Check if used for Tabs or Modules canDelete = DataProvider.Instance().CanDeleteSkin(skinType, skinFolder); } - + return canDelete; } @@ -194,7 +138,7 @@ public static string FormatMessage(string title, string body, int level, bool is { message = "" + title + ""; } - + switch (level) { case -1: @@ -210,7 +154,7 @@ public static string FormatMessage(string title, string body, int level, bool is message = "
  • " + message + "
  • "; break; } - + return message + ": " + body + Environment.NewLine; } @@ -221,7 +165,7 @@ public static string FormatSkinPath(string skinSrc) { strSkinSrc = strSkinSrc.Substring(0, strSkinSrc.LastIndexOf("/") + 1); } - + return strSkinSrc; } @@ -243,7 +187,7 @@ public static string FormatSkinSrc(string skinSrc, PortalSettings portalSettings break; } } - + return strSkinSrc; } @@ -297,7 +241,7 @@ public static List> GetSkins(PortalInfo portalInfo, skins.AddRange(GetPortalSkins(portalInfo, skinRoot)); break; } - + return skins; } @@ -314,7 +258,7 @@ public static bool IsGlobalSkin(string skinSrc) { return skinSrc.Contains(Globals.HostPath); } - + public static void SetSkin(string skinRoot, int portalId, SkinType skinType, string skinSrc) { var selectedCultureCode = LocaleController.Instance.GetCurrentLocale(portalId).Code; @@ -343,7 +287,7 @@ public static void SetSkin(string skinRoot, int portalId, SkinType skinType, str PortalController.UpdatePortalSetting(portalId, "DefaultPortalSkin", skinSrc, true, selectedCultureCode); } } - + break; case "Containers": if (skinType == SkinType.Admin) @@ -368,36 +312,8 @@ public static void SetSkin(string skinRoot, int portalId, SkinType skinType, str PortalController.UpdatePortalSetting(portalId, "DefaultPortalContainer", skinSrc, true, selectedCultureCode); } } - - break; - } - } - /// ----------------------------------------------------------------------------- - /// - /// 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; + break; } } @@ -408,7 +324,7 @@ public static void UpdateSkin(int skinID, string skinSrc) public static void UpdateSkinPackage(SkinPackageInfo skinPackage) { - DataProvider.Instance().UpdateSkinPackage( + DataProvider.Instance().UpdateSkinPackage( skinPackage.SkinPackageID, skinPackage.PackageID, skinPackage.PortalID, @@ -468,7 +384,7 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } - + objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream); } @@ -483,7 +399,7 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } - + objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream); } @@ -517,7 +433,7 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s objFileStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } - + objFileStream.Close(); // save the skin file @@ -531,10 +447,10 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s { arrSkinFiles.Add(strFileName); } - + break; } - + break; } } @@ -543,10 +459,10 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s strMessage += string.Format(FILE_RESTICTED, objZipEntry.Name, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true"); } } - + objZipEntry = objZipInputStream.GetNextEntry(); } - + strMessage += FormatMessage(END_MESSAGE, skinName + ".zip", 1, false); objZipInputStream.Close(); @@ -564,15 +480,99 @@ public static string UploadLegacySkin(string rootPath, string skinRoot, string s { log.LogProperties.Add(new LogDetailInfo("Info:", HtmlUtils.StripTags(strRow, true))); } - + LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); } - + return strMessage; - } + } + + private static void AddSkinFiles(List> skins, string skinRoot, string skinFolder, string skinPrefix) + { + foreach (string skinFile in Directory.GetFiles(skinFolder, "*.ascx")) + { + string folder = skinFolder.Substring(skinFolder.LastIndexOf("\\") + 1); + + string key = (skinPrefix == PortalSystemSkinPrefix || skinPrefix == PortalSkinPrefix ? "Site: " : "Host: ") + + FormatSkinName(folder, Path.GetFileNameWithoutExtension(skinFile)); + string value = skinPrefix + skinRoot + "/" + folder + "/" + Path.GetFileName(skinFile); + skins.Add(new KeyValuePair(key, value)); + } + } + + private static List> GetHostSkins(string skinRoot) + { + var skins = new List>(); + + string root = Globals.HostMapPath + skinRoot; + if (Directory.Exists(root)) + { + foreach (string skinFolder in Directory.GetDirectories(root)) + { + if (!skinFolder.EndsWith(Globals.glbHostSkinFolder)) + { + AddSkinFiles(skins, skinRoot, skinFolder, GlobalSkinPrefix); + } + } + } + + return skins; + } + + private static List> GetPortalSkins(PortalInfo portalInfo, string skinRoot) + { + var skins = new List>(); + + if (portalInfo != null) + { + ProcessSkinsFolder(skins, portalInfo.HomeSystemDirectoryMapPath + skinRoot, skinRoot, PortalSystemSkinPrefix); + ProcessSkinsFolder(skins, portalInfo.HomeDirectoryMapPath + skinRoot, skinRoot, PortalSkinPrefix); // to be compliant with all versions + } + + return skins; + } + + private static void ProcessSkinsFolder(List> skins, string skinsFolder, string skinRoot, string skinPrefix) + { + if (Directory.Exists(skinsFolder)) + { + foreach (string skinFolder in Directory.GetDirectories(skinsFolder)) + { + AddSkinFiles(skins, skinRoot, skinFolder, skinPrefix); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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; + } + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinDefaults.cs b/DNN Platform/Library/UI/Skins/SkinDefaults.cs index 1661610fe44..041ff2ea5e0 100644 --- a/DNN Platform/Library/UI/Skins/SkinDefaults.cs +++ b/DNN Platform/Library/UI/Skins/SkinDefaults.cs @@ -39,7 +39,7 @@ public string AdminDefaultName { return this._adminDefaultName; } - + set { this._adminDefaultName = value; @@ -52,7 +52,7 @@ public string DefaultName { return this._defaultName; } - + set { this._defaultName = value; @@ -65,7 +65,7 @@ public string Folder { return this._folder; } - + set { this._folder = value; diff --git a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs index 3b69d0630b8..ca4150002f0 100644 --- a/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs +++ b/DNN Platform/Library/UI/Skins/SkinFileProcessor.cs @@ -35,7 +35,7 @@ public enum SkinParser /// ----------------------------------------------------------------------------- public class SkinFileProcessor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinFileProcessor)); + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinFileProcessor)); private readonly string DUPLICATE_DETAIL = Util.GetLocalizedString("DuplicateSkinObject.Detail"); private readonly string DUPLICATE_ERROR = Util.GetLocalizedString("DuplicateSkinObject.Error"); private readonly string FILES_END = Util.GetLocalizedString("EndSkinFiles"); @@ -53,10 +53,10 @@ public class SkinFileProcessor private readonly string m_SkinName; private readonly string m_SkinPath; private readonly string m_SkinRoot; - private string m_Message = string.Empty; - + private string m_Message = string.Empty; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// SkinFileProcessor class constructor. /// @@ -73,10 +73,10 @@ public SkinFileProcessor(string ControlKey, string ControlSrc) // Instantiate the object parser with the list of skin objects this.m_ObjectFactory = new ObjectParser(this.m_ControlList); - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// SkinFileProcessor class constructor. /// @@ -129,7 +129,7 @@ public SkinFileProcessor(string SkinPath, string SkinRoot, string SkinName) // If the control is already in the hash table if (this.m_ControlList.ContainsKey(Token)) { - this.Message += SkinController.FormatMessage( + this.Message += SkinController.FormatMessage( string.Format(this.DUPLICATE_ERROR, Token), string.Format(this.DUPLICATE_DETAIL, this.m_ControlList[Token], objSkinControl.ControlSrc), 2, @@ -148,8 +148,8 @@ public SkinFileProcessor(string SkinPath, string SkinRoot, string SkinName) // Instantiate the object parser with the list of skin objects this.m_ObjectFactory = new ObjectParser(this.m_ControlList); - } - + } + public string SkinRoot { get @@ -165,7 +165,15 @@ public string SkinPath return this.m_SkinPath; } } - + + public string SkinName + { + get + { + return this.m_SkinName; + } + } + private PathParser PathFactory { get @@ -204,21 +212,13 @@ private string Message { return this.m_Message; } - + set { this.m_Message = value; } - } + } - public string SkinName - { - get - { - return this.m_SkinName; - } - } - public string ProcessFile(string FileName, SkinParser ParseOption) { string strMessage = SkinController.FormatMessage(this.FILE_BEGIN, Path.GetFileName(FileName), 0, false); @@ -238,7 +238,7 @@ public string ProcessFile(string FileName, SkinParser ParseOption) strMessage += objSkinFile.PrependASCXDirectives(Registrations); break; } - + objSkinFile.Write(); strMessage += objSkinFile.Messages; strMessage += SkinController.FormatMessage(this.FILE_END, Path.GetFileName(FileName), 1, false); @@ -265,7 +265,7 @@ public string ProcessList(ArrayList FileList, SkinParser ParseOption) { this.Message += this.ProcessFile(FileName, ParseOption); } - + this.Message += SkinController.FormatMessage(this.FILES_END, this.SkinRoot + " :: " + this.SkinName, 0, false); return this.Message; } @@ -277,8 +277,8 @@ public string ProcessSkin(string SkinSource, XmlDocument SkinAttributes, SkinPar this.Message += this.ControlFactory.Parse(ref contents, objSkinFile.Attributes); this.Message += objSkinFile.PrependASCXDirectives(this.ControlFactory.Registrations); return contents; - } - + } + /// ----------------------------------------------------------------------------- /// Project : DotNetNuke /// Class : SkinFileProcessor.ControlParser @@ -301,15 +301,15 @@ 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); - + 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(); - + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// ControlParser class constructor. /// @@ -353,24 +353,24 @@ private MatchEvaluator Handler } } - private ArrayList RegisterList + private Hashtable ControlList { get { - return this.m_RegisterList; - } - - set - { - this.m_RegisterList = value; + return this.m_ControlList; } } - private Hashtable ControlList + private ArrayList RegisterList { get { - return this.m_ControlList; + return this.m_RegisterList; + } + + set + { + this.m_RegisterList = value; } } @@ -380,7 +380,7 @@ private XmlDocument Attributes { return this.m_Attributes; } - + set { this.m_Attributes = value; @@ -393,7 +393,7 @@ private string Messages { return this.m_ParseMessages; } - + set { this.m_ParseMessages = value; @@ -415,10 +415,10 @@ private string Messages public string Parse(ref string Source, XmlDocument Attributes) { this.Messages = string.Empty; - + // set the token attributes this.Attributes = Attributes; - + // clear register list this.RegisterList.Clear(); @@ -482,19 +482,19 @@ private string TokenMatchHandler(Match m) { // look for the the node of this instance of the token XmlNode xmlSkinAttributeRoot = this.Attributes.DocumentElement.SelectSingleNode("descendant::Object[Token='[" + AttributeNode + "]']"); - + // if the token is found if (xmlSkinAttributeRoot != null) { this.Messages += SkinController.FormatMessage(TOKEN_FOUND, "[" + AttributeNode + "]", 2, false); - + // process each token attribute foreach (XmlNode xmlSkinAttribute in xmlSkinAttributeRoot.SelectNodes(".//Settings/Setting")) { if (!string.IsNullOrEmpty(xmlSkinAttribute.SelectSingleNode("Value").InnerText)) { // append the formatted attribute to the inner contents of the control statement - this.Messages += SkinController.FormatMessage( + this.Messages += SkinController.FormatMessage( TOKEN_FORMAT, xmlSkinAttribute.SelectSingleNode("Name").InnerText + "=\"" + xmlSkinAttribute.SelectSingleNode("Value").InnerText + "\"", 2, @@ -509,7 +509,7 @@ private string TokenMatchHandler(Match m) this.Messages += SkinController.FormatMessage(TOKEN_NOTFOUND_INFILE, "[" + AttributeNode + "]", 2, false); } } - + if (this.ControlList.ContainsKey(Token)) { // create the skin object user control tag @@ -533,7 +533,7 @@ private string TokenMatchHandler(Match m) { SkinControl = " id=\"ContentPane\""; } - + SkinControl = "div runat=\"server\"" + SkinControl + ">"; } - + return SkinControl; } else @@ -553,8 +553,8 @@ private string TokenMatchHandler(Match m) return "[" + m.Groups["token"].Value + "]"; } } - } - + } + /// ----------------------------------------------------------------------------- /// Project : DotNetNuke /// Class : SkinFileProcessor.ObjectParser @@ -580,14 +580,14 @@ private class ObjectParser private static readonly Regex FindObjectInstance = new Regex("\\.*?)
    ", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - private static readonly Regex MultiSpaceRegex = new Regex("\\s+", 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. /// ControlParser class constructor. /// @@ -631,24 +631,24 @@ private MatchEvaluator Handler } } - private ArrayList RegisterList + private Hashtable ControlList { get { - return this.m_RegisterList; - } - - set - { - this.m_RegisterList = value; + return this.m_ControlList; } } - private Hashtable ControlList + private ArrayList RegisterList { get { - return this.m_ControlList; + return this.m_RegisterList; + } + + set + { + this.m_RegisterList = value; } } @@ -658,7 +658,7 @@ private string Messages { return this.m_ParseMessages; } - + set { this.m_ParseMessages = value; @@ -787,7 +787,7 @@ private string ObjectMatchHandler(Match m) { SkinControl += "id=\"" + ControlName + "\" "; } - + SkinControl += Parameters; // save control registration statement @@ -812,14 +812,14 @@ private string ObjectMatchHandler(Match m) { SkinControl += "id=\"ContentPane\" "; } - + SkinControl += Parameters + ">"; } - + return SkinControl; } else @@ -835,8 +835,8 @@ private string ObjectMatchHandler(Match m) return ""; } } - } - + } + /// ----------------------------------------------------------------------------- /// Project : DotNetNuke /// Class : SkinFileProcessor.PathParser @@ -870,7 +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), }; - + + // retrieve the patterns + private static readonly Regex[] CssArrayPattern = + { + new Regex("(?\\surl\\u0028)(?[^\\u0029]*)(?\\u0029.*;)", PatternOptions), + }; + private readonly string SUBST = Util.GetLocalizedString("Substituting"); private readonly string SUBST_DETAIL = Util.GetLocalizedString("Substituting.Detail"); private readonly ArrayList m_CSSPatterns = new ArrayList(); @@ -878,12 +884,6 @@ private class PathParser private string m_Messages = string.Empty; private string m_SkinPath = string.Empty; - // retrieve the patterns - private static readonly Regex[] CssArrayPattern = - { - new Regex("(?\\surl\\u0028)(?[^\\u0029]*)(?\\u0029.*;)", PatternOptions), - }; - /// ----------------------------------------------------------------------------- /// /// Gets list of regular expressions for processing HTML syntax. @@ -909,7 +909,7 @@ public ArrayList HTMLList // optimize the arraylist size since it will not change this.m_HTMLPatterns.TrimToSize(); } - + return this.m_HTMLPatterns; } } @@ -939,7 +939,7 @@ public ArrayList CSSList // optimize the arraylist size since it will not change this.m_CSSPatterns.TrimToSize(); } - + return this.m_CSSPatterns; } } @@ -958,7 +958,7 @@ private string SkinPath { return this.m_SkinPath; } - + set { this.m_SkinPath = value; @@ -986,7 +986,7 @@ public string Parse(ref string Source, ArrayList RegexList, string SkinPath, Ski // set path propery which is file specific this.SkinPath = SkinPath; - + // set parse option this.ParseOption = ParseOption; @@ -995,7 +995,7 @@ public string Parse(ref string Source, ArrayList RegexList, string SkinPath, Ski { Source = ((Regex)RegexList[i]).Replace(Source, this.Handler); } - + return this.m_Messages; } @@ -1029,7 +1029,7 @@ private string MatchHandler(Match m) // insert the localized path strNewTag = m.Groups["tag"].Value + this.SkinPath + m.Groups["content"].Value + m.Groups["endtag"].Value; } - + break; case SkinParser.Portable: // if the tag does not contain a reference to the skinpath @@ -1045,16 +1045,16 @@ private string MatchHandler(Match m) // remove the localized path strNewTag = strNewTag.Replace(this.SkinPath, string.Empty); } - + break; } } - + this.m_Messages += SkinController.FormatMessage(this.SUBST, string.Format(this.SUBST_DETAIL, HttpUtility.HtmlEncode(strOldTag), HttpUtility.HtmlEncode(strNewTag)), 2, false); return strNewTag; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Utility class for processing of skin files. @@ -1065,10 +1065,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 static readonly Regex BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | 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"); @@ -1083,10 +1084,9 @@ 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 BodyExtractionRegex = new Regex(StrPattern, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled); - + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// SkinFile class constructor. /// @@ -1102,10 +1102,10 @@ public SkinFile(string SkinContents, XmlDocument SkinAttributes) { this.m_FileAttributes = SkinAttributes; this.Contents = SkinContents; - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// SkinFile class constructor. /// @@ -1163,7 +1163,7 @@ public SkinFile(string SkinRoot, string FileName, XmlDocument SkinAttributes) this.m_Messages += SkinController.FormatMessage(this.FILE_LOAD_ERROR, FileName, 2, true); } } - + break; default: // output file name is same as input file name @@ -1237,7 +1237,7 @@ public void Write() { File.Delete(this.WriteFileName); } - + this.m_Messages += SkinController.FormatMessage(this.FILE_WRITE, Path.GetFileName(this.WriteFileName), 2, false); using (var objStreamWriter = new StreamWriter(this.WriteFileName)) { @@ -1269,7 +1269,7 @@ public string PrependASCXDirectives(ArrayList Registrations) // if the skin source is an HTML document, extract the content within the tags this.Contents = objMatch.Groups[1].Value; } - + if (this.SkinRoot == SkinController.RootSkin) { Prefix += "<%@ Control language=\"vb\" AutoEventWireup=\"false\" Explicit=\"True\" Inherits=\"DotNetNuke.UI.Skins.Skin\" %>" + Environment.NewLine; @@ -1278,7 +1278,7 @@ public string PrependASCXDirectives(ArrayList Registrations) { Prefix += "<%@ Control language=\"vb\" AutoEventWireup=\"false\" Explicit=\"True\" Inherits=\"DotNetNuke.UI.Containers.Container\" %>" + Environment.NewLine; } - + Messages += SkinController.FormatMessage(this.CONTROL_DIR, HttpUtility.HtmlEncode(Prefix), 2, false); // add preformatted Control Registrations @@ -1302,6 +1302,6 @@ private string Read(string FileName) return strFileContents; } } - } + } } } diff --git a/DNN Platform/Library/UI/Skins/SkinInfo.cs b/DNN Platform/Library/UI/Skins/SkinInfo.cs index 65091e6dc8e..2360575ed0b 100644 --- a/DNN Platform/Library/UI/Skins/SkinInfo.cs +++ b/DNN Platform/Library/UI/Skins/SkinInfo.cs @@ -31,7 +31,7 @@ public int SkinId { return this._SkinId; } - + set { this._SkinId = value; @@ -44,7 +44,7 @@ public int PortalId { return this._PortalId; } - + set { this._PortalId = value; @@ -57,7 +57,7 @@ public string SkinRoot { return this._SkinRoot; } - + set { this._SkinRoot = value; @@ -70,7 +70,7 @@ public SkinType SkinType { return this._SkinType; } - + set { this._SkinType = value; @@ -83,7 +83,7 @@ public string SkinSrc { return this._SkinSrc; } - + set { this._SkinSrc = value; diff --git a/DNN Platform/Library/UI/Skins/SkinObjectBase.cs b/DNN Platform/Library/UI/Skins/SkinObjectBase.cs index b2a3ee85e04..67129d4e8b4 100644 --- a/DNN Platform/Library/UI/Skins/SkinObjectBase.cs +++ b/DNN Platform/Library/UI/Skins/SkinObjectBase.cs @@ -23,7 +23,7 @@ public class SkinObjectBase : UserControl, ISkinControl /// Gets the portal Settings for this Skin Control. /// /// ----------------------------------------------------------------------------- - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { @@ -44,13 +44,13 @@ public bool AdminMode { return TabPermissionController.CanAdminPage(); } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the associated ModuleControl for this SkinControl. /// /// ----------------------------------------------------------------------------- - public IModuleControl ModuleControl { get; set; } + public IModuleControl ModuleControl { get; set; } } } diff --git a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs index 9d096cf05c8..3772f4ec347 100644 --- a/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs +++ b/DNN Platform/Library/UI/Skins/SkinPackageInfo.cs @@ -25,21 +25,21 @@ namespace DotNetNuke.UI.Skins /// ----------------------------------------------------------------------------- [Serializable] public class SkinPackageInfo : BaseEntityInfo, IHydratable - { + { private int _PackageID = Null.NullInteger; private int _PortalID = Null.NullInteger; private string _SkinName; private int _SkinPackageID = Null.NullInteger; private string _SkinType; - private Dictionary _Skins = new Dictionary(); - + private Dictionary _Skins = new Dictionary(); + public int PackageID { get { return this._PackageID; } - + set { this._PackageID = value; @@ -52,7 +52,7 @@ public int SkinPackageID { return this._SkinPackageID; } - + set { this._SkinPackageID = value; @@ -65,7 +65,7 @@ public int PortalID { return this._PortalID; } - + set { this._PortalID = value; @@ -78,7 +78,7 @@ public string SkinName { return this._SkinName; } - + set { this._SkinName = value; @@ -92,7 +92,7 @@ public Dictionary Skins { return this._Skins; } - + set { this._Skins = value; @@ -105,12 +105,12 @@ public string SkinType { return this._SkinType; } - + set { this._SkinType = value; } - } + } public int KeyID { @@ -118,20 +118,20 @@ public int KeyID { return this.SkinPackageID; } - + set { this.SkinPackageID = value; } - } - + } + public void Fill(IDataReader dr) { this.SkinPackageID = Null.SetNullInteger(dr["SkinPackageID"]); this.PackageID = Null.SetNullInteger(dr["PackageID"]); this.SkinName = Null.SetNullString(dr["SkinName"]); this.SkinType = Null.SetNullString(dr["SkinType"]); - + // Call the base classes fill method to populate base class proeprties this.FillInternal(dr); diff --git a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs index 21fb4c7b69d..6be6db52379 100644 --- a/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs +++ b/DNN Platform/Library/UI/Skins/SkinThumbNailControl.cs @@ -26,16 +26,16 @@ namespace DotNetNuke.UI.Skins public abstract class SkinThumbNailControl : UserControlBase { protected HtmlGenericControl ControlContainer; - protected RadioButtonList OptSkin; - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinThumbNailControl)); - + protected RadioButtonList OptSkin; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinThumbNailControl)); + public string Border { get { return Convert.ToString(this.ViewState["SkinControlBorder"]); } - + set { this.ViewState["SkinControlBorder"] = value; @@ -55,7 +55,7 @@ public int Columns { return Convert.ToInt32(this.ViewState["SkinControlColumns"]); } - + set { this.ViewState["SkinControlColumns"] = value; @@ -72,7 +72,7 @@ public string Height { return Convert.ToString(this.ViewState["SkinControlHeight"]); } - + set { this.ViewState["SkinControlHeight"] = value; @@ -89,7 +89,7 @@ public string SkinRoot { return Convert.ToString(this.ViewState["SkinRoot"]); } - + set { this.ViewState["SkinRoot"] = value; @@ -102,7 +102,7 @@ public string SkinSrc { return this.OptSkin.SelectedItem != null ? this.OptSkin.SelectedItem.Value : string.Empty; } - + set { // select current skin @@ -124,7 +124,7 @@ public string Width { return Convert.ToString(this.ViewState["SkinControlWidth"]); } - + set { this.ViewState["SkinControlWidth"] = value; @@ -133,8 +133,8 @@ public string Width this.ControlContainer.Style.Add("width", value); } } - } - + } + /// ----------------------------------------------------------------------------- /// /// Clear clears the radio button list. @@ -170,6 +170,95 @@ public void LoadAllSkins(bool includeNotSpecified) this.LoadPortalSkins(false); } + /// ----------------------------------------------------------------------------- + /// + /// LoadHostSkins loads all the available Host skins to the radio button list. + /// + /// + /// + /// Optionally include the "Not Specified" option. + /// ----------------------------------------------------------------------------- + public void LoadHostSkins(bool includeNotSpecified) + { + // default value + if (includeNotSpecified) + { + this.AddDefaultSkin(); + } + + // load host skins + var strRoot = Globals.HostMapPath + this.SkinRoot; + if (Directory.Exists(strRoot)) + { + var arrFolders = Directory.GetDirectories(strRoot); + foreach (var strFolder in arrFolders) + { + if (!strFolder.EndsWith(Globals.glbHostSkinFolder)) + { + this.LoadSkins(strFolder, "[G]", false); + } + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// LoadHostSkins loads all the available Site/Portal skins to the radio button list. + /// + /// + /// + /// Optionally include the "Not Specified" option. + /// ----------------------------------------------------------------------------- + public void LoadPortalSkins(bool includeNotSpecified) + { + // default value + if (includeNotSpecified) + { + this.AddDefaultSkin(); + } + + // load portal skins + var strRoot = this.PortalSettings.HomeDirectoryMapPath + this.SkinRoot; + if (Directory.Exists(strRoot)) + { + var arrFolders = Directory.GetDirectories(strRoot); + foreach (var strFolder in arrFolders) + { + this.LoadSkins(strFolder, "[L]", false); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// LoadSkins loads all the available skins in a specific folder to the radio button list. + /// + /// + /// + /// The folder to search for skins. + /// A string that identifies whether the skin is Host "[G]" or Site "[L]". + /// Optionally include the "Not Specified" option. + /// ----------------------------------------------------------------------------- + public void LoadSkins(string strFolder, string skinType, bool includeNotSpecified) + { + // default value + if (includeNotSpecified) + { + this.AddDefaultSkin(); + } + + if (Directory.Exists(strFolder)) + { + var arrFiles = Directory.GetFiles(strFolder, "*.ascx"); + strFolder = strFolder.Substring(strFolder.LastIndexOf("\\") + 1); + + foreach (var strFile in arrFiles) + { + this.AddSkin(skinType + this.SkinRoot, strFolder, strFile); + } + } + } + /// ----------------------------------------------------------------------------- /// /// format skin name. @@ -221,7 +310,7 @@ private static string CreateThumbnail(string strImage) blnCreate = false; } } - + if (blnCreate) { const int intSize = 140; // size of the thumbnail @@ -274,11 +363,11 @@ private static string CreateThumbnail(string strImage) Logger.Error(ex); } } - + strThumbnail = Globals.ApplicationPath + "\\" + strThumbnail.Substring(strThumbnail.IndexOf("portals\\", StringComparison.InvariantCultureIgnoreCase)); return strThumbnail; - } - + } + /// ----------------------------------------------------------------------------- /// /// AddDefaultSkin adds the not-specified skin to the radio button list. @@ -315,97 +404,8 @@ private void AddSkin(string root, string strFolder, string strFile) { strImage += ""; } - - this.OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
    " + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); - } - /// ----------------------------------------------------------------------------- - /// - /// LoadHostSkins loads all the available Host skins to the radio button list. - /// - /// - /// - /// Optionally include the "Not Specified" option. - /// ----------------------------------------------------------------------------- - public void LoadHostSkins(bool includeNotSpecified) - { - // default value - if (includeNotSpecified) - { - this.AddDefaultSkin(); - } - - // load host skins - var strRoot = Globals.HostMapPath + this.SkinRoot; - if (Directory.Exists(strRoot)) - { - var arrFolders = Directory.GetDirectories(strRoot); - foreach (var strFolder in arrFolders) - { - if (!strFolder.EndsWith(Globals.glbHostSkinFolder)) - { - this.LoadSkins(strFolder, "[G]", false); - } - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// LoadHostSkins loads all the available Site/Portal skins to the radio button list. - /// - /// - /// - /// Optionally include the "Not Specified" option. - /// ----------------------------------------------------------------------------- - public void LoadPortalSkins(bool includeNotSpecified) - { - // default value - if (includeNotSpecified) - { - this.AddDefaultSkin(); - } - - // load portal skins - var strRoot = this.PortalSettings.HomeDirectoryMapPath + this.SkinRoot; - if (Directory.Exists(strRoot)) - { - var arrFolders = Directory.GetDirectories(strRoot); - foreach (var strFolder in arrFolders) - { - this.LoadSkins(strFolder, "[L]", false); - } - } + this.OptSkin.Items.Add(new ListItem(FormatSkinName(strFolder, Path.GetFileNameWithoutExtension(strFile)) + "
    " + strImage, root + "/" + strFolder + "/" + Path.GetFileName(strFile))); } - - /// ----------------------------------------------------------------------------- - /// - /// LoadSkins loads all the available skins in a specific folder to the radio button list. - /// - /// - /// - /// The folder to search for skins. - /// A string that identifies whether the skin is Host "[G]" or Site "[L]". - /// Optionally include the "Not Specified" option. - /// ----------------------------------------------------------------------------- - public void LoadSkins(string strFolder, string skinType, bool includeNotSpecified) - { - // default value - if (includeNotSpecified) - { - this.AddDefaultSkin(); - } - - if (Directory.Exists(strFolder)) - { - var arrFiles = Directory.GetFiles(strFolder, "*.ascx"); - strFolder = strFolder.Substring(strFolder.LastIndexOf("\\") + 1); - - foreach (var strFile in arrFiles) - { - this.AddSkin(skinType + this.SkinRoot, strFolder, strFile); - } - } - } } } diff --git a/DNN Platform/Library/UI/UIUtilities.cs b/DNN Platform/Library/UI/UIUtilities.cs index 26e38c7ce95..0898e65942a 100644 --- a/DNN Platform/Library/UI/UIUtilities.cs +++ b/DNN Platform/Library/UI/UIUtilities.cs @@ -65,7 +65,15 @@ public static bool IsLegacyUI(int moduleId, string key, int portalId) return isLegacyUi; } - + + public static bool IsLegacyUI(int portalId) + { + var key = GetControlKey(); + var moduleId = GetModuleId(key); + + return IsLegacyUI(moduleId, key, portalId); + } + internal static string GetControlKey() { HttpRequest request = HttpContext.Current.Request; @@ -75,7 +83,7 @@ internal static string GetControlKey() { key = request.QueryString["ctl"]; } - + return key; } @@ -88,7 +96,7 @@ internal static int GetModuleId(string key) { int.TryParse(request.QueryString["mid"], out moduleId); } - + if (request.QueryString["moduleid"] != null && (key.Equals("module", StringComparison.InvariantCultureIgnoreCase) || key.Equals("help", StringComparison.InvariantCultureIgnoreCase))) { int.TryParse(request.QueryString["moduleid"], out moduleId); @@ -106,7 +114,7 @@ internal static string GetRenderMode() { renderMode = request.QueryString["render"]; } - + return renderMode; } @@ -153,14 +161,6 @@ internal static ModuleInfo GetSlaveModule(int moduleId, string key, int tabId) return slaveModule; } - public static bool IsLegacyUI(int portalId) - { - var key = GetControlKey(); - var moduleId = GetModuleId(key); - - return IsLegacyUI(moduleId, key, portalId); - } - internal static string GetLocalResourceFile(Control ctrl) { string resourceFileName = Null.NullString; diff --git a/DNN Platform/Library/UI/UserControls/Address.cs b/DNN Platform/Library/UI/UserControls/Address.cs index a154c898837..a3702cdeccf 100644 --- a/DNN Platform/Library/UI/UserControls/Address.cs +++ b/DNN Platform/Library/UI/UserControls/Address.cs @@ -22,33 +22,10 @@ namespace DotNetNuke.UI.UserControls /// /// public abstract class Address : UserControlBase - { + { + private const string MyFileName = "Address.ascx"; protected CountryListBox cboCountry; protected DropDownList cboRegion; - private const string MyFileName = "Address.ascx"; - private string _cell; - private string _city; - private string _controlColumnWidth = string.Empty; - private string _country; - private string _countryData = "Text"; - private string _fax; - private string _labelColumnWidth = string.Empty; - private int _moduleId; - private string _postal; - private string _region; - private string _regionData = "Text"; - private bool _showCell = true; - private bool _showCity = true; - private bool _showCountry = true; - private bool _showFax = true; - private bool _showPostal = true; - private bool _showRegion = true; - private bool _showStreet = true; - private bool _showTelephone = true; - private bool _showUnit = true; - private string _street; - private string _telephone; - private string _unit; protected CheckBox chkCell; protected CheckBox chkCity; protected CheckBox chkCountry; @@ -91,20 +68,51 @@ public abstract class Address : UserControlBase protected RequiredFieldValidator valRegion1; protected RequiredFieldValidator valRegion2; protected RequiredFieldValidator valStreet; - protected RequiredFieldValidator valTelephone; - + protected RequiredFieldValidator valTelephone; + private string _cell; + private string _city; + private string _controlColumnWidth = string.Empty; + private string _country; + private string _countryData = "Text"; + private string _fax; + private string _labelColumnWidth = string.Empty; + private int _moduleId; + private string _postal; + private string _region; + private string _regionData = "Text"; + private bool _showCell = true; + private bool _showCity = true; + private bool _showCountry = true; + private bool _showFax = true; + private bool _showPostal = true; + private bool _showRegion = true; + private bool _showStreet = true; + private bool _showTelephone = true; + private bool _showUnit = true; + private string _street; + private string _telephone; + private string _unit; + protected Address() { this.StartTabIndex = 1; - } - + } + + public string LocalResourceFile + { + get + { + return Localization.GetResourceFile(this, MyFileName); + } + } + public int ModuleId { get { return Convert.ToInt32(this.ViewState["ModuleId"]); } - + set { this._moduleId = value; @@ -117,7 +125,7 @@ public string LabelColumnWidth { return Convert.ToString(this.ViewState["LabelColumnWidth"]); } - + set { this._labelColumnWidth = value; @@ -130,7 +138,7 @@ public string ControlColumnWidth { return Convert.ToString(this.ViewState["ControlColumnWidth"]); } - + set { this._controlColumnWidth = value; @@ -145,7 +153,7 @@ public string Street { return this.txtStreet.Text; } - + set { this._street = value; @@ -158,7 +166,7 @@ public string Unit { return this.txtUnit.Text; } - + set { this._unit = value; @@ -171,7 +179,7 @@ public string City { return this.txtCity.Text; } - + set { this._city = value; @@ -195,10 +203,10 @@ public string Country break; } } - + return retValue; } - + set { this._country = value; @@ -221,7 +229,7 @@ public string Region { retValue = this.cboRegion.SelectedItem.Text; } - + break; case "value": retValue = this.cboRegion.SelectedItem.Value; @@ -233,10 +241,10 @@ public string Region { retValue = this.txtRegion.Text; } - + return retValue; } - + set { this._region = value; @@ -249,7 +257,7 @@ public string Postal { return this.txtPostal.Text; } - + set { this._postal = value; @@ -262,7 +270,7 @@ public string Telephone { return this.txtTelephone.Text; } - + set { this._telephone = value; @@ -275,7 +283,7 @@ public string Cell { return this.txtCell.Text; } - + set { this._cell = value; @@ -288,7 +296,7 @@ public string Fax { return this.txtFax.Text; } - + set { this._fax = value; @@ -383,14 +391,6 @@ public string RegionData } } - public string LocalResourceFile - { - get - { - return Localization.GetResourceFile(this, MyFileName); - } - } - /// /// Page_Load runs when the control is loaded. /// @@ -459,7 +459,7 @@ protected override void OnLoad(EventArgs e) this.cboCountry.Items.FindByText(this._country).Selected = true; } } - + break; case "value": if (this.cboCountry.Items.FindByValue(this._country) != null) @@ -467,10 +467,10 @@ protected override void OnLoad(EventArgs e) this.cboCountry.ClearSelection(); this.cboCountry.Items.FindByValue(this._country).Selected = true; } - + break; } - + this.Localize(); if (this.cboRegion.Visible) @@ -489,14 +489,14 @@ protected override void OnLoad(EventArgs e) 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; } } @@ -504,7 +504,7 @@ protected override void OnLoad(EventArgs e) { this.txtRegion.Text = this._region; } - + this.txtStreet.Text = this._street; this.txtUnit.Text = this._unit; this.txtCity.Text = this._city; @@ -534,7 +534,7 @@ protected override void OnLoad(EventArgs e) 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; @@ -559,7 +559,103 @@ protected void OnCountryIndexChanged(object sender, EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + + protected void OnCityCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCountryCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnPostalCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnRegionCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnStreetCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnTelephoneCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnCellCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnFaxCheckChanged(object sender, EventArgs e) + { + try + { + this.UpdateRequiredFields(); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + /// /// Localize correctly sets up the control for US/Canada/Other Countries. /// @@ -569,7 +665,7 @@ private void Localize() { var countryCode = this.cboCountry.SelectedItem.Value; var ctlEntry = new ListController(); - + // listKey in format "Country.US:Region" var listKey = "Country." + countryCode; var entryCollection = ctlEntry.GetListEntryInfoItems("Region", listKey); @@ -584,7 +680,7 @@ private void Localize() this.cboRegion.DataBind(); this.cboRegion.Items.Insert(0, new ListItem("<" + Localization.GetString("Not_Specified", Localization.SharedResourceFile) + ">", string.Empty)); } - + if (countryCode.Equals("us", StringComparison.InvariantCultureIgnoreCase)) { this.valRegion1.Enabled = true; @@ -603,7 +699,7 @@ private void Localize() this.plPostal.Text = Localization.GetString("plPostal", Localization.GetResourceFile(this, MyFileName)); this.plPostal.HelpText = Localization.GetString("plPostal.Help", Localization.GetResourceFile(this, MyFileName)); } - + this.valRegion1.Enabled = true; this.valRegion2.Enabled = false; } @@ -658,7 +754,7 @@ private void ShowRequiredFields() this.valCountry.Enabled = false; this.cboCountry.CssClass = string.Empty; } - + if (reqRegion) { this.chkRegion.Checked = true; @@ -683,7 +779,7 @@ private void ShowRequiredFields() this.txtRegion.CssClass = string.Empty; this.cboRegion.CssClass = string.Empty; } - + if (reqCity) { this.chkCity.Checked = true; @@ -695,7 +791,7 @@ private void ShowRequiredFields() this.valCity.Enabled = false; this.txtCity.CssClass = string.Empty; } - + if (reqStreet) { this.chkStreet.Checked = true; @@ -707,7 +803,7 @@ private void ShowRequiredFields() this.valStreet.Enabled = false; this.txtStreet.CssClass = string.Empty; } - + if (reqPostal) { this.chkPostal.Checked = true; @@ -719,7 +815,7 @@ private void ShowRequiredFields() this.valPostal.Enabled = false; this.txtPostal.CssClass = string.Empty; } - + if (reqTelephone) { this.chkTelephone.Checked = true; @@ -731,7 +827,7 @@ private void ShowRequiredFields() this.valTelephone.Enabled = false; this.txtTelephone.CssClass = string.Empty; } - + if (reqCell) { this.chkCell.Checked = true; @@ -743,7 +839,7 @@ private void ShowRequiredFields() this.valCell.Enabled = false; this.txtCell.CssClass = string.Empty; } - + if (reqFax) { this.chkFax.Checked = true; @@ -769,7 +865,7 @@ private void UpdateRequiredFields() { this.chkRegion.Checked = false; } - + PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressstreet", this.chkStreet.Checked ? string.Empty : "N"); PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscity", this.chkCity.Checked ? string.Empty : "N"); PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addresscountry", this.chkCountry.Checked ? string.Empty : "N"); @@ -780,102 +876,6 @@ private void UpdateRequiredFields() PortalController.UpdatePortalSetting(this.PortalSettings.PortalId, "addressfax", this.chkFax.Checked ? string.Empty : "N"); this.ShowRequiredFields(); - } - - protected void OnCityCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } } - - protected void OnCountryCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnPostalCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnRegionCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnStreetCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnTelephoneCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnCellCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnFaxCheckChanged(object sender, EventArgs e) - { - try - { - this.UpdateRequiredFields(); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } } } diff --git a/DNN Platform/Library/UI/UserControls/DualListControl.cs b/DNN Platform/Library/UI/UserControls/DualListControl.cs index c6d436d0fdc..b286c021659 100644 --- a/DNN Platform/Library/UI/UserControls/DualListControl.cs +++ b/DNN Platform/Library/UI/UserControls/DualListControl.cs @@ -12,11 +12,15 @@ namespace DotNetNuke.UI.UserControls using DotNetNuke.Services.Localization; public abstract class DualListControl : UserControlBase - { + { protected Label Label1; protected Label Label2; protected LinkButton cmdAdd; protected LinkButton cmdAddAll; + protected LinkButton cmdRemove; + protected LinkButton cmdRemoveAll; + protected ListBox lstAssigned; + protected ListBox lstAvailable; private string MyFileName = "DualListControl.ascx"; private ArrayList _Assigned; private ArrayList _Available; @@ -25,18 +29,14 @@ public abstract class DualListControl : UserControlBase private bool _Enabled = true; private string _ListBoxHeight = string.Empty; private string _ListBoxWidth = string.Empty; - protected LinkButton cmdRemove; - protected LinkButton cmdRemoveAll; - protected ListBox lstAssigned; - protected ListBox lstAvailable; - + public string ListBoxWidth { get { return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxWidth"]); } - + set { this._ListBoxWidth = value; @@ -49,7 +49,7 @@ public string ListBoxHeight { return Convert.ToString(this.ViewState[this.ClientID + "_ListBoxHeight"]); } - + set { this._ListBoxHeight = value; @@ -65,10 +65,10 @@ public ArrayList Available { objList.Add(objListItem); } - + return objList; } - + set { this._Available = value; @@ -84,10 +84,10 @@ public ArrayList Assigned { objList.Add(objListItem); } - + return objList; } - + set { this._Assigned = value; @@ -116,8 +116,8 @@ public bool Enabled { this._Enabled = value; } - } - + } + /// The Page_Load server event handler on this page is used to populate the role information for the page. protected override void OnLoad(EventArgs e) { @@ -146,7 +146,7 @@ protected override void OnLoad(EventArgs e) this.lstAvailable.Width = Unit.Parse(this._ListBoxWidth); this.lstAssigned.Width = Unit.Parse(this._ListBoxWidth); } - + if (!string.IsNullOrEmpty(this._ListBoxHeight)) { this.lstAvailable.Height = Unit.Parse(this._ListBoxHeight); @@ -189,7 +189,7 @@ private void cmdAdd_Click(object sender, EventArgs e) { objList.Add(objListItem); } - + foreach (ListItem objListItem in objList) { if (objListItem.Selected) @@ -198,7 +198,7 @@ private void cmdAdd_Click(object sender, EventArgs e) this.lstAssigned.Items.Add(objListItem); } } - + this.lstAvailable.ClearSelection(); this.lstAssigned.ClearSelection(); this.Sort(this.lstAssigned); @@ -211,7 +211,7 @@ private void cmdRemove_Click(object sender, EventArgs e) { objList.Add(objListItem); } - + foreach (ListItem objListItem in objList) { if (objListItem.Selected) @@ -220,7 +220,7 @@ private void cmdRemove_Click(object sender, EventArgs e) this.lstAvailable.Items.Add(objListItem); } } - + this.lstAvailable.ClearSelection(); this.lstAssigned.ClearSelection(); this.Sort(this.lstAvailable); @@ -232,7 +232,7 @@ private void cmdAddAll_Click(object sender, EventArgs e) { this.lstAssigned.Items.Add(objListItem); } - + this.lstAvailable.Items.Clear(); this.lstAvailable.ClearSelection(); this.lstAssigned.ClearSelection(); @@ -245,13 +245,13 @@ private void cmdRemoveAll_Click(object sender, EventArgs e) { this.lstAvailable.Items.Add(objListItem); } - + this.lstAssigned.Items.Clear(); this.lstAvailable.ClearSelection(); this.lstAssigned.ClearSelection(); this.Sort(this.lstAvailable); - } - + } + private void Sort(ListBox ctlListBox) { var arrListItems = new ArrayList(); @@ -259,24 +259,24 @@ private void Sort(ListBox ctlListBox) { arrListItems.Add(objListItem); } - + arrListItems.Sort(new ListItemComparer()); ctlListBox.Items.Clear(); foreach (ListItem objListItem in arrListItems) { ctlListBox.Items.Add(objListItem); } - } + } } public class ListItemComparer : IComparer - { + { public int Compare(object x, object y) { var a = (ListItem)x; var b = (ListItem)y; var c = new CaseInsensitiveComparer(); return c.Compare(a.Text, b.Text); - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/Help.cs b/DNN Platform/Library/UI/UserControls/Help.cs index b064e5f783a..6de274f7ea2 100644 --- a/DNN Platform/Library/UI/UserControls/Help.cs +++ b/DNN Platform/Library/UI/UserControls/Help.cs @@ -22,12 +22,12 @@ public abstract class Help : PortalModuleBase { protected LinkButton cmdCancel; protected HyperLink cmdHelp; - private string MyFileName = "Help.ascx"; - private string _key; protected Literal helpFrame; protected Label lblHelp; protected Label lblInfo; - + private string MyFileName = "Help.ascx"; + private string _key; + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -71,7 +71,7 @@ protected override void OnLoad(EventArgs e) } this._key = objModuleControl.ControlKey; - + // display module info to Host users if (this.UserInfo.IsSuperUser) { @@ -97,13 +97,13 @@ protected override void OnLoad(EventArgs e) } } } - + this.lblInfo.Text = this.Server.HtmlDecode(strInfo); } this.cmdHelp.Visible = !string.IsNullOrEmpty(objModuleControl.HelpURL); } - + if (this.Page.IsPostBack == false) { if (this.Request.UrlReferrer != null) diff --git a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs index 742b14685c0..ecbc3eef83e 100644 --- a/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs +++ b/DNN Platform/Library/UI/UserControls/HelpButtonControl.cs @@ -23,14 +23,14 @@ namespace DotNetNuke.UI.UserControls /// /// ----------------------------------------------------------------------------- public abstract class HelpButtonControl : UserControl - { + { protected LinkButton cmdHelp; protected Image imgHelp; + protected Label lblHelp; + protected Panel pnlHelp; private string _HelpKey; private string _ResourceKey; - protected Label lblHelp; - protected Panel pnlHelp; - + /// ----------------------------------------------------------------------------- /// /// Gets or sets controlName is the Id of the control that is associated with the label. @@ -55,7 +55,7 @@ public string HelpKey { return this._HelpKey; } - + set { this._HelpKey = value; @@ -76,7 +76,7 @@ public string HelpText { return this.lblHelp.Text; } - + set { this.lblHelp.Text = value; @@ -104,13 +104,13 @@ public string ResourceKey { return this._ResourceKey; } - + set { this._ResourceKey = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -132,7 +132,7 @@ protected override void OnLoad(EventArgs e) // Set Help Key to the Resource Key plus ".Help" this._HelpKey = this._ResourceKey + ".Help"; } - + string helpText = Localization.GetString(this._HelpKey, this); if (!string.IsNullOrEmpty(helpText)) { @@ -148,6 +148,6 @@ protected override void OnLoad(EventArgs e) protected void cmdHelp_Click(object sender, EventArgs e) { this.pnlHelp.Visible = true; - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/LabelControl.cs b/DNN Platform/Library/UI/UserControls/LabelControl.cs index b369e4c25b8..9a34084d97a 100644 --- a/DNN Platform/Library/UI/UserControls/LabelControl.cs +++ b/DNN Platform/Library/UI/UserControls/LabelControl.cs @@ -25,14 +25,14 @@ namespace DotNetNuke.UI.UserControls /// the javascript function __dnn_Help_OnClick(). /// public abstract class LabelControl : UserControl - { + { protected LinkButton cmdHelp; protected HtmlGenericControl label; protected Label lblHelp; protected Label lblLabel; protected Panel pnlHelp; - protected Label lblNoHelpLabel; - + protected Label lblNoHelpLabel; + /// /// Gets or sets controlName is the Id of the control that is associated with the label. /// @@ -75,7 +75,7 @@ public string HelpText { return this.lblHelp.Text; } - + set { this.lblHelp.Text = value; @@ -88,7 +88,7 @@ public string NoHelpLabelText { return this.lblNoHelpLabel.Text; } - + set { this.lblNoHelpLabel.Text = value; @@ -123,7 +123,7 @@ public string Text { return this.lblLabel.Text; } - + set { this.lblLabel.Text = value; @@ -142,13 +142,13 @@ public Unit Width { return this.lblLabel.Width; } - + set { this.lblLabel.Width = value; } - } - + } + /// /// Page_Load runs when the control is loaded. /// @@ -177,20 +177,20 @@ protected override void OnPreRender(EventArgs e) // Set Resource Key to the ID of the control this.ResourceKey = this.ID; } - + if (!string.IsNullOrEmpty(this.ResourceKey)) { var localText = Localization.GetString(this.ResourceKey, this); if (!string.IsNullOrEmpty(localText)) { this.Text = localText + this.Suffix; - + // NoHelpLabelText = Text; } else { this.Text += this.Suffix; - + // NoHelpLabelText = Text; } } @@ -210,7 +210,7 @@ protected override void OnPreRender(EventArgs e) if (string.IsNullOrEmpty(this.HelpText)) { this.pnlHelp.Visible = this.cmdHelp.Visible = false; - + // lblHelp.Visible = false; // lblNoHelpLabel.Visible = true; } @@ -234,7 +234,7 @@ protected override void OnPreRender(EventArgs e) { clientId = string.Format(this.AssociateFormat, clientId); } - + this.label.Attributes["for"] = clientId; } } @@ -243,8 +243,8 @@ private void RegisterClientDependencies() { JavaScript.RegisterClientReference(this.Page, ClientAPI.ClientNamespaceReferences.dnn); JavaScript.RequestRegistration(CommonJs.DnnPlugins); - + // ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/Scripts/initTooltips.js"); - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs index 674370275f5..306c6334291 100644 --- a/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs +++ b/DNN Platform/Library/UI/UserControls/LocaleSelectorControl.cs @@ -17,20 +17,20 @@ namespace DotNetNuke.UI.UserControls /// /// ----------------------------------------------------------------------------- public abstract class LocaleSelectorControl : UserControlBase - { + { protected DropDownList ddlPortalDefaultLanguage; protected Literal litStatus; - protected RadioButtonList rbViewType; + protected RadioButtonList rbViewType; private string MyFileName = "LocaleSelectorControl.ascx"; private string _ViewType = string.Empty; - + public string CultureCode { get { return this.ddlPortalDefaultLanguage.SelectedValue; } - } + } private CultureDropDownTypes DisplayType { @@ -56,24 +56,24 @@ private string ViewType { this._ViewType = Convert.ToString(Personalization.GetProfile("LanguageEnabler", string.Format("ViewType{0}", this.PortalSettings.PortalId))); } - + if (string.IsNullOrEmpty(this._ViewType)) { this._ViewType = "NATIVE"; } - + return this._ViewType; } - } - + } + public void BindDefaultLanguageSelector() { if (this.Page.IsPostBack == false) { Localization.LoadCultureDropDownList(this.ddlPortalDefaultLanguage, this.DisplayType, this.PortalSettings.DefaultLanguage, true); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -90,7 +90,7 @@ protected override void OnLoad(EventArgs e) { item.Selected = true; } - + item = new ListItem(Localization.GetString("EnglishName.Text", Localization.GetResourceFile(this, this.MyFileName)), "ENGLISH"); this.rbViewType.Items.Add(item); if (this.ViewType == "ENGLISH") @@ -113,6 +113,6 @@ protected override void OnPreRender(EventArgs e) private void rbViewType_SelectedIndexChanged(object sender, EventArgs e) { this._ViewType = this.rbViewType.SelectedValue; - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs index 43d5e4f2808..01e3f2f3f11 100644 --- a/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs +++ b/DNN Platform/Library/UI/UserControls/ModuleAuditControl.cs @@ -18,12 +18,12 @@ namespace DotNetNuke.UI.UserControls public abstract class ModuleAuditControl : UserControl { + private const string MyFileName = "ModuleAuditControl.ascx"; 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); + private string _systemUser; public ModuleAuditControl() { @@ -37,20 +37,6 @@ public ModuleAuditControl() public string CreatedByUser { private get; set; } - private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); - - [Serializable] - private class EntityInfo - { - public int CreatedByUserID { get; set; } - - public DateTime CreatedOnDate { get; set; } - - public int LastModifiedByUserID { get; set; } - - public DateTime LastModifiedOnDate { get; set; } - } - public string LastModifiedByUser { private get; set; } public string LastModifiedDate { private get; set; } @@ -76,6 +62,8 @@ public BaseEntityInfo Entity } } + private string DisplayMode => (this.Request.QueryString["Display"] ?? string.Empty).ToLowerInvariant(); + private EntityInfo Model { get { return this.ViewState["Entity"] as EntityInfo; } @@ -131,7 +119,7 @@ private void ShowCreatedString() } } } - + string createdString = Localization.GetString("CreatedBy", Localization.GetResourceFile(this, MyFileName)); this.lblCreatedBy.Text = string.Format(createdString, this.CreatedByUser, this.CreatedDate); } @@ -168,5 +156,17 @@ private void ShowUpdatedString(bool isCreatorAndUpdater) string updatedByString = Localization.GetString("UpdatedBy", Localization.GetResourceFile(this, MyFileName)); this.lblUpdatedBy.Text = string.Format(updatedByString, this.LastModifiedByUser, this.LastModifiedDate); } + + [Serializable] + private class EntityInfo + { + public int CreatedByUserID { get; set; } + + public DateTime CreatedOnDate { get; set; } + + public int LastModifiedByUserID { get; set; } + + public DateTime LastModifiedOnDate { get; set; } + } } } diff --git a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs index 6f9c27f9c85..94916c1e5f2 100644 --- a/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs +++ b/DNN Platform/Library/UI/UserControls/SectionHeadControl.cs @@ -22,16 +22,16 @@ namespace DotNetNuke.UI.UserControls /// /// ----------------------------------------------------------------------------- public class SectionHeadControl : UserControl - { + { protected ImageButton imgIcon; protected Label lblTitle; + protected Panel pnlRule; 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 Panel pnlRule; - + /// ----------------------------------------------------------------------------- /// /// Gets or sets cssClass determines the Css Class used for the Title Text. @@ -46,7 +46,7 @@ public string CssClass { return this.lblTitle.CssClass; } - + set { this.lblTitle.CssClass = value; @@ -68,7 +68,7 @@ public bool IncludeRule { return this._includeRule; } - + set { this._includeRule = value; @@ -90,7 +90,7 @@ public bool IsExpanded { return DNNClientAPI.MinMaxContentVisibile(this.imgIcon, -1, !this._isExpanded, DNNClientAPI.MinMaxPersistanceType.Page); } - + set { this._isExpanded = value; @@ -112,7 +112,7 @@ public string JavaScript { return this._javaScript; } - + set { this._javaScript = value; @@ -134,7 +134,7 @@ public string MaxImageUrl { return this._maxImageUrl; } - + set { this._maxImageUrl = value; @@ -156,13 +156,13 @@ public string MinImageUrl { return this._minImageUrl; } - + set { this._minImageUrl = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the ResourceKey is the key used to identify the Localization Resource for the @@ -172,8 +172,8 @@ public string MinImageUrl /// /// /// ----------------------------------------------------------------------------- - public string ResourceKey { get; set; } - + public string ResourceKey { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Section is the Id of the DHTML object that contains the xection content @@ -199,13 +199,13 @@ public string Text { return this.lblTitle.Text; } - + set { this.lblTitle.Text = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Assign resource key to label for localization. @@ -270,6 +270,6 @@ protected void imgIcon_Click(object sender, ImageClickEventArgs e) { this.IsExpanded = !this.IsExpanded; } - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/TextEditor.cs b/DNN Platform/Library/UI/UserControls/TextEditor.cs index 2feafb07e49..5b3d227ad71 100644 --- a/DNN Platform/Library/UI/UserControls/TextEditor.cs +++ b/DNN Platform/Library/UI/UserControls/TextEditor.cs @@ -30,11 +30,10 @@ namespace DotNetNuke.UI.UserControls /// ----------------------------------------------------------------------------- [ValidationPropertyAttribute("Text")] public class TextEditor : UserControl - { + { + private const string MyFileName = "TextEditor.ascx"; protected Panel PanelTextEditor; protected RadioButtonList OptRender; - private const string MyFileName = "TextEditor.ascx"; - private HtmlEditorProvider _richTextEditor; protected RadioButtonList OptView; protected PlaceHolder PlcEditor; protected HtmlGenericControl DivBasicTextBox; @@ -42,14 +41,57 @@ public class TextEditor : UserControl protected HtmlGenericControl DivRichTextBox; protected Panel PanelView; protected TextBox TxtDesktopHTML; + private HtmlEditorProvider _richTextEditor; public TextEditor() { this.HtmlEncode = true; this.ChooseRender = true; this.ChooseMode = true; - } - + } + + public bool IsRichEditorAvailable + { + get + { + return this._richTextEditor != null; + } + } + + /// Gets allows public access ot the HtmlEditorProvider. + public HtmlEditorProvider RichText + { + get + { + return this._richTextEditor; + } + } + + /// Gets allows public access of the BasicTextEditor. + public TextBox BasicTextEditor + { + get + { + return this.TxtDesktopHTML; + } + } + + public string OptViewClientId + { + get + { + return this.OptView.ClientID; + } + } + + public string LocalResourceFile + { + get + { + return this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + MyFileName; + } + } + /// Gets or sets a value indicating whether enables/Disables the option to allow the user to select between Rich/Basic Mode, Default is true. public bool ChooseMode { get; set; } @@ -63,7 +105,7 @@ public string DefaultMode { return this.ViewState["DefaultMode"] == null || string.IsNullOrEmpty(this.ViewState["DefaultMode"].ToString()) ? "RICH" : this.ViewState["DefaultMode"].ToString(); } - + set { if (!value.Equals("BASIC", StringComparison.OrdinalIgnoreCase)) @@ -119,10 +161,10 @@ public string Mode { strMode = "BASIC"; } - + return strMode; } - + set { UserInfo objUserInfo = UserController.Instance.GetCurrentUserInfo(); @@ -159,24 +201,24 @@ public string Text switch (this.OptRender.SelectedItem.Value) { case "T": - return this.Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(this.TxtDesktopHTML.Text))); - - // break; + return this.Encode(HtmlUtils.ConvertToHtml(RemoveBaseTags(this.TxtDesktopHTML.Text))); + + // break; case "R": - return RemoveBaseTags(this.TxtDesktopHTML.Text); - - // break; + return RemoveBaseTags(this.TxtDesktopHTML.Text); + + // break; default: return this.Encode(RemoveBaseTags(this.TxtDesktopHTML.Text)); - + // break; } - + default: return this.IsRichEditorAvailable ? this.Encode(RemoveBaseTags(this._richTextEditor.Text)) : this.Encode(RemoveBaseTags(this.TxtDesktopHTML.Text)); } } - + set { this.TxtDesktopHTML.Text = HtmlUtils.ConvertToText(this.Decode(value)); @@ -194,7 +236,7 @@ public string TextRenderMode { return Convert.ToString(this.ViewState["textrender"]); } - + set { var strMode = value.ToUpper().Substring(0, 1); @@ -202,7 +244,7 @@ public string TextRenderMode { strMode = "H"; } - + this.ViewState["textrender"] = strMode; } } @@ -210,171 +252,18 @@ public string TextRenderMode /// Gets or sets /Sets the Width of the control. public Unit Width { get; set; } - public bool IsRichEditorAvailable - { - get - { - return this._richTextEditor != null; - } - } - - /// Gets allows public access ot the HtmlEditorProvider. - public HtmlEditorProvider RichText - { - get - { - return this._richTextEditor; - } - } - - /// Gets allows public access of the BasicTextEditor. - public TextBox BasicTextEditor - { - get - { - return this.TxtDesktopHTML; - } - } - - public string OptViewClientId - { - get - { - return this.OptView.ClientID; - } - } - - public string LocalResourceFile - { - get - { - return this.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + MyFileName; - } - } - 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. - /// - /// - /// - /// Html to decode. - /// The decoded html. - /// ----------------------------------------------------------------------------- - private string Decode(string strHtml) - { - return this.HtmlEncode ? this.Server.HtmlDecode(strHtml) : strHtml; } - /// ----------------------------------------------------------------------------- - /// - /// Encodes the html. - /// - /// - /// - /// Html to encode. - /// The encoded html. - /// ----------------------------------------------------------------------------- - private string Encode(string strHtml) - { - return this.HtmlEncode ? this.Server.HtmlEncode(strHtml) : strHtml; - } - - /// ----------------------------------------------------------------------------- - /// - /// Builds the radio button lists. - /// - /// - /// - /// ----------------------------------------------------------------------------- - private void PopulateLists() - { - if (this.OptRender.Items.Count == 0) - { - this.OptRender.Items.Add(new ListItem(Localization.GetString("Text", Localization.GetResourceFile(this, MyFileName)), "T")); - this.OptRender.Items.Add(new ListItem(Localization.GetString("Html", Localization.GetResourceFile(this, MyFileName)), "H")); - this.OptRender.Items.Add(new ListItem(Localization.GetString("Raw", Localization.GetResourceFile(this, MyFileName)), "R")); - } - - if (this.OptView.Items.Count == 0) - { - this.OptView.Items.Add(new ListItem(Localization.GetString("BasicTextBox", Localization.GetResourceFile(this, MyFileName)), "BASIC")); - if (this.IsRichEditorAvailable) - { - this.OptView.Items.Add(new ListItem(Localization.GetString("RichTextBox", Localization.GetResourceFile(this, MyFileName)), "RICH")); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Sets the Mode displayed. - /// - /// - /// - /// ----------------------------------------------------------------------------- - private void SetPanels() - { - if (this.OptView.SelectedIndex != -1) - { - this.Mode = this.OptView.SelectedItem.Value; - } - - if (!string.IsNullOrEmpty(this.Mode)) - { - this.OptView.Items.FindByValue(this.Mode).Selected = true; - } - else - { - this.OptView.SelectedIndex = 0; - } - - // Set the text render mode for basic mode - if (this.OptRender.SelectedIndex != -1) - { - this.TextRenderMode = this.OptRender.SelectedItem.Value; - } - - if (!string.IsNullOrEmpty(this.TextRenderMode)) - { - this.OptRender.Items.FindByValue(this.TextRenderMode).Selected = true; - } - else - { - this.OptRender.SelectedIndex = 0; - } - - if (this.OptView.SelectedItem.Value == "BASIC") - { - this.DivBasicTextBox.Visible = true; - this.DivRichTextBox.Visible = false; - this.PanelView.CssClass = "dnnTextPanelView dnnTextPanelView-basic"; - } - else - { - this.DivBasicTextBox.Visible = false; - this.DivRichTextBox.Visible = true; - this.PanelView.CssClass = "dnnTextPanelView"; - } - } - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -427,7 +316,7 @@ protected override void OnLoad(EventArgs e) { this.PanelView.Visible = false; } - + if (!this.ChooseRender) { this.DivBasicRender.Visible = false; @@ -460,12 +349,12 @@ protected void OptRenderSelectedIndexChanged(object sender, EventArgs e) { this.TextRenderMode = this.OptRender.SelectedItem.Value; } - + if (this.Mode == "BASIC") { this.TxtDesktopHTML.Text = this.TextRenderMode == "H" ? HtmlUtils.ConvertToHtml(this.TxtDesktopHTML.Text) : HtmlUtils.ConvertToText(this.TxtDesktopHTML.Text); } - + this.SetPanels(); } @@ -482,7 +371,7 @@ protected void OptViewSelectedIndexChanged(object sender, EventArgs e) { this.Mode = this.OptView.SelectedItem.Value; } - + if (this.Mode == "BASIC") { switch (this.TextRenderMode) @@ -507,8 +396,119 @@ protected void OptViewSelectedIndexChanged(object sender, EventArgs e) break; } } - + this.SetPanels(); - } + } + + private static string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } + + /// ----------------------------------------------------------------------------- + /// + /// Decodes the html. + /// + /// + /// + /// Html to decode. + /// The decoded html. + /// ----------------------------------------------------------------------------- + private string Decode(string strHtml) + { + return this.HtmlEncode ? this.Server.HtmlDecode(strHtml) : strHtml; + } + + /// ----------------------------------------------------------------------------- + /// + /// Encodes the html. + /// + /// + /// + /// Html to encode. + /// The encoded html. + /// ----------------------------------------------------------------------------- + private string Encode(string strHtml) + { + return this.HtmlEncode ? this.Server.HtmlEncode(strHtml) : strHtml; + } + + /// ----------------------------------------------------------------------------- + /// + /// Builds the radio button lists. + /// + /// + /// + /// ----------------------------------------------------------------------------- + private void PopulateLists() + { + if (this.OptRender.Items.Count == 0) + { + this.OptRender.Items.Add(new ListItem(Localization.GetString("Text", Localization.GetResourceFile(this, MyFileName)), "T")); + this.OptRender.Items.Add(new ListItem(Localization.GetString("Html", Localization.GetResourceFile(this, MyFileName)), "H")); + this.OptRender.Items.Add(new ListItem(Localization.GetString("Raw", Localization.GetResourceFile(this, MyFileName)), "R")); + } + + if (this.OptView.Items.Count == 0) + { + this.OptView.Items.Add(new ListItem(Localization.GetString("BasicTextBox", Localization.GetResourceFile(this, MyFileName)), "BASIC")); + if (this.IsRichEditorAvailable) + { + this.OptView.Items.Add(new ListItem(Localization.GetString("RichTextBox", Localization.GetResourceFile(this, MyFileName)), "RICH")); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Sets the Mode displayed. + /// + /// + /// + /// ----------------------------------------------------------------------------- + private void SetPanels() + { + if (this.OptView.SelectedIndex != -1) + { + this.Mode = this.OptView.SelectedItem.Value; + } + + if (!string.IsNullOrEmpty(this.Mode)) + { + this.OptView.Items.FindByValue(this.Mode).Selected = true; + } + else + { + this.OptView.SelectedIndex = 0; + } + + // Set the text render mode for basic mode + if (this.OptRender.SelectedIndex != -1) + { + this.TextRenderMode = this.OptRender.SelectedItem.Value; + } + + if (!string.IsNullOrEmpty(this.TextRenderMode)) + { + this.OptRender.Items.FindByValue(this.TextRenderMode).Selected = true; + } + else + { + this.OptRender.SelectedIndex = 0; + } + + if (this.OptView.SelectedItem.Value == "BASIC") + { + this.DivBasicTextBox.Visible = true; + this.DivRichTextBox.Visible = false; + this.PanelView.CssClass = "dnnTextPanelView dnnTextPanelView-basic"; + } + else + { + this.DivBasicTextBox.Visible = false; + this.DivRichTextBox.Visible = true; + this.PanelView.CssClass = "dnnTextPanelView"; + } + } } } diff --git a/DNN Platform/Library/UI/UserControls/URLControl.cs b/DNN Platform/Library/UI/UserControls/URLControl.cs index d7b7194f64d..c454d9ed7ed 100644 --- a/DNN Platform/Library/UI/UserControls/URLControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLControl.cs @@ -38,13 +38,6 @@ public abstract class UrlControl : UserControlBase protected Panel UserRow; protected DropDownList cboFiles; protected DropDownList cboFolders; - private bool _doChangeURL; - private bool _doReloadFiles; - private bool _doReloadFolders; - private bool _doRenderTypeControls; - private bool _doRenderTypes; - private string _localResourceFile; - private PortalInfo _objPortal; protected DropDownList cboImages; protected DropDownList cboTabs; protected DropDownList cboUrls; @@ -70,6 +63,43 @@ public abstract class UrlControl : UserControlBase protected HtmlInputFile txtFile; protected TextBox txtUrl; protected TextBox txtUser; + private bool _doChangeURL; + private bool _doReloadFiles; + private bool _doReloadFolders; + private bool _doRenderTypeControls; + private bool _doRenderTypes; + private string _localResourceFile; + private PortalInfo _objPortal; + + public bool Log + { + get + { + if (this.chkLog.Visible) + { + return this.chkLog.Checked; + } + else + { + return false; + } + } + } + + public bool Track + { + get + { + if (this.chkTrack.Visible) + { + return this.chkTrack.Checked; + } + else + { + return false; + } + } + } public string FileFilter { @@ -142,21 +172,6 @@ public string LocalResourceFile } } - public bool Log - { - get - { - if (this.chkLog.Visible) - { - return this.chkLog.Checked; - } - else - { - return false; - } - } - } - public int ModuleID { get @@ -424,21 +439,6 @@ public bool ShowUsers } } - public bool Track - { - get - { - if (this.chkTrack.Visible) - { - return this.chkTrack.Checked; - } - else - { - return false; - } - } - } - public string Url { get @@ -645,416 +645,741 @@ protected override void OnLoad(EventArgs e) } } - private ArrayList GetFileList(bool NoneSpecified) + protected override void OnPreRender(EventArgs e) { - int PortalId = Null.NullInteger; + base.OnPreRender(e); - if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) + try { - PortalId = this._objPortal.PortalID; - } + if (this._doRenderTypes) + { + this.DoRenderTypes(); + } - return Globals.GetFileList(PortalId, this.FileFilter, NoneSpecified, this.cboFolders.SelectedItem.Value, false); + if (this._doChangeURL) + { + this.DoChangeURL(); + } + + if (this._doReloadFolders || this._doReloadFiles) + { + this.DoCorrectRadioButtonList(); + this._doRenderTypeControls = true; + } + + if (this._doRenderTypeControls) + { + if (!(this._doReloadFolders || this._doReloadFiles)) + { + this.DoCorrectRadioButtonList(); + } + + this.DoRenderTypeControls(); + } + + this.ViewState["Url"] = null; + this.ViewState["IsUrlControlLoaded"] = "Loaded"; + } + catch (Exception exc) + { + // Let's detect possible problems + Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); + } } - private void LoadFolders(string Permissions) + protected void cboFolders_SelectedIndexChanged(object sender, EventArgs e) { int PortalId = Null.NullInteger; - this.cboFolders.Items.Clear(); - if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) + if (!this.IsHostMenu || this.Request.QueryString["pid"] != null) { PortalId = this._objPortal.PortalID; } - var folders = FolderManager.Instance.GetFolders(UserController.Instance.GetCurrentUserInfo(), Permissions); - foreach (FolderInfo folder in folders) + var objFolder = FolderManager.Instance.GetFolder(PortalId, this.cboFolders.SelectedValue); + if (FolderPermissionController.CanAddFolder((FolderInfo)objFolder)) { - var FolderItem = new ListItem(); - if (folder.FolderPath == Null.NullString) - { - FolderItem.Text = Localization.GetString("Root", this.LocalResourceFile); - } - else + if (!this.txtFile.Visible) { - FolderItem.Text = folder.DisplayPath; + this.cmdSave.Visible = false; + + // only show if not already in upload mode and not disabled + this.cmdUpload.Visible = this.ShowUpLoad; } + } + else + { + // reset controls + this.cboFiles.Visible = true; + this.cmdUpload.Visible = false; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + } - FolderItem.Value = folder.FolderPath; - this.cboFolders.Items.Add(FolderItem); + this.cboFiles.Items.Clear(); + this.cboFiles.DataSource = this.GetFileList(!this.Required); + this.cboFiles.DataBind(); + this.SetStorageLocationType(); + if (this.cboFolders.SelectedIndex >= 0) + { + this.ViewState["LastFolderPath"] = this.cboFolders.SelectedValue; + } + else + { + this.ViewState["LastFolderPath"] = string.Empty; } + + if (this.cboFiles.SelectedIndex >= 0) + { + this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; + } + else + { + this.ViewState["LastFileName"] = string.Empty; + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - private void LoadUrls() + protected void cmdAdd_Click(object sender, EventArgs e) { - var objUrls = new UrlController(); - this.cboUrls.Items.Clear(); - this.cboUrls.DataSource = objUrls.GetUrls(this._objPortal.PortalID); - this.cboUrls.DataBind(); + this.cboUrls.Visible = false; + this.cmdSelect.Visible = true; + this.txtUrl.Visible = true; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - private void SetStorageLocationType() + protected void cmdCancel_Click(object sender, EventArgs e) { - string FolderName = this.cboFolders.SelectedValue; + this.cboFiles.Visible = true; + this.cmdUpload.Visible = true; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; + } - // Check to see if this is the 'Root' folder, if so we cannot rely on its text value because it is something and not an empty string that we need to lookup the 'root' folder - if (this.cboFolders.SelectedValue == string.Empty) + protected void cmdDelete_Click(object sender, EventArgs e) + { + if (this.cboUrls.SelectedItem != null) { - FolderName = string.Empty; + var objUrls = new UrlController(); + objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); + this.LoadUrls(); // we must reload the url list } - var objFolderInfo = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, FolderName); - if (objFolderInfo != null) - { - var folderMapping = FolderMappingController.Instance.GetFolderMapping(objFolderInfo.PortalID, objFolderInfo.FolderMappingID); - if (folderMapping.MappingName == "Standard") - { - this.imgStorageLocationType.Visible = false; - } - else - { - this.imgStorageLocationType.Visible = true; - this.imgStorageLocationType.ImageUrl = FolderProvider.Instance(folderMapping.FolderProviderType).GetFolderProviderIconPath(); - } - } + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; } - private void DoChangeURL() + protected void cmdSave_Click(object sender, EventArgs e) { - string _Url = Convert.ToString(this.ViewState["Url"]); - string _Urltype = Convert.ToString(this.ViewState["UrlType"]); - if (!string.IsNullOrEmpty(_Url)) - { - var objUrls = new UrlController(); - string TrackingUrl = _Url; + this.cmdUpload.Visible = false; - _Urltype = Globals.GetURLType(_Url).ToString("g").Substring(0, 1); - if (_Urltype == "U" && _Url.StartsWith("~/" + this.PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase)) - { - _Urltype = "I"; - } + // if no file is selected exit + if (string.IsNullOrEmpty(this.txtFile.PostedFile.FileName)) + { + return; + } - this.ViewState["UrlType"] = _Urltype; - if (_Urltype == "F") - { - if (_Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) - { - TrackingUrl = _Url; - var objFile = FileManager.Instance.GetFile(int.Parse(_Url.Substring(7))); - if (objFile != null) - { - _Url = objFile.Folder + objFile.FileName; - } - } - else - { - // to handle legacy scenarios before the introduction of the FileServerHandler - var fileName = Path.GetFileName(_Url); - var folderPath = _Url.Substring(0, _Url.LastIndexOf(fileName)); - var folder = FolderManager.Instance.GetFolder(this._objPortal.PortalID, folderPath); - var fileId = -1; - if (folder != null) - { - var file = FileManager.Instance.GetFile(folder, fileName); - if (file != null) - { - fileId = file.FileId; - } - } - - TrackingUrl = "FileID=" + fileId.ToString(); - } - } - - if (_Urltype == "M") - { - if (_Url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) - { - UserInfo objUser = UserController.GetUserById(this._objPortal.PortalID, int.Parse(_Url.Substring(7))); - if (objUser != null) - { - _Url = objUser.Username; - } - } - } - - UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this._objPortal.PortalID, TrackingUrl, this.ModuleID); - if (objUrlTracking != null) - { - this.chkNewWindow.Checked = objUrlTracking.NewWindow; - this.chkTrack.Checked = objUrlTracking.TrackClicks; - this.chkLog.Checked = objUrlTracking.LogActivity; - } - else // the url does not exist in the tracking table - { - this.chkTrack.Checked = false; - this.chkLog.Checked = false; - } - - this.ViewState["Url"] = _Url; + string ParentFolderName; + if (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) + { + ParentFolderName = Globals.HostMapPath; } else { - if (!string.IsNullOrEmpty(_Urltype)) - { - this.optType.ClearSelection(); - if (this.optType.Items.FindByValue(_Urltype) != null) - { - this.optType.Items.FindByValue(_Urltype).Selected = true; - } - else - { - this.optType.Items[0].Selected = true; - } - } - else - { - if (this.optType.Items.Count > 0) - { - this.optType.ClearSelection(); - this.optType.Items[0].Selected = true; - } - } - - this.chkNewWindow.Checked = false; // Need check - this.chkTrack.Checked = false; // Need check - this.chkLog.Checked = false; // Need check + ParentFolderName = this.PortalSettings.HomeDirectoryMapPath; } - // Url type changed, then we must draw the controlos for that type - this._doRenderTypeControls = true; - } - - private void DoRenderTypes() - { - // We must clear the list to keep the same item order - string strCurrent = string.Empty; - if (this.optType.SelectedIndex >= 0) - { - strCurrent = this.optType.SelectedItem.Value; // Save current selected value - } + ParentFolderName += this.cboFolders.SelectedItem.Value; - this.optType.Items.Clear(); - if (this.ShowNone) + string strExtension = Path.GetExtension(this.txtFile.PostedFile.FileName).Replace(".", string.Empty); + if (!string.IsNullOrEmpty(this.FileFilter) && ("," + this.FileFilter.ToLowerInvariant()).IndexOf("," + strExtension.ToLowerInvariant()) == -1) { - if (this.optType.Items.FindByValue("N") == null) - { - this.optType.Items.Add(new ListItem(Localization.GetString("NoneType", this.LocalResourceFile), "N")); - } + // trying to upload a file not allowed for current filter + this.lblMessage.Text = string.Format(Localization.GetString("UploadError", this.LocalResourceFile), this.FileFilter, strExtension); + this.ErrorRow.Visible = true; } else { - if (this.optType.Items.FindByValue("N") != null) + var fileManager = FileManager.Instance; + var folderManager = FolderManager.Instance; + + var settings = PortalController.Instance.GetCurrentPortalSettings(); + var portalID = (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; + + var fileName = Path.GetFileName(this.txtFile.PostedFile.FileName); + var folderPath = Globals.GetSubFolderPath(ParentFolderName.Replace("/", "\\") + fileName, portalID); + + var folder = folderManager.GetFolder(portalID, folderPath); + this.ErrorRow.Visible = false; + + try { - this.optType.Items.Remove(this.optType.Items.FindByValue("N")); + fileManager.AddFile(folder, fileName, this.txtFile.PostedFile.InputStream, true, true, ((FileManager)fileManager).GetContentType(Path.GetExtension(fileName))); } - } - - if (this.ShowUrls) - { - if (this.optType.Items.FindByValue("U") == null) + catch (Services.FileSystem.PermissionsNotMetException) { - this.optType.Items.Add(new ListItem(Localization.GetString("URLType", this.LocalResourceFile), "U")); + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); + this.ErrorRow.Visible = true; } - } - else - { - if (this.optType.Items.FindByValue("U") != null) + catch (NoSpaceAvailableException) { - this.optType.Items.Remove(this.optType.Items.FindByValue("U")); + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); + this.ErrorRow.Visible = true; } - } - - if (this.ShowTabs) - { - if (this.optType.Items.FindByValue("T") == null) + catch (InvalidFileExtensionException) { - this.optType.Items.Add(new ListItem(Localization.GetString("TabType", this.LocalResourceFile), "T")); + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); + this.ErrorRow.Visible = true; } - } - else - { - if (this.optType.Items.FindByValue("T") != null) + catch (Exception) { - this.optType.Items.Remove(this.optType.Items.FindByValue("T")); + this.lblMessage.Text += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); + this.ErrorRow.Visible = true; } } - if (this.ShowFiles) + if (this.lblMessage.Text == string.Empty) { - if (this.optType.Items.FindByValue("F") == null) + this.cboFiles.Visible = true; + this.cmdUpload.Visible = this.ShowUpLoad; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this.ErrorRow.Visible = false; + + var Root = new DirectoryInfo(ParentFolderName); + this.cboFiles.Items.Clear(); + this.cboFiles.DataSource = this.GetFileList(false); + this.cboFiles.DataBind(); + + string FileName = this.txtFile.PostedFile.FileName.Substring(this.txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); + if (this.cboFiles.Items.FindByText(FileName) != null) { - this.optType.Items.Add(new ListItem(Localization.GetString("FileType", this.LocalResourceFile), "F")); + this.cboFiles.Items.FindByText(FileName).Selected = true; } - } - else - { - if (this.optType.Items.FindByValue("F") != null) + + if (this.cboFiles.SelectedIndex >= 0) { - this.optType.Items.Remove(this.optType.Items.FindByValue("F")); + this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; } - } - - if (this.ShowImages) - { - if (this.optType.Items.FindByValue("I") == null) + else { - this.optType.Items.Add(new ListItem(Localization.GetString("ImageType", this.LocalResourceFile), "I")); + this.ViewState["LastFileName"] = string.Empty; } } - else + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; + } + + protected void cmdSelect_Click(object sender, EventArgs e) + { + this.cboUrls.Visible = true; + this.cmdSelect.Visible = false; + this.txtUrl.Visible = false; + this.cmdAdd.Visible = true; + this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); + this.LoadUrls(); + if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) { - if (this.optType.Items.FindByValue("I") != null) - { - this.optType.Items.Remove(this.optType.Items.FindByValue("I")); - } + this.cboUrls.ClearSelection(); + this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; } - if (this.ShowUsers) + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; + } + + protected void cmdUpload_Click(object sender, EventArgs e) + { + string strSaveFolder = this.cboFolders.SelectedValue; + this.LoadFolders("ADD"); + if (this.cboFolders.Items.FindByValue(strSaveFolder) != null) { - if (this.optType.Items.FindByValue("M") == null) - { - this.optType.Items.Add(new ListItem(Localization.GetString("UserType", this.LocalResourceFile), "M")); - } + this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; + this.cboFiles.Visible = false; + this.cmdUpload.Visible = false; + this.txtFile.Visible = true; + this.cmdSave.Visible = true; + this.cmdCancel.Visible = true; } else { - if (this.optType.Items.FindByValue("M") != null) + if (this.cboFolders.Items.Count > 0) { - this.optType.Items.Remove(this.optType.Items.FindByValue("M")); + this.cboFolders.Items[0].Selected = true; + this.cboFiles.Visible = false; + this.cmdUpload.Visible = false; + this.txtFile.Visible = true; + this.cmdSave.Visible = true; + this.cmdCancel.Visible = true; } - } - - if (this.optType.Items.Count > 0) - { - if (!string.IsNullOrEmpty(strCurrent)) + else { - if (this.optType.Items.FindByValue(strCurrent) != null) - { - this.optType.Items.FindByValue(strCurrent).Selected = true; - } - else - { - this.optType.Items[0].Selected = true; - this._doRenderTypeControls = true; // Type changed, re-draw - } + // reset controls + this.LoadFolders("BROWSE,ADD"); + this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; + this.cboFiles.Visible = true; + this.cmdUpload.Visible = false; + this.txtFile.Visible = false; + this.cmdSave.Visible = false; + this.cmdCancel.Visible = false; + this.lblMessage.Text = Localization.GetString("NoWritePermission", this.LocalResourceFile); + this.ErrorRow.Visible = true; + } + } + + this._doRenderTypeControls = false; // Must not render on this postback + this._doRenderTypes = false; + this._doChangeURL = false; + this._doReloadFolders = false; + this._doReloadFiles = false; + } + + protected void optType_SelectedIndexChanged(object sender, EventArgs e) + { + // Type changed, render the correct control set + this.ViewState["UrlType"] = this.optType.SelectedItem.Value; + this._doRenderTypeControls = true; + } + + private ArrayList GetFileList(bool NoneSpecified) + { + int PortalId = Null.NullInteger; + + if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) + { + PortalId = this._objPortal.PortalID; + } + + return Globals.GetFileList(PortalId, this.FileFilter, NoneSpecified, this.cboFolders.SelectedItem.Value, false); + } + + private void LoadFolders(string Permissions) + { + int PortalId = Null.NullInteger; + this.cboFolders.Items.Clear(); + + if ((!this.IsHostMenu) || (this.Request.QueryString["pid"] != null)) + { + PortalId = this._objPortal.PortalID; + } + + var folders = FolderManager.Instance.GetFolders(UserController.Instance.GetCurrentUserInfo(), Permissions); + foreach (FolderInfo folder in folders) + { + var FolderItem = new ListItem(); + if (folder.FolderPath == Null.NullString) + { + FolderItem.Text = Localization.GetString("Root", this.LocalResourceFile); } else { - this.optType.Items[0].Selected = true; - this._doRenderTypeControls = true; // Type changed, re-draw + FolderItem.Text = folder.DisplayPath; } - this.TypeRow.Visible = this.optType.Items.Count > 1; - } - else - { - this.TypeRow.Visible = false; + FolderItem.Value = folder.FolderPath; + this.cboFolders.Items.Add(FolderItem); } } - private void DoCorrectRadioButtonList() + private void LoadUrls() { - string _Urltype = Convert.ToString(this.ViewState["UrlType"]); + var objUrls = new UrlController(); + this.cboUrls.Items.Clear(); + this.cboUrls.DataSource = objUrls.GetUrls(this._objPortal.PortalID); + this.cboUrls.DataBind(); + } - if (this.optType.Items.Count > 0) + private void SetStorageLocationType() + { + string FolderName = this.cboFolders.SelectedValue; + + // Check to see if this is the 'Root' folder, if so we cannot rely on its text value because it is something and not an empty string that we need to lookup the 'root' folder + if (this.cboFolders.SelectedValue == string.Empty) { - this.optType.ClearSelection(); - if (!string.IsNullOrEmpty(_Urltype)) + FolderName = string.Empty; + } + + var objFolderInfo = FolderManager.Instance.GetFolder(this.PortalSettings.PortalId, FolderName); + if (objFolderInfo != null) + { + var folderMapping = FolderMappingController.Instance.GetFolderMapping(objFolderInfo.PortalID, objFolderInfo.FolderMappingID); + if (folderMapping.MappingName == "Standard") { - if (this.optType.Items.FindByValue(_Urltype) != null) - { - this.optType.Items.FindByValue(_Urltype).Selected = true; - } - else - { - this.optType.Items[0].Selected = true; - _Urltype = this.optType.Items[0].Value; - this.ViewState["UrlType"] = _Urltype; - } + this.imgStorageLocationType.Visible = false; } else { - this.optType.Items[0].Selected = true; - _Urltype = this.optType.Items[0].Value; - this.ViewState["UrlType"] = _Urltype; + this.imgStorageLocationType.Visible = true; + this.imgStorageLocationType.ImageUrl = FolderProvider.Instance(folderMapping.FolderProviderType).GetFolderProviderIconPath(); } } } - private void DoRenderTypeControls() + private void DoChangeURL() { string _Url = Convert.ToString(this.ViewState["Url"]); string _Urltype = Convert.ToString(this.ViewState["UrlType"]); - var objUrls = new UrlController(); - if (!string.IsNullOrEmpty(_Urltype)) + if (!string.IsNullOrEmpty(_Url)) { - // load listitems - switch (this.optType.SelectedItem.Value) - { - case "N": // None - this.URLRow.Visible = false; - this.TabRow.Visible = false; - this.FileRow.Visible = false; - this.UserRow.Visible = false; - this.ImagesRow.Visible = false; - break; - case "I": // System Image - this.URLRow.Visible = false; - this.TabRow.Visible = false; - this.FileRow.Visible = false; - this.UserRow.Visible = false; - this.ImagesRow.Visible = true; + var objUrls = new UrlController(); + string TrackingUrl = _Url; - this.cboImages.Items.Clear(); + _Urltype = Globals.GetURLType(_Url).ToString("g").Substring(0, 1); + if (_Urltype == "U" && _Url.StartsWith("~/" + this.PortalSettings.DefaultIconLocation, StringComparison.InvariantCultureIgnoreCase)) + { + _Urltype = "I"; + } - string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, this.PortalSettings.DefaultIconLocation.Replace('/', '\\')); - foreach (string strImage in Directory.GetFiles(strImagesFolder)) + this.ViewState["UrlType"] = _Urltype; + if (_Urltype == "F") + { + if (_Url.StartsWith("fileid=", StringComparison.InvariantCultureIgnoreCase)) + { + TrackingUrl = _Url; + var objFile = FileManager.Instance.GetFile(int.Parse(_Url.Substring(7))); + if (objFile != null) { - string img = strImage.Replace(strImagesFolder, string.Empty).Trim('/').Trim('\\'); - this.cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", this.PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); + _Url = objFile.Folder + objFile.FileName; } - - ListItem selecteItem = this.cboImages.Items.FindByValue(_Url.ToLowerInvariant()); - if (selecteItem != null) + } + else + { + // to handle legacy scenarios before the introduction of the FileServerHandler + var fileName = Path.GetFileName(_Url); + var folderPath = _Url.Substring(0, _Url.LastIndexOf(fileName)); + var folder = FolderManager.Instance.GetFolder(this._objPortal.PortalID, folderPath); + var fileId = -1; + if (folder != null) { - selecteItem.Selected = true; + var file = FileManager.Instance.GetFile(folder, fileName); + if (file != null) + { + fileId = file.FileId; + } } - break; - - case "U": // Url - this.URLRow.Visible = true; - this.TabRow.Visible = false; - this.FileRow.Visible = false; - this.UserRow.Visible = false; - this.ImagesRow.Visible = false; - if (string.IsNullOrEmpty(this.txtUrl.Text)) - { - this.txtUrl.Text = _Url; - } + TrackingUrl = "FileID=" + fileId.ToString(); + } + } - if (string.IsNullOrEmpty(this.txtUrl.Text)) + if (_Urltype == "M") + { + if (_Url.StartsWith("userid=", StringComparison.InvariantCultureIgnoreCase)) + { + UserInfo objUser = UserController.GetUserById(this._objPortal.PortalID, int.Parse(_Url.Substring(7))); + if (objUser != null) { - this.txtUrl.Text = "http://"; + _Url = objUser.Username; } + } + } - this.txtUrl.Visible = true; + UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this._objPortal.PortalID, TrackingUrl, this.ModuleID); + if (objUrlTracking != null) + { + this.chkNewWindow.Checked = objUrlTracking.NewWindow; + this.chkTrack.Checked = objUrlTracking.TrackClicks; + this.chkLog.Checked = objUrlTracking.LogActivity; + } + else // the url does not exist in the tracking table + { + this.chkTrack.Checked = false; + this.chkLog.Checked = false; + } - this.cmdSelect.Visible = true; + this.ViewState["Url"] = _Url; + } + else + { + if (!string.IsNullOrEmpty(_Urltype)) + { + this.optType.ClearSelection(); + if (this.optType.Items.FindByValue(_Urltype) != null) + { + this.optType.Items.FindByValue(_Urltype).Selected = true; + } + else + { + this.optType.Items[0].Selected = true; + } + } + else + { + if (this.optType.Items.Count > 0) + { + this.optType.ClearSelection(); + this.optType.Items[0].Selected = true; + } + } - this.cboUrls.Visible = false; - this.cmdAdd.Visible = false; - this.cmdDelete.Visible = false; - break; - case "T": // tab - this.URLRow.Visible = false; - this.TabRow.Visible = true; - this.FileRow.Visible = false; - this.UserRow.Visible = false; - this.ImagesRow.Visible = false; + this.chkNewWindow.Checked = false; // Need check + this.chkTrack.Checked = false; // Need check + this.chkLog.Checked = false; // Need check + } - this.cboTabs.Items.Clear(); + // Url type changed, then we must draw the controlos for that type + this._doRenderTypeControls = true; + } + + private void DoRenderTypes() + { + // We must clear the list to keep the same item order + string strCurrent = string.Empty; + if (this.optType.SelectedIndex >= 0) + { + strCurrent = this.optType.SelectedItem.Value; // Save current selected value + } + + this.optType.Items.Clear(); + if (this.ShowNone) + { + if (this.optType.Items.FindByValue("N") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("NoneType", this.LocalResourceFile), "N")); + } + } + else + { + if (this.optType.Items.FindByValue("N") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("N")); + } + } + + if (this.ShowUrls) + { + if (this.optType.Items.FindByValue("U") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("URLType", this.LocalResourceFile), "U")); + } + } + else + { + if (this.optType.Items.FindByValue("U") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("U")); + } + } + + if (this.ShowTabs) + { + if (this.optType.Items.FindByValue("T") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("TabType", this.LocalResourceFile), "T")); + } + } + else + { + if (this.optType.Items.FindByValue("T") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("T")); + } + } + + if (this.ShowFiles) + { + if (this.optType.Items.FindByValue("F") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("FileType", this.LocalResourceFile), "F")); + } + } + else + { + if (this.optType.Items.FindByValue("F") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("F")); + } + } + + if (this.ShowImages) + { + if (this.optType.Items.FindByValue("I") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("ImageType", this.LocalResourceFile), "I")); + } + } + else + { + if (this.optType.Items.FindByValue("I") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("I")); + } + } + + if (this.ShowUsers) + { + if (this.optType.Items.FindByValue("M") == null) + { + this.optType.Items.Add(new ListItem(Localization.GetString("UserType", this.LocalResourceFile), "M")); + } + } + else + { + if (this.optType.Items.FindByValue("M") != null) + { + this.optType.Items.Remove(this.optType.Items.FindByValue("M")); + } + } + + if (this.optType.Items.Count > 0) + { + if (!string.IsNullOrEmpty(strCurrent)) + { + if (this.optType.Items.FindByValue(strCurrent) != null) + { + this.optType.Items.FindByValue(strCurrent).Selected = true; + } + else + { + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw + } + } + else + { + this.optType.Items[0].Selected = true; + this._doRenderTypeControls = true; // Type changed, re-draw + } + + this.TypeRow.Visible = this.optType.Items.Count > 1; + } + else + { + this.TypeRow.Visible = false; + } + } + + private void DoCorrectRadioButtonList() + { + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); + + if (this.optType.Items.Count > 0) + { + this.optType.ClearSelection(); + if (!string.IsNullOrEmpty(_Urltype)) + { + if (this.optType.Items.FindByValue(_Urltype) != null) + { + this.optType.Items.FindByValue(_Urltype).Selected = true; + } + else + { + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; + } + } + else + { + this.optType.Items[0].Selected = true; + _Urltype = this.optType.Items[0].Value; + this.ViewState["UrlType"] = _Urltype; + } + } + } + + private void DoRenderTypeControls() + { + string _Url = Convert.ToString(this.ViewState["Url"]); + string _Urltype = Convert.ToString(this.ViewState["UrlType"]); + var objUrls = new UrlController(); + if (!string.IsNullOrEmpty(_Urltype)) + { + // load listitems + switch (this.optType.SelectedItem.Value) + { + case "N": // None + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + break; + case "I": // System Image + this.URLRow.Visible = false; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = true; + + this.cboImages.Items.Clear(); + + string strImagesFolder = Path.Combine(Globals.ApplicationMapPath, this.PortalSettings.DefaultIconLocation.Replace('/', '\\')); + foreach (string strImage in Directory.GetFiles(strImagesFolder)) + { + string img = strImage.Replace(strImagesFolder, string.Empty).Trim('/').Trim('\\'); + this.cboImages.Items.Add(new ListItem(img, string.Format("~/{0}/{1}", this.PortalSettings.DefaultIconLocation, img).ToLowerInvariant())); + } + + ListItem selecteItem = this.cboImages.Items.FindByValue(_Url.ToLowerInvariant()); + if (selecteItem != null) + { + selecteItem.Selected = true; + } + + break; + + case "U": // Url + this.URLRow.Visible = true; + this.TabRow.Visible = false; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + if (string.IsNullOrEmpty(this.txtUrl.Text)) + { + this.txtUrl.Text = _Url; + } + + if (string.IsNullOrEmpty(this.txtUrl.Text)) + { + this.txtUrl.Text = "http://"; + } + + this.txtUrl.Visible = true; + + this.cmdSelect.Visible = true; + + this.cboUrls.Visible = false; + this.cmdAdd.Visible = false; + this.cmdDelete.Visible = false; + break; + case "T": // tab + this.URLRow.Visible = false; + this.TabRow.Visible = true; + this.FileRow.Visible = false; + this.UserRow.Visible = false; + this.ImagesRow.Visible = false; + + this.cboTabs.Items.Clear(); PortalSettings _settings = PortalController.Instance.GetCurrentPortalSettings(); this.cboTabs.DataSource = TabController.GetPortalTabs(_settings.PortalId, Null.NullInteger, !this.Required, "none available", true, false, false, true, false); @@ -1222,330 +1547,5 @@ private void DoRenderTypeControls() this.UserRow.Visible = false; } } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - try - { - if (this._doRenderTypes) - { - this.DoRenderTypes(); - } - - if (this._doChangeURL) - { - this.DoChangeURL(); - } - - if (this._doReloadFolders || this._doReloadFiles) - { - this.DoCorrectRadioButtonList(); - this._doRenderTypeControls = true; - } - - if (this._doRenderTypeControls) - { - if (!(this._doReloadFolders || this._doReloadFiles)) - { - this.DoCorrectRadioButtonList(); - } - - this.DoRenderTypeControls(); - } - - this.ViewState["Url"] = null; - this.ViewState["IsUrlControlLoaded"] = "Loaded"; - } - catch (Exception exc) - { - // Let's detect possible problems - Exceptions.LogException(new Exception("Error rendering URLControl subcontrols.", exc)); - } - } - - protected void cboFolders_SelectedIndexChanged(object sender, EventArgs e) - { - int PortalId = Null.NullInteger; - - if (!this.IsHostMenu || this.Request.QueryString["pid"] != null) - { - PortalId = this._objPortal.PortalID; - } - - var objFolder = FolderManager.Instance.GetFolder(PortalId, this.cboFolders.SelectedValue); - if (FolderPermissionController.CanAddFolder((FolderInfo)objFolder)) - { - if (!this.txtFile.Visible) - { - this.cmdSave.Visible = false; - - // only show if not already in upload mode and not disabled - this.cmdUpload.Visible = this.ShowUpLoad; - } - } - else - { - // reset controls - this.cboFiles.Visible = true; - this.cmdUpload.Visible = false; - this.txtFile.Visible = false; - this.cmdSave.Visible = false; - this.cmdCancel.Visible = false; - } - - this.cboFiles.Items.Clear(); - this.cboFiles.DataSource = this.GetFileList(!this.Required); - this.cboFiles.DataBind(); - this.SetStorageLocationType(); - if (this.cboFolders.SelectedIndex >= 0) - { - this.ViewState["LastFolderPath"] = this.cboFolders.SelectedValue; - } - else - { - this.ViewState["LastFolderPath"] = string.Empty; - } - - if (this.cboFiles.SelectedIndex >= 0) - { - this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; - } - else - { - this.ViewState["LastFileName"] = string.Empty; - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdAdd_Click(object sender, EventArgs e) - { - this.cboUrls.Visible = false; - this.cmdSelect.Visible = true; - this.txtUrl.Visible = true; - this.cmdAdd.Visible = false; - this.cmdDelete.Visible = false; - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdCancel_Click(object sender, EventArgs e) - { - this.cboFiles.Visible = true; - this.cmdUpload.Visible = true; - this.txtFile.Visible = false; - this.cmdSave.Visible = false; - this.cmdCancel.Visible = false; - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdDelete_Click(object sender, EventArgs e) - { - if (this.cboUrls.SelectedItem != null) - { - var objUrls = new UrlController(); - objUrls.DeleteUrl(this._objPortal.PortalID, this.cboUrls.SelectedItem.Value); - this.LoadUrls(); // we must reload the url list - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdSave_Click(object sender, EventArgs e) - { - this.cmdUpload.Visible = false; - - // if no file is selected exit - if (string.IsNullOrEmpty(this.txtFile.PostedFile.FileName)) - { - return; - } - - string ParentFolderName; - if (Globals.IsHostTab(this.PortalSettings.ActiveTab.TabID)) - { - ParentFolderName = Globals.HostMapPath; - } - else - { - ParentFolderName = this.PortalSettings.HomeDirectoryMapPath; - } - - ParentFolderName += this.cboFolders.SelectedItem.Value; - - string strExtension = Path.GetExtension(this.txtFile.PostedFile.FileName).Replace(".", string.Empty); - if (!string.IsNullOrEmpty(this.FileFilter) && ("," + this.FileFilter.ToLowerInvariant()).IndexOf("," + strExtension.ToLowerInvariant()) == -1) - { - // trying to upload a file not allowed for current filter - this.lblMessage.Text = string.Format(Localization.GetString("UploadError", this.LocalResourceFile), this.FileFilter, strExtension); - this.ErrorRow.Visible = true; - } - else - { - var fileManager = FileManager.Instance; - var folderManager = FolderManager.Instance; - - var settings = PortalController.Instance.GetCurrentPortalSettings(); - var portalID = (settings.ActiveTab.ParentId == settings.SuperTabId) ? Null.NullInteger : settings.PortalId; - - var fileName = Path.GetFileName(this.txtFile.PostedFile.FileName); - var folderPath = Globals.GetSubFolderPath(ParentFolderName.Replace("/", "\\") + fileName, portalID); - - var folder = folderManager.GetFolder(portalID, folderPath); - this.ErrorRow.Visible = false; - - try - { - fileManager.AddFile(folder, fileName, this.txtFile.PostedFile.InputStream, true, true, ((FileManager)fileManager).GetContentType(Path.GetExtension(fileName))); - } - catch (Services.FileSystem.PermissionsNotMetException) - { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("InsufficientFolderPermission"), folder.FolderPath); - this.ErrorRow.Visible = true; - } - catch (NoSpaceAvailableException) - { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("DiskSpaceExceeded"), fileName); - this.ErrorRow.Visible = true; - } - catch (InvalidFileExtensionException) - { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("RestrictedFileType"), fileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - this.ErrorRow.Visible = true; - } - catch (Exception) - { - this.lblMessage.Text += "
    " + string.Format(Localization.GetString("SaveFileError"), fileName); - this.ErrorRow.Visible = true; - } - } - - if (this.lblMessage.Text == string.Empty) - { - this.cboFiles.Visible = true; - this.cmdUpload.Visible = this.ShowUpLoad; - this.txtFile.Visible = false; - this.cmdSave.Visible = false; - this.cmdCancel.Visible = false; - this.ErrorRow.Visible = false; - - var Root = new DirectoryInfo(ParentFolderName); - this.cboFiles.Items.Clear(); - this.cboFiles.DataSource = this.GetFileList(false); - this.cboFiles.DataBind(); - - string FileName = this.txtFile.PostedFile.FileName.Substring(this.txtFile.PostedFile.FileName.LastIndexOf("\\") + 1); - if (this.cboFiles.Items.FindByText(FileName) != null) - { - this.cboFiles.Items.FindByText(FileName).Selected = true; - } - - if (this.cboFiles.SelectedIndex >= 0) - { - this.ViewState["LastFileName"] = this.cboFiles.SelectedValue; - } - else - { - this.ViewState["LastFileName"] = string.Empty; - } - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdSelect_Click(object sender, EventArgs e) - { - this.cboUrls.Visible = true; - this.cmdSelect.Visible = false; - this.txtUrl.Visible = false; - this.cmdAdd.Visible = true; - this.cmdDelete.Visible = PortalSecurity.IsInRole(this._objPortal.AdministratorRoleName); - this.LoadUrls(); - if (this.cboUrls.Items.FindByValue(this.txtUrl.Text) != null) - { - this.cboUrls.ClearSelection(); - this.cboUrls.Items.FindByValue(this.txtUrl.Text).Selected = true; - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void cmdUpload_Click(object sender, EventArgs e) - { - string strSaveFolder = this.cboFolders.SelectedValue; - this.LoadFolders("ADD"); - if (this.cboFolders.Items.FindByValue(strSaveFolder) != null) - { - this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; - this.cboFiles.Visible = false; - this.cmdUpload.Visible = false; - this.txtFile.Visible = true; - this.cmdSave.Visible = true; - this.cmdCancel.Visible = true; - } - else - { - if (this.cboFolders.Items.Count > 0) - { - this.cboFolders.Items[0].Selected = true; - this.cboFiles.Visible = false; - this.cmdUpload.Visible = false; - this.txtFile.Visible = true; - this.cmdSave.Visible = true; - this.cmdCancel.Visible = true; - } - else - { - // reset controls - this.LoadFolders("BROWSE,ADD"); - this.cboFolders.Items.FindByValue(strSaveFolder).Selected = true; - this.cboFiles.Visible = true; - this.cmdUpload.Visible = false; - this.txtFile.Visible = false; - this.cmdSave.Visible = false; - this.cmdCancel.Visible = false; - this.lblMessage.Text = Localization.GetString("NoWritePermission", this.LocalResourceFile); - this.ErrorRow.Visible = true; - } - } - - this._doRenderTypeControls = false; // Must not render on this postback - this._doRenderTypes = false; - this._doChangeURL = false; - this._doReloadFolders = false; - this._doReloadFiles = false; - } - - protected void optType_SelectedIndexChanged(object sender, EventArgs e) - { - // Type changed, render the correct control set - this.ViewState["UrlType"] = this.optType.SelectedItem.Value; - this._doRenderTypeControls = true; - } } } diff --git a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs index eef23c59cfe..1531329f834 100644 --- a/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs +++ b/DNN Platform/Library/UI/UserControls/URLTrackingControl.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.UI.UserControls using Calendar = DotNetNuke.Common.Utilities.Calendar; public abstract class URLTrackingControl : UserControlBase - { + { protected Label Label1; protected Label Label2; protected Label Label3; @@ -28,11 +28,6 @@ public abstract class URLTrackingControl : UserControlBase 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 HyperLink cmdStartCalendar; protected DataGrid grdLog; protected Label lblClicks; @@ -46,15 +41,20 @@ public abstract class URLTrackingControl : UserControlBase protected TextBox txtEndDate; protected TextBox txtStartDate; protected CompareValidator valEndDate; - protected CompareValidator valStartDate; - + protected CompareValidator valStartDate; + private string _FormattedURL = string.Empty; + private int _ModuleID = -2; + private string _TrackingURL = string.Empty; + private string _URL = string.Empty; + private string _localResourceFile; + public string FormattedURL { get { return this._FormattedURL; } - + set { this._FormattedURL = value; @@ -67,7 +67,7 @@ public string TrackingURL { return this._TrackingURL; } - + set { this._TrackingURL = value; @@ -80,7 +80,7 @@ public string URL { return this._URL; } - + set { this._URL = value; @@ -99,10 +99,10 @@ public int ModuleID int.TryParse(this.Request.QueryString["mid"], out moduleID); } } - + return moduleID; } - + set { this._ModuleID = value; @@ -122,16 +122,16 @@ public string LocalResourceFile { fileRoot = this._localResourceFile; } - + return fileRoot; } - + set { this._localResourceFile = value; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -161,7 +161,7 @@ protected override void OnLoad(EventArgs e) this.lblLogURL.Text = "FileID=" + file.FileId; } - + var objUrls = new UrlController(); UrlTrackingInfo objUrlTracking = objUrls.GetUrlTracking(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID); if (objUrlTracking != null) @@ -178,7 +178,7 @@ protected override void OnLoad(EventArgs e) { this.lblURL.Text = this._FormattedURL; } - + this.lblCreatedDate.Text = objUrlTracking.CreatedDate.ToString(); if (objUrlTracking.TrackClicks) @@ -190,21 +190,21 @@ protected override void OnLoad(EventArgs e) { this.lblTrackingURL.Text = Globals.AddHTTP(this.Request.Url.Host); } - + this.lblTrackingURL.Text += Globals.LinkClick(this.URL, this.PortalSettings.ActiveTab.TabID, this.ModuleID, objUrlTracking.TrackClicks); } else { this.lblTrackingURL.Text = this._TrackingURL; } - + this.lblClicks.Text = objUrlTracking.Clicks.ToString(); if (!Null.IsNull(objUrlTracking.LastClick)) { this.lblLastClick.Text = objUrlTracking.LastClick.ToString(); } } - + if (objUrlTracking.LogActivity) { this.pnlLog.Visible = true; @@ -235,15 +235,15 @@ private void cmdDisplay_Click(object sender, EventArgs e) { strStartDate = strStartDate + " 00:00"; } - + string strEndDate = this.txtEndDate.Text; if (!string.IsNullOrEmpty(strEndDate)) { strEndDate = strEndDate + " 23:59"; } - + var objUrls = new UrlController(); - + // localize datagrid Localization.LocalizeDataGrid(ref this.grdLog, this.LocalResourceFile); this.grdLog.DataSource = objUrls.GetUrlLog(this.PortalSettings.PortalId, this.lblLogURL.Text, this.ModuleID, Convert.ToDateTime(strStartDate), Convert.ToDateTime(strEndDate)); @@ -253,6 +253,6 @@ private void cmdDisplay_Click(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Library/UI/UserControls/User.cs b/DNN Platform/Library/UI/UserControls/User.cs index 66889046f13..43a506f7030 100644 --- a/DNN Platform/Library/UI/UserControls/User.cs +++ b/DNN Platform/Library/UI/UserControls/User.cs @@ -19,25 +19,11 @@ namespace DotNetNuke.UI.UserControls /// /// ----------------------------------------------------------------------------- public abstract class User : UserControlBase - { + { protected HtmlTableRow ConfirmPasswordRow; protected HtmlTableRow PasswordRow; - protected Label lblUsername; + protected Label lblUsername; protected Label lblUsernameAsterisk; - private string MyFileName = "User.ascx"; - private string _Confirm; - private string _ControlColumnWidth = string.Empty; - private string _Email; - private string _FirstName; - private string _IM; - private string _LabelColumnWidth = string.Empty; - private string _LastName; - private int _ModuleId; - private string _Password; - private bool _ShowPassword; - private int _StartTabIndex = 1; - private string _UserName; - private string _Website; protected LabelControl plConfirm; protected LabelControl plEmail; protected LabelControl plFirstName; @@ -61,15 +47,37 @@ public abstract class User : UserControlBase protected RequiredFieldValidator valFirstName; protected RequiredFieldValidator valLastName; protected RequiredFieldValidator valPassword; - protected RequiredFieldValidator valUsername; - + protected RequiredFieldValidator valUsername; + private string MyFileName = "User.ascx"; + private string _Confirm; + private string _ControlColumnWidth = string.Empty; + private string _Email; + private string _FirstName; + private string _IM; + private string _LabelColumnWidth = string.Empty; + private string _LastName; + private int _ModuleId; + private string _Password; + private bool _ShowPassword; + private int _StartTabIndex = 1; + private string _UserName; + private string _Website; + + public string LocalResourceFile + { + get + { + return Localization.GetResourceFile(this, this.MyFileName); + } + } + public int ModuleId { get { return Convert.ToInt32(this.ViewState["ModuleId"]); } - + set { this._ModuleId = value; @@ -82,7 +90,7 @@ public string LabelColumnWidth { return Convert.ToString(this.ViewState["LabelColumnWidth"]); } - + set { this._LabelColumnWidth = value; @@ -95,7 +103,7 @@ public string ControlColumnWidth { return Convert.ToString(this.ViewState["ControlColumnWidth"]); } - + set { this._ControlColumnWidth = value; @@ -108,7 +116,7 @@ public string FirstName { return this.txtFirstName.Text; } - + set { this._FirstName = value; @@ -121,7 +129,7 @@ public string LastName { return this.txtLastName.Text; } - + set { this._LastName = value; @@ -134,7 +142,7 @@ public string UserName { return this.txtUsername.Text; } - + set { this._UserName = value; @@ -147,7 +155,7 @@ public string Password { return this.txtPassword.Text; } - + set { this._Password = value; @@ -160,7 +168,7 @@ public string Confirm { return this.txtConfirm.Text; } - + set { this._Confirm = value; @@ -173,7 +181,7 @@ public string Email { return this.txtEmail.Text; } - + set { this._Email = value; @@ -186,7 +194,7 @@ public string Website { return this.txtWebsite.Text; } - + set { this._Website = value; @@ -199,7 +207,7 @@ public string IM { return this.txtIM.Text; } - + set { this._IM = value; @@ -222,14 +230,6 @@ public bool ShowPassword } } - public string LocalResourceFile - { - get - { - return Localization.GetResourceFile(this, this.MyFileName); - } - } - /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -272,7 +272,7 @@ protected override void OnLoad(EventArgs e) this.txtWebsite.Width = Unit.Parse(this._ControlColumnWidth); this.txtIM.Width = Unit.Parse(this._ControlColumnWidth); } - + if (!this._ShowPassword) { this.valPassword.Enabled = false; @@ -297,12 +297,12 @@ protected override void OnLoad(EventArgs e) this.PasswordRow.Visible = true; this.ConfirmPasswordRow.Visible = true; } - + this.ViewState["ModuleId"] = Convert.ToString(this._ModuleId); this.ViewState["LabelColumnWidth"] = this._LabelColumnWidth; this.ViewState["ControlColumnWidth"] = this._ControlColumnWidth; } - + this.txtPassword.Attributes.Add("value", this.txtPassword.Text); this.txtConfirm.Attributes.Add("value", this.txtConfirm.Text); } @@ -310,6 +310,6 @@ protected override void OnLoad(EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Library/UI/Utilities/ClientAPI.cs b/DNN Platform/Library/UI/Utilities/ClientAPI.cs index 6b6a9022de3..ee6dc2b8a9b 100644 --- a/DNN Platform/Library/UI/Utilities/ClientAPI.cs +++ b/DNN Platform/Library/UI/Utilities/ClientAPI.cs @@ -139,12 +139,6 @@ 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); @@ -300,51 +294,6 @@ public static void MinMaxContentVisibile(Control objButton, bool blnDefaultMin, MinMaxContentVisibile(objButton, -1, blnDefaultMin, ePersistanceType, value); } - private static void SetMinMaxProperties(Control objButton, string strImage, string strToolTip, string strAltText) - { - if (objButton is LinkButton) - { - var objLB = (LinkButton)objButton; - objLB.ToolTip = strToolTip; - if (objLB.Controls.Count > 0) - { - SetImageProperties(objLB.Controls[0], strImage, strToolTip, strAltText); - } - } - else if (objButton is Image) - { - SetImageProperties(objButton, strImage, strToolTip, strAltText); - } - else if (objButton is ImageButton) - { - SetImageProperties(objButton, strImage, strToolTip, strAltText); - } - } - - private static void SetImageProperties(Control objControl, string strImage, string strToolTip, string strAltText) - { - if (objControl is Image) - { - var objImage = (Image)objControl; - objImage.ImageUrl = strImage; - objImage.AlternateText = strAltText; - objImage.ToolTip = strToolTip; - } - else if (objControl is ImageButton) - { - var objImage = (ImageButton)objControl; - objImage.ImageUrl = strImage; - objImage.AlternateText = strAltText; - objImage.ToolTip = strToolTip; - } - else if (objControl is HtmlImage) - { - var objImage = (HtmlImage)objControl; - objImage.Src = strImage; - objImage.Alt = strAltText; - } - } - public static bool MinMaxContentVisibile(Control objButton, int intModuleId, bool blnDefaultMin, MinMaxPersistanceType ePersistanceType) { if (HttpContext.Current != null) @@ -456,6 +405,57 @@ public static bool IsPersonalizationKeyRegistered(string strKey) return m_objEnabledClientPersonalizationKeys.ContainsKey(strKey); } + private static void AddBodyOnLoad(Page objPage, string scriptKey, string strJSFunction) + { + JavaScript.RegisterClientReference(objPage, ClientAPI.ClientNamespaceReferences.dnn); + objPage.ClientScript.RegisterStartupScript(objPage.GetType(), scriptKey, strJSFunction, true); + } + + private static void SetMinMaxProperties(Control objButton, string strImage, string strToolTip, string strAltText) + { + if (objButton is LinkButton) + { + var objLB = (LinkButton)objButton; + objLB.ToolTip = strToolTip; + if (objLB.Controls.Count > 0) + { + SetImageProperties(objLB.Controls[0], strImage, strToolTip, strAltText); + } + } + else if (objButton is Image) + { + SetImageProperties(objButton, strImage, strToolTip, strAltText); + } + else if (objButton is ImageButton) + { + SetImageProperties(objButton, strImage, strToolTip, strAltText); + } + } + + private static void SetImageProperties(Control objControl, string strImage, string strToolTip, string strAltText) + { + if (objControl is Image) + { + var objImage = (Image)objControl; + objImage.ImageUrl = strImage; + objImage.AlternateText = strAltText; + objImage.ToolTip = strToolTip; + } + else if (objControl is ImageButton) + { + var objImage = (ImageButton)objControl; + objImage.ImageUrl = strImage; + objImage.AlternateText = strAltText; + objImage.ToolTip = strToolTip; + } + else if (objControl is HtmlImage) + { + var objImage = (HtmlImage)objControl; + objImage.Src = strImage; + objImage.Alt = strAltText; + } + } + private static void AddAttribute(Control objControl, string strName, string strValue) { if (objControl is HtmlControl) diff --git a/DNN Platform/Library/UI/WebControls/ActionLink.cs b/DNN Platform/Library/UI/WebControls/ActionLink.cs index b1827743eda..74fd7ee1bfa 100644 --- a/DNN Platform/Library/UI/WebControls/ActionLink.cs +++ b/DNN Platform/Library/UI/WebControls/ActionLink.cs @@ -25,15 +25,15 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class ActionLink : HyperLink - { + { public ActionLink() { this.RequireEditMode = false; this.Security = "Edit"; this.ControlKey = string.Empty; this.Title = string.Empty; - } - + } + public string Title { get; set; } public string ControlKey { get; set; } @@ -46,8 +46,8 @@ public ActionLink() public bool RequireEditMode { get; set; } - public IModuleControl ModuleControl { get; set; } - + public IModuleControl ModuleControl { get; set; } + /// ----------------------------------------------------------------------------- /// /// CreateChildControls builds the control tree. @@ -61,7 +61,7 @@ protected override void CreateChildControls() // Set Causes Validation and Enables ViewState to false this.EnableViewState = false; } - + /// ----------------------------------------------------------------------------- /// /// OnPreRender runs when just before the Render phase of the Page Lifecycle. @@ -87,8 +87,8 @@ protected override void OnPreRender(EventArgs e) { this.Visible = false; } - } - + } + private bool IsVisible(SecurityAccessLevel security) { bool isVisible = false; @@ -101,6 +101,6 @@ private bool IsVisible(SecurityAccessLevel security) } return isVisible; - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/CaptchaControl.cs b/DNN Platform/Library/UI/WebControls/CaptchaControl.cs index e3cc6b5bca2..219498d9e0e 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 { - internal const string KEY = "captcha"; + 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"; + private const string CHARS_DEFAULT = "abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CaptchaControl)); 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(); @@ -58,21 +58,66 @@ public class CaptchaControl : WebControl, INamingContainer, IPostBackDataHandler private bool _IsValid; private string _RenderUrl = RENDERURL_DEFAULT; private string _UserText = string.Empty; - private Image _image; - + private Image _image; + public CaptchaControl() { this.ErrorMessage = Localization.GetString("InvalidCaptcha", Localization.SharedResourceFile); this.Text = Localization.GetString("CaptchaText.Text", Localization.SharedResourceFile); this._Expiration = HostController.Instance.GetInteger("EXPIRATION_DEFAULT", EXPIRATION_DEFAULT); - } - - public event ServerValidateEventHandler UserValidated; - + } + + public event ServerValidateEventHandler UserValidated; + + /// + /// Gets and sets the BackGroundColor. + /// + [Browsable(true)] + [Category("Appearance")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Error Message Control.")] + public Style ErrorStyle + { + get + { + return this._ErrorStyle; + } + } + + /// + /// Gets a value indicating whether gets whether the control is valid. + /// + [Category("Validation")] + [Description("Returns True if the user was CAPTCHA validated after a postback.")] + public bool IsValid + { + get + { + return this._IsValid; + } + } + + /// + /// Gets the Style to use for the Text Box. + /// + [Browsable(true)] + [Category("Appearance")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Text Box Control.")] + public Style TextBoxStyle + { + get + { + return this._TextBoxStyle; + } + } + /// /// Gets or sets and sets the BackGroundColor. /// - [Category("Appearance")] + [Category("Appearance")] [Description("The Background Color to use for the Captcha Image.")] public Color BackGroundColor { @@ -80,7 +125,7 @@ public Color BackGroundColor { return this._BackGroundColor; } - + set { this._BackGroundColor = value; @@ -90,7 +135,7 @@ public Color BackGroundColor /// /// Gets or sets and sets the BackGround Image. /// - [Category("Appearance")] + [Category("Appearance")] [Description("A Background Image to use for the Captcha Image.")] public string BackGroundImage { @@ -98,26 +143,18 @@ public string BackGroundImage { return this._BackGroundImage; } - + set { this._BackGroundImage = value; } } - - private bool IsDesignMode - { - get - { - return HttpContext.Current == null; - } - } /// /// Gets or sets and sets the list of characters. /// - [Category("Behavior")] - [DefaultValue(CHARS_DEFAULT)] + [Category("Behavior")] + [DefaultValue(CHARS_DEFAULT)] [Description("Characters used to render CAPTCHA text. A character will be picked randomly from the string.")] public string CaptchaChars { @@ -125,7 +162,7 @@ public string CaptchaChars { return this._CaptchaChars; } - + set { this._CaptchaChars = value; @@ -135,7 +172,7 @@ public string CaptchaChars /// /// Gets or sets and sets the height of the Captcha image. /// - [Category("Appearance")] + [Category("Appearance")] [Description("Height of Captcha Image.")] public Unit CaptchaHeight { @@ -143,7 +180,7 @@ public Unit CaptchaHeight { return this._CaptchaHeight; } - + set { this._CaptchaHeight = value; @@ -153,8 +190,8 @@ public Unit CaptchaHeight /// /// Gets or sets and sets the length of the Captcha string. /// - [Category("Behavior")] - [DefaultValue(LENGTH_DEFAULT)] + [Category("Behavior")] + [DefaultValue(LENGTH_DEFAULT)] [Description("Number of CaptchaChars used in the CAPTCHA text")] public int CaptchaLength { @@ -162,7 +199,7 @@ public int CaptchaLength { return this._CaptchaLength; } - + set { this._CaptchaLength = value; @@ -172,7 +209,7 @@ public int CaptchaLength /// /// Gets or sets and sets the width of the Captcha image. /// - [Category("Appearance")] + [Category("Appearance")] [Description("Width of Captcha Image.")] public Unit CaptchaWidth { @@ -180,7 +217,7 @@ public Unit CaptchaWidth { return this._CaptchaWidth; } - + set { this._CaptchaWidth = value; @@ -197,7 +234,7 @@ public override bool EnableViewState { return base.EnableViewState; } - + set { base.EnableViewState = value; @@ -207,32 +244,16 @@ public override bool EnableViewState /// /// Gets or sets and sets the ErrorMessage to display if the control is invalid. /// - [Category("Behavior")] - [Description("The Error Message to display if invalid.")] + [Category("Behavior")] + [Description("The Error Message to display if invalid.")] [DefaultValue("")] - public string ErrorMessage { get; set; } - - /// - /// Gets and sets the BackGroundColor. - /// - [Browsable(true)] - [Category("Appearance")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [Description("Set the Style for the Error Message Control.")] - public Style ErrorStyle - { - get - { - return this._ErrorStyle; - } - } + public string ErrorMessage { get; set; } /// /// Gets or sets and sets the Expiration time in seconds. /// - [Category("Behavior")] - [Description("The duration of time (seconds) a user has before the challenge expires.")] + [Category("Behavior")] + [Description("The duration of time (seconds) a user has before the challenge expires.")] [DefaultValue(EXPIRATION_DEFAULT)] public int Expiration { @@ -240,31 +261,18 @@ public int Expiration { return this._Expiration; } - + set { this._Expiration = value; } } - /// - /// Gets a value indicating whether gets whether the control is valid. - /// - [Category("Validation")] - [Description("Returns True if the user was CAPTCHA validated after a postback.")] - public bool IsValid - { - get - { - return this._IsValid; - } - } - /// /// Gets or sets and sets the Url to use to render the control. /// - [Category("Behavior")] - [Description("The URL used to render the image to the client.")] + [Category("Behavior")] + [Description("The URL used to render the image to the client.")] [DefaultValue(RENDERURL_DEFAULT)] public string RenderUrl { @@ -272,7 +280,7 @@ public string RenderUrl { return this._RenderUrl; } - + set { this._RenderUrl = value; @@ -282,33 +290,25 @@ public string RenderUrl /// /// Gets or sets and sets the Help Text to use. /// - [Category("Captcha")] - [DefaultValue("Enter the code shown above:")] + [Category("Captcha")] + [DefaultValue("Enter the code shown above:")] [Description("Instructional text displayed next to CAPTCHA image.")] public string Text { get; set; } - /// - /// Gets the Style to use for the Text Box. - /// - [Browsable(true)] - [Category("Appearance")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [Description("Set the Style for the Text Box Control.")] - public Style TextBoxStyle + private bool IsDesignMode { get { - return this._TextBoxStyle; + return HttpContext.Current == null; } - } - + } + /// ----------------------------------------------------------------------------- /// /// LoadPostData loads the Post Back Data and determines whether the value has change. /// /// A key to the PostBack Data to load. - /// A name value collection of postback data. + /// A name value collection of postback data. /// /// ----------------------------------------------------------------------------- public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) @@ -319,7 +319,7 @@ public virtual bool LoadPostData(string postDataKey, NameValueCollection postCol { this._CaptchaText = this.GetNextCaptcha(); } - + return false; } @@ -330,12 +330,12 @@ public virtual bool LoadPostData(string postDataKey, NameValueCollection postCol /// ----------------------------------------------------------------------------- public void RaisePostDataChangedEvent() { - } - + } + /// /// Validates the posted back data. /// - /// The user entered data. + /// The user entered data. /// public bool Validate(string userData) { @@ -354,13 +354,13 @@ public bool Validate(string userData) this.OnUserValidated(new ServerValidateEventArgs(this._CaptchaText, this._IsValid)); return this._IsValid; - } + } /// ----------------------------------------------------------------------------- /// /// GenerateImage generates the Captch Image. /// - /// The Encrypted Text to display. + /// The Encrypted Text to display. /// /// ----------------------------------------------------------------------------- internal static Bitmap GenerateImage(string encryptedText) @@ -388,7 +388,7 @@ internal static Bitmap GenerateImage(string encryptedText) { bmp = (Bitmap)System.Drawing.Image.FromFile(HttpContext.Current.Request.MapPath(backgroundImage)); } - + g = Graphics.FromImage(bmp); // Create Text @@ -407,10 +407,10 @@ internal static Bitmap GenerateImage(string encryptedText) { Exceptions.LogException(exc); } - + return bmp; } - + /// /// Creates the child controls. /// @@ -422,14 +422,14 @@ protected override void CreateChildControls() { 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() { @@ -442,7 +442,7 @@ protected virtual string GetNextCaptcha() { 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 @@ -454,7 +454,159 @@ protected virtual string GetNextCaptcha() Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null); return challenge; } - + + /// + /// Loads the previously saved Viewstate. + /// + /// The saved state. + protected override void LoadViewState(object savedState) + { + if (savedState != null) + { + // Load State from the array of objects that was saved at SaveViewState. + var myState = (object[])savedState; + + // Load the ViewState of the Base Control + if (myState[0] != null) + { + base.LoadViewState(myState[0]); + } + + // Load the CAPTCHA Text from the ViewState + if (myState[1] != null) + { + this._CaptchaText = Convert.ToString(myState[1]); + } + } + + // var cacheKey = string.Format(DataCache.CaptchaCacheKey, masterPortalId); + // _CaptchaText + } + + /// + /// Runs just before the control is to be rendered. + /// + protected override void OnPreRender(EventArgs e) + { + // Generate Random Challenge Text + this._CaptchaText = this.GetNextCaptcha(); + + // Enable Viewstate Encryption + this.Page.RegisterRequiresViewStateEncryption(); + + // Call Base Class method + base.OnPreRender(e); + } + + protected virtual void OnUserValidated(ServerValidateEventArgs e) + { + ServerValidateEventHandler handler = this.UserValidated; + if (handler != null) + { + handler(this, e); + } + } + + /// + /// Render the control. + /// + /// An Html Text Writer. + protected override void Render(HtmlTextWriter writer) + { + this.ControlStyle.AddAttributesToRender(writer); + + // Render outer
    Tag + writer.AddAttribute("class", "dnnLeft"); + writer.RenderBeginTag(HtmlTextWriterTag.Div); + + // Render image Tag + writer.AddAttribute(HtmlTextWriterAttribute.Src, this.GetUrl()); + writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); + if (!string.IsNullOrEmpty(this.ToolTip)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Alt, this.ToolTip); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Alt, Localization.GetString("CaptchaAlt.Text", Localization.SharedResourceFile)); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Img); + writer.RenderEndTag(); + + // Render Help Text + if (!string.IsNullOrEmpty(this.Text)) + { + writer.RenderBeginTag(HtmlTextWriterTag.Div); + writer.Write(this.Text); + writer.RenderEndTag(); + } + + // Render text box Tag + this.TextBoxStyle.AddAttributesToRender(writer); + writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); + writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + this.Width); + writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this._CaptchaText.Length.ToString()); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + if (!string.IsNullOrEmpty(this.AccessKey)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, this.AccessKey); + } + + if (!this.Enabled) + { + writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); + } + + if (this.TabIndex > 0) + { + writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex.ToString()); + } + + if (this._UserText == this._CaptchaText) + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, this._UserText); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Value, string.Empty); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + + // Render error message + if (!this.IsValid && this.Page.IsPostBack && !string.IsNullOrEmpty(this._UserText)) + { + this.ErrorStyle.AddAttributesToRender(writer); + writer.RenderBeginTag(HtmlTextWriterTag.Span); + writer.Write(this.ErrorMessage); + writer.RenderEndTag(); + } + + // Render
    + writer.RenderEndTag(); + } + + /// + /// Save the controls Voewstate. + /// + /// + protected override object SaveViewState() + { + var baseState = base.SaveViewState(); + var allStates = new object[2]; + allStates[0] = baseState; + if (string.IsNullOrEmpty(this._CaptchaText)) + { + this._CaptchaText = this.GetNextCaptcha(); + } + + allStates[1] = this._CaptchaText; + + return allStates; + } + /// /// Creates the Image. /// @@ -469,7 +621,7 @@ private static Bitmap CreateImage(int width, int height) g = Graphics.FromImage(bmp); - Brush b = new LinearGradientBrush( + Brush b = new LinearGradientBrush( rect, Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), Color.FromArgb(_Rand.Next(224), _Rand.Next(224), _Rand.Next(224)), @@ -485,7 +637,7 @@ private static Bitmap CreateImage(int width, int height) { DistortImage(ref bmp, -_Rand.Next(5, 20)); } - + return bmp; } @@ -514,11 +666,11 @@ private static GraphicsPath CreateText(string text, int width, int height, Graph { break; } - + f.Dispose(); emSize -= 2; } - + emSize += 8; f = new Font(ff, emSize); @@ -537,39 +689,10 @@ private static GraphicsPath CreateText(string text, int width, int height, Graph { f.Dispose(); } - - 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; + return textPath; } - /// - /// 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(); - } - /// ----------------------------------------------------------------------------- /// /// Decrypts the CAPTCHA Text. @@ -591,7 +714,7 @@ private static string Decrypt(string encryptedContent) { Logger.Debug(exc); } - + return decryptedText; } @@ -618,12 +741,12 @@ private static void DistortImage(ref Bitmap b, double distortion) { newX = 0; } - + if (newY < 0 || newY >= height) { newY = 0; } - + b.SetPixel(x, y, copy.GetPixel(newX, newY)); } } @@ -663,7 +786,7 @@ private static FontFamily GetFont() _font = null; } } - + return _font; } @@ -707,158 +830,35 @@ private static void WarpText(ref GraphicsPath textPath, Rectangle rect) var m = new Matrix(); m.Translate(0, 0); textPath.Warp(points, rectF, m, WarpMode.Perspective, 0); - } - - /// - /// Loads the previously saved Viewstate. - /// - /// The saved state. - protected override void LoadViewState(object savedState) - { - if (savedState != null) - { - // Load State from the array of objects that was saved at SaveViewState. - var myState = (object[])savedState; - - // Load the ViewState of the Base Control - if (myState[0] != null) - { - base.LoadViewState(myState[0]); - } - - // Load the CAPTCHA Text from the ViewState - if (myState[1] != null) - { - this._CaptchaText = Convert.ToString(myState[1]); - } - } - - // var cacheKey = string.Format(DataCache.CaptchaCacheKey, masterPortalId); - // _CaptchaText } /// - /// Runs just before the control is to be rendered. + /// Builds the url for the Handler. /// - protected override void OnPreRender(EventArgs e) + private string GetUrl() { - // Generate Random Challenge Text - this._CaptchaText = this.GetNextCaptcha(); - - // Enable Viewstate Encryption - this.Page.RegisterRequiresViewStateEncryption(); - - // Call Base Class method - base.OnPreRender(e); - } + var url = this.ResolveUrl(this.RenderUrl); + url += "?" + KEY + "=" + Encrypt(this.EncodeTicket(), DateTime.Now.AddSeconds(this.Expiration)); - protected virtual void OnUserValidated(ServerValidateEventArgs e) - { - ServerValidateEventHandler handler = this.UserValidated; - if (handler != null) - { - handler(this, e); - } + // 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; } /// - /// Render the control. + /// Encodes the querystring to pass to the Handler. /// - /// An Html Text Writer. - protected override void Render(HtmlTextWriter writer) + private string EncodeTicket() { - this.ControlStyle.AddAttributesToRender(writer); - - // Render outer
    Tag - writer.AddAttribute("class", "dnnLeft"); - writer.RenderBeginTag(HtmlTextWriterTag.Div); - - // Render image Tag - writer.AddAttribute(HtmlTextWriterAttribute.Src, this.GetUrl()); - writer.AddAttribute(HtmlTextWriterAttribute.Border, "0"); - if (!string.IsNullOrEmpty(this.ToolTip)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Alt, this.ToolTip); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Alt, Localization.GetString("CaptchaAlt.Text", Localization.SharedResourceFile)); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Img); - writer.RenderEndTag(); - - // Render Help Text - if (!string.IsNullOrEmpty(this.Text)) - { - writer.RenderBeginTag(HtmlTextWriterTag.Div); - writer.Write(this.Text); - writer.RenderEndTag(); - } - - // Render text box Tag - this.TextBoxStyle.AddAttributesToRender(writer); - writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); - writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + this.Width); - writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, this._CaptchaText.Length.ToString()); - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); - if (!string.IsNullOrEmpty(this.AccessKey)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Accesskey, this.AccessKey); - } - - if (!this.Enabled) - { - writer.AddAttribute(HtmlTextWriterAttribute.Disabled, "disabled"); - } - - if (this.TabIndex > 0) - { - writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex.ToString()); - } - - if (this._UserText == this._CaptchaText) - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, this._UserText); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Value, string.Empty); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); + var sb = new StringBuilder(); - // Render error message - if (!this.IsValid && this.Page.IsPostBack && !string.IsNullOrEmpty(this._UserText)) - { - this.ErrorStyle.AddAttributesToRender(writer); - writer.RenderBeginTag(HtmlTextWriterTag.Span); - writer.Write(this.ErrorMessage); - writer.RenderEndTag(); - } + sb.Append(this.CaptchaWidth.Value.ToString()); + sb.Append(_Separator + this.CaptchaHeight.Value); + sb.Append(_Separator + this._CaptchaText); + sb.Append(_Separator + this.BackGroundImage); - // Render
    - writer.RenderEndTag(); + return sb.ToString(); } - - /// - /// Save the controls Voewstate. - /// - /// - protected override object SaveViewState() - { - var baseState = base.SaveViewState(); - var allStates = new object[2]; - allStates[0] = baseState; - if (string.IsNullOrEmpty(this._CaptchaText)) - { - this._CaptchaText = this.GetNextCaptcha(); - } - - allStates[1] = this._CaptchaText; - - return allStates; - } } } diff --git a/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs b/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs index 4f34a986823..e020c068899 100644 --- a/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs +++ b/DNN Platform/Library/UI/WebControls/CaptchaHandler.cs @@ -20,8 +20,8 @@ namespace DotNetNuke.UI.WebControls public class CaptchaHandler : IHttpHandler { private const int MAX_IMAGE_WIDTH = 600; - private const int MAX_IMAGE_HEIGHT = 600; - + private const int MAX_IMAGE_HEIGHT = 600; + public bool IsReusable { get @@ -40,6 +40,6 @@ public void ProcessRequest(HttpContext context) { bmp.Save(response.OutputStream, ImageFormat.Jpeg); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/CommandButton.cs b/DNN Platform/Library/UI/WebControls/CommandButton.cs index 72f7f951b65..444d3a3dac7 100644 --- a/DNN Platform/Library/UI/WebControls/CommandButton.cs +++ b/DNN Platform/Library/UI/WebControls/CommandButton.cs @@ -29,7 +29,7 @@ public class CommandButton : WebControl, INamingContainer private LiteralControl separator; public event EventHandler Click; - + public event CommandEventHandler Command; /// ----------------------------------------------------------------------------- @@ -46,7 +46,7 @@ public string ButtonSeparator this.EnsureChildControls(); return this.separator.Text; } - + set { this.EnsureChildControls(); @@ -68,7 +68,7 @@ public bool CausesValidation this.EnsureChildControls(); return this.link.CausesValidation; } - + set { this.EnsureChildControls(); @@ -90,7 +90,7 @@ public string CommandArgument this.EnsureChildControls(); return this.link.CommandArgument; } - + set { this.EnsureChildControls(); @@ -112,7 +112,7 @@ public string CommandName this.EnsureChildControls(); return this.link.CommandName; } - + set { this.EnsureChildControls(); @@ -135,7 +135,7 @@ public bool DisplayLink this.EnsureChildControls(); return this.link.Visible; } - + set { this.EnsureChildControls(); @@ -157,7 +157,7 @@ public bool DisplayIcon this.EnsureChildControls(); return this.icon.Visible; } - + set { this.EnsureChildControls(); @@ -176,14 +176,14 @@ public string ImageUrl get { this.EnsureChildControls(); - if (string.IsNullOrEmpty(this.icon.ImageUrl)) - { - this.icon.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); - } - + if (string.IsNullOrEmpty(this.icon.ImageUrl)) + { + this.icon.ImageUrl = Entities.Icons.IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); + } + return this.icon.ImageUrl; } - + set { this.EnsureChildControls(); @@ -228,7 +228,7 @@ public string OnClick this.EnsureChildControls(); return this.link.Attributes["onclick"]; } - + set { this.EnsureChildControls(); @@ -258,7 +258,7 @@ public string OnClientClick this.EnsureChildControls(); return this.link.OnClientClick; } - + set { this.EnsureChildControls(); @@ -280,7 +280,7 @@ public string ResourceKey this.EnsureChildControls(); return this.link.Attributes["resourcekey"]; } - + set { this.EnsureChildControls(); @@ -310,7 +310,7 @@ public string Text this.EnsureChildControls(); return this.link.Text; } - + set { this.EnsureChildControls(); @@ -339,7 +339,7 @@ public string ValidationGroup this.EnsureChildControls(); return this.link.ValidationGroup; } - + set { this.EnsureChildControls(); @@ -371,7 +371,7 @@ protected override void CreateChildControls() { this.CssClass = "CommandButton"; } - + this.icon = new ImageButton(); this.icon.Visible = true; this.icon.CausesValidation = true; @@ -391,7 +391,7 @@ protected override void CreateChildControls() { this.icon.EnableViewState = this.EnableViewState; } - + if (this.DisplayLink) { this.link.CssClass = this.CssClass; diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs index c3f03deafca..3169226d222 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumn.cs @@ -18,26 +18,26 @@ namespace DotNetNuke.UI.WebControls ///
    /// ----------------------------------------------------------------------------- public class CheckBoxColumn : TemplateColumn - { + { private bool mAutoPostBack = true; private string mDataField = Null.NullString; private bool mEnabled = true; private string mEnabledField = Null.NullString; - private bool mHeaderCheckBox = true; - + private bool mHeaderCheckBox = true; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the CheckBoxColumn. /// /// ----------------------------------------------------------------------------- - public CheckBoxColumn() + public CheckBoxColumn() : this(false) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the CheckBoxColumn, with an optional AutoPostBack (where each change /// of state of a check box causes a Post Back). @@ -47,10 +47,10 @@ public CheckBoxColumn() public CheckBoxColumn(bool autoPostBack) { this.AutoPostBack = autoPostBack; - } - - public event DNNDataGridCheckedColumnEventHandler CheckedChanged; - + } + + 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 @@ -64,7 +64,7 @@ public bool AutoPostBack { return this.mAutoPostBack; } - + set { this.mAutoPostBack = value; @@ -92,7 +92,7 @@ public string DataField { return this.mDataField; } - + set { this.mDataField = value; @@ -113,7 +113,7 @@ public bool Enabled { return this.mEnabled; } - + set { this.mEnabled = value; @@ -133,7 +133,7 @@ public string EnabledField { return this.mEnabledField; } - + set { this.mEnabledField = value; @@ -153,13 +153,13 @@ public bool HeaderCheckBox { return this.mHeaderCheckBox; } - + set { this.mHeaderCheckBox = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Initialises the Column. @@ -176,11 +176,11 @@ public override void Initialize() this.HeaderStyle.Font.Size = new FontUnit("10pt"); this.HeaderStyle.Font.Bold = true; } - + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; - } - + } + /// ----------------------------------------------------------------------------- /// /// Creates a CheckBoxColumnTemplate. @@ -194,13 +194,13 @@ private CheckBoxColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } - + var template = new CheckBoxColumnTemplate(type); if (type != ListItemType.Header) { template.AutoPostBack = this.AutoPostBack; } - + template.Checked = this.Checked; template.DataField = this.DataField; template.Enabled = this.Enabled; @@ -212,7 +212,7 @@ private CheckBoxColumnTemplate CreateTemplate(ListItemType type) template.AutoPostBack = true; template.HeaderCheckBox = this.HeaderCheckBox; } - + template.DesignMode = isDesignMode; return template; } @@ -230,6 +230,6 @@ private void OnCheckedChanged(object sender, DNNDataGridCheckChangedEventArgs e) { this.CheckedChanged(sender, e); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs index 5cf30065a67..7c5d0ca9333 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/CheckBoxColumnTemplate.cs @@ -27,7 +27,7 @@ public class CheckBoxColumnTemplate : ITemplate private ListItemType mItemType = ListItemType.Item; private string mText = string.Empty; - public CheckBoxColumnTemplate() + public CheckBoxColumnTemplate() : this(ListItemType.Item) { } @@ -35,10 +35,10 @@ public CheckBoxColumnTemplate() public CheckBoxColumnTemplate(ListItemType itemType) { this.ItemType = itemType; - } - + } + 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 @@ -46,8 +46,8 @@ public CheckBoxColumnTemplate(ListItemType itemType) /// /// A Boolean. /// ----------------------------------------------------------------------------- - public bool AutoPostBack { get; set; } - + public bool AutoPostBack { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and sets whether the checkbox is checked (unless DataBound). @@ -68,13 +68,13 @@ public string DataField { return this.mDataField; } - + set { this.mDataField = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets or sets the Design Mode of the Column. @@ -97,7 +97,7 @@ public bool Enabled { return this.mEnabled; } - + set { this.mEnabled = value; @@ -117,7 +117,7 @@ public string EnabledField { return this.mEnabledField; } - + set { this.mEnabledField = value; @@ -137,7 +137,7 @@ public bool HeaderCheckBox { return this.mHeaderCheckBox; } - + set { this.mHeaderCheckBox = value; @@ -156,7 +156,7 @@ public ListItemType ItemType { return this.mItemType; } - + set { this.mItemType = value; @@ -175,13 +175,13 @@ public string Text { return this.mText; } - + set { this.mText = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// InstantiateIn is called when the Template is instantiated by the parent control. @@ -194,7 +194,7 @@ public void InstantiateIn(Control container) { container.Controls.Add(new LiteralControl(this.Text + "
    ")); } - + if (this.ItemType != ListItemType.Header || (this.ItemType == ListItemType.Header && this.HeaderCheckBox)) { var box = new CheckBox(); @@ -203,7 +203,7 @@ public void InstantiateIn(Control container) box.CheckedChanged += this.OnCheckChanged; container.Controls.Add(box); } - } + } /// ----------------------------------------------------------------------------- /// @@ -229,7 +229,7 @@ private void Item_DataBinding(object sender, EventArgs e) { box.Checked = this.Checked; } - + if (!string.IsNullOrEmpty(this.EnabledField)) { if (this.DesignMode) @@ -265,7 +265,7 @@ private void OnCheckChanged(object sender, EventArgs e) { evntArgs = new DNNDataGridCheckChangedEventArgs(container, box.Checked, this.DataField, false); } - + if (this.CheckedChanged != null) { this.CheckedChanged(sender, evntArgs); diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs index d319fc5fb81..1309fbc99c9 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGrid.cs @@ -19,9 +19,9 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class DNNDataGrid : DataGrid - { - public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged; - + { + public event DNNDataGridCheckedColumnEventHandler ItemCheckedChanged; + /// ----------------------------------------------------------------------------- /// /// Called when the grid is Data Bound. @@ -44,7 +44,12 @@ protected override void CreateControlHierarchy(bool useDataSource) { base.CreateControlHierarchy(useDataSource); } - + + protected override void PrepareControlHierarchy() + { + base.PrepareControlHierarchy(); + } + /// ----------------------------------------------------------------------------- /// /// Centralised Event that is raised whenever a check box is changed. @@ -56,11 +61,6 @@ private void OnItemCheckedChanged(object sender, DNNDataGridCheckChangedEventArg { this.ItemCheckedChanged(sender, e); } - } - - protected override void PrepareControlHierarchy() - { - base.PrepareControlHierarchy(); - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs index 2b20407e6fc..7706a70d246 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNDataGridCheckChangedEventArgs.cs @@ -21,12 +21,12 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- public class DNNDataGridCheckChangedEventArgs : DataGridItemEventArgs { - public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field) + public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field) : this(item, isChecked, field, false) { } - public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field, bool isAll) + public DNNDataGridCheckChangedEventArgs(DataGridItem item, bool isChecked, string field, bool isAll) : base(item) { this.Checked = isChecked; diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs index 9af0684d9a4..a6ffa0cd29e 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumn.cs @@ -25,21 +25,21 @@ public class DNNMultiStateBoxColumn : TemplateColumn private string mEnabledField = Null.NullString; private string mImagePath = string.Empty; private string mSelectedStateKey = string.Empty; - private DNNMultiStateCollection mStates; - + private DNNMultiStateCollection mStates; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the DNNMultiStateBoxColumn. /// /// ----------------------------------------------------------------------------- - public DNNMultiStateBoxColumn() + public DNNMultiStateBoxColumn() : this(false) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs the MultiStateBoxColumn, with an optional AutoPostBack (where each change /// of state of the control causes a Post Back). @@ -63,7 +63,7 @@ public bool AutoPostBack { return this.mAutoPostBack; } - + set { this.mAutoPostBack = value; @@ -82,7 +82,7 @@ public string SelectedStateKey { return this.mSelectedStateKey; } - + set { this.mSelectedStateKey = value; @@ -102,7 +102,7 @@ public string DataField { return this.mDataField; } - + set { this.mDataField = value; @@ -123,7 +123,7 @@ public bool Enabled { return this.mEnabled; } - + set { this.mEnabled = value; @@ -143,7 +143,7 @@ public string EnabledField { return this.mEnabledField; } - + set { this.mEnabledField = value; @@ -162,7 +162,7 @@ public string ImagePath { return this.mImagePath; } - + set { this.mImagePath = value; @@ -183,10 +183,10 @@ public DNNMultiStateCollection States { this.mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); } - + return this.mStates; } - + set { this.mStates = value; @@ -209,7 +209,7 @@ public override void Initialize() this.HeaderStyle.Font.Size = new FontUnit("10pt"); this.HeaderStyle.Font.Bold = true; } - + this.ItemStyle.HorizontalAlign = HorizontalAlign.Center; this.HeaderStyle.HorizontalAlign = HorizontalAlign.Center; } @@ -227,13 +227,13 @@ private DNNMultiStateBoxColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } - + var template = new DNNMultiStateBoxColumnTemplate(type); if (type != ListItemType.Header) { template.AutoPostBack = this.AutoPostBack; } - + template.DataField = this.DataField; template.Enabled = this.Enabled; template.EnabledField = this.EnabledField; @@ -242,14 +242,14 @@ private DNNMultiStateBoxColumnTemplate CreateTemplate(ListItemType type) { template.States.Add(objState); } - + template.SelectedStateKey = this.SelectedStateKey; if (type == ListItemType.Header) { template.Text = this.HeaderText; template.AutoPostBack = true; } - + template.DesignMode = isDesignMode; return template; } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs index c8e56062db8..80710062234 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/DNNMultiStateBoxColumnTemplate.cs @@ -29,7 +29,7 @@ public class DNNMultiStateBoxColumnTemplate : ITemplate private DNNMultiStateCollection mStates; private string mText = string.Empty; - public DNNMultiStateBoxColumnTemplate() + public DNNMultiStateBoxColumnTemplate() : this(ListItemType.Item) { } @@ -59,7 +59,7 @@ public string SelectedStateKey { return this.mSelectedStateKey; } - + set { this.mSelectedStateKey = value; @@ -78,7 +78,7 @@ public string DataField { return this.mDataField; } - + set { this.mDataField = value; @@ -107,7 +107,7 @@ public bool Enabled { return this.mEnabled; } - + set { this.mEnabled = value; @@ -127,7 +127,7 @@ public string EnabledField { return this.mEnabledField; } - + set { this.mEnabledField = value; @@ -146,7 +146,7 @@ public ListItemType ItemType { return this.mItemType; } - + set { this.mItemType = value; @@ -165,7 +165,7 @@ public string Text { return this.mText; } - + set { this.mText = value; @@ -184,7 +184,7 @@ public string ImagePath { return this.mImagePath; } - + set { this.mImagePath = value; @@ -205,16 +205,16 @@ public DNNMultiStateCollection States { this.mStates = new DNNMultiStateCollection(new DNNMultiStateBox()); } - + return this.mStates; } - + set { this.mStates = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// InstantiateIn is called when the Template is instantiated by the parent control. @@ -227,7 +227,7 @@ public void InstantiateIn(Control container) { container.Controls.Add(new LiteralControl(this.Text + "
    ")); } - + if (this.ItemType != ListItemType.Header) { var box = new DNNMultiStateBox(); @@ -237,12 +237,12 @@ public void InstantiateIn(Control container) { box.States.Add(objState); } - + box.DataBinding += this.Item_DataBinding; container.Controls.Add(box); } - } - + } + /// ----------------------------------------------------------------------------- /// /// Called when the template item is Data Bound. @@ -267,7 +267,7 @@ private void Item_DataBinding(object sender, EventArgs e) { box.SelectedStateKey = this.SelectedStateKey; } - + if (!string.IsNullOrEmpty(this.EnabledField)) { if (this.DesignMode) diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs index b0d3b232138..febb5695321 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumn.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.UI.WebControls public class ImageCommandColumn : TemplateColumn { private ImageCommandColumnEditMode _editMode = ImageCommandColumnEditMode.Command; - private bool _showImage = true; + private bool _showImage = true; private string _imageURL = string.Empty; /// @@ -24,7 +24,7 @@ public class ImageCommandColumn : TemplateColumn /// /// A String. public string CommandName { get; set; } - + /// /// Gets or sets editMode for the Column. /// @@ -34,7 +34,7 @@ public ImageCommandColumnEditMode EditMode get { return this._editMode; } set { this._editMode = value; } } - + /// /// Gets or sets the URL of the Image. /// @@ -50,55 +50,55 @@ public string ImageURL return IconController.IconURL(this.IconKey, this.IconSize, this.IconStyle); } - + set { this._imageURL = value; } } - + /// /// Gets or sets the Icon Key to obtain ImageURL. /// /// A String. public string IconKey { get; set; } - + /// /// Gets or sets the Icon Siz to obtain ImageURL. /// /// A String. public string IconSize { get; set; } - + /// /// Gets or sets the Icon Style to obtain ImageURL. /// /// A String. public string IconStyle { get; set; } - + /// /// Gets or sets the Key Field that provides a Unique key to the data Item. /// /// A String. public string KeyField { get; set; } - + /// /// Gets or sets the URL of the Link (unless DataBinding through KeyField). /// /// A String. public string NavigateURL { get; set; } - + /// /// Gets or sets the URL Formatting string. /// /// A String. public string NavigateURLFormatString { get; set; } - + /// /// Gets or sets javascript text to attach to the OnClick Event. /// /// A String. // ReSharper disable InconsistentNaming - public string OnClickJS { get; set; } - - // ReSharper restore InconsistentNaming - + public string OnClickJS { get; set; } + + // ReSharper restore InconsistentNaming + /// /// Gets or sets a value indicating whether gets or sets whether an Image is displayed. /// @@ -109,19 +109,19 @@ public bool ShowImage get { return this._showImage; } set { this._showImage = value; } } - + /// /// Gets or sets the Text (for Header/Footer Templates). /// /// A String. public string Text { get; set; } - + /// /// Gets or sets an flag that indicates whether the buttons are visible. /// /// A Boolean. public string VisibleField { get; set; } - + /// /// Initialises the Column. /// @@ -137,11 +137,11 @@ public override void Initialize() 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. /// @@ -160,7 +160,7 @@ private ImageCommandColumnTemplate CreateTemplate(ListItemType type) template.KeyField = this.KeyField; } } - + template.EditMode = this.EditMode; template.NavigateURL = this.NavigateURL; template.NavigateURLFormatString = this.NavigateURLFormatString; @@ -174,6 +174,6 @@ private ImageCommandColumnTemplate CreateTemplate(ListItemType type) template.DesignMode = isDesignMode; return template; - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs index c9ed387dc70..0ad3350d081 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/ImageCommandColumnTemplate.cs @@ -20,13 +20,13 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class ImageCommandColumnTemplate : ITemplate - { + { private ImageCommandColumnEditMode mEditMode = ImageCommandColumnEditMode.Command; private ListItemType mItemType = ListItemType.Item; private bool mShowImage = true; - private bool mVisible = true; - - public ImageCommandColumnTemplate() + private bool mVisible = true; + + public ImageCommandColumnTemplate() : this(ListItemType.Item) { } @@ -34,8 +34,8 @@ public ImageCommandColumnTemplate() public ImageCommandColumnTemplate(ListItemType itemType) { this.ItemType = itemType; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the CommandName for the Column. @@ -64,7 +64,7 @@ public ImageCommandColumnEditMode EditMode { return this.mEditMode; } - + set { this.mEditMode = value; @@ -91,7 +91,7 @@ public ListItemType ItemType { return this.mItemType; } - + set { this.mItemType = value; @@ -143,7 +143,7 @@ public bool ShowImage { return this.mShowImage; } - + set { this.mShowImage = value; @@ -172,7 +172,7 @@ public bool Visible { return this.mVisible; } - + set { this.mVisible = value; @@ -185,8 +185,8 @@ public bool Visible /// /// A Boolean. /// ----------------------------------------------------------------------------- - public string VisibleField { get; set; } - + public string VisibleField { get; set; } + /// ----------------------------------------------------------------------------- /// /// InstantiateIn instantiates the template (implementation of ITemplate). @@ -218,7 +218,7 @@ public void InstantiateIn(Control container) { img.ImageUrl = this.ImageURL; } - + hypLink.Controls.Add(img); img.ToolTip = this.Text; } @@ -226,7 +226,7 @@ public void InstantiateIn(Control container) { hypLink.Text = this.Text; } - + hypLink.DataBinding += this.Item_DataBinding; container.Controls.Add(hypLink); } @@ -243,18 +243,18 @@ public void InstantiateIn(Control container) { colIcon.ImageUrl = this.ImageURL; } - + colIcon.ToolTip = this.Text; if (!string.IsNullOrEmpty(this.OnClickJS)) { ClientAPI.AddButtonConfirm(colIcon, this.OnClickJS); } - + colIcon.CommandName = this.CommandName; colIcon.DataBinding += this.Item_DataBinding; container.Controls.Add(colIcon); } - + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { var colLink = new LinkButton(); @@ -263,22 +263,22 @@ public void InstantiateIn(Control container) { ClientAPI.AddButtonConfirm(colLink, this.OnClickJS); } - + colLink.CommandName = this.CommandName; colLink.Text = this.Text; colLink.DataBinding += this.Item_DataBinding; container.Controls.Add(colLink); } } - + break; case ListItemType.Footer: case ListItemType.Header: container.Controls.Add(new LiteralControl(this.Text)); break; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets whether theButton is visible. @@ -296,7 +296,7 @@ private bool GetIsVisible(DataGridItem container) { isVisible = this.Visible; } - + return isVisible; } @@ -313,7 +313,7 @@ private int GetValue(DataGridItem container) { keyValue = Convert.ToInt32(DataBinder.Eval(container.DataItem, this.KeyField)); } - + return keyValue; } @@ -355,7 +355,7 @@ private void Item_DataBinding(object sender, EventArgs e) colIcon.CommandArgument = keyValue.ToString(); colIcon.Visible = this.GetIsVisible(container); } - + if (!string.IsNullOrEmpty(this.Text) && !this.ShowImage) { // Bind Link Button @@ -366,6 +366,6 @@ private void Item_DataBinding(object sender, EventArgs e) colLink.Visible = this.GetIsVisible(container); } } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs index 90535849472..d9034776f09 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriState.cs @@ -45,6 +45,10 @@ public PermissionTriState() // value on postback is undefined at this time public bool Locked { get; set; } + public string PermissionKey { get; set; } + + public bool SupportsDenyMode { get; set; } + public static void RegisterScripts(Page page, Control ctl) { const string scriptKey = "initTriState"; @@ -119,7 +123,7 @@ protected override void Render(HtmlTextWriter writer) { imagePath = this._lockImagePath; cssClass += " lockedPerm"; - + // altText is set based on Value } @@ -160,9 +164,5 @@ private static void LookupScriptValues(Control ctl, out string grantImagePath, o denyAltText = Localization.GetString("PermissionTypeDeny"); nullAltText = Localization.GetString("PermissionTypeNull"); } - - public string PermissionKey { get; set; } - - public bool SupportsDenyMode { get; set; } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs index 30823300871..28cac7304dc 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/PermissionTriStateTemplate.cs @@ -25,7 +25,7 @@ public PermissionTriStateTemplate(PermissionInfo permission) public bool IsView { get; set; } public bool SupportDenyMode { get; set; } - + public void InstantiateIn(Control container) { var triState = new PermissionTriState(); diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs index d84016d99bd..45771578256 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/RolesSelectionGrid.cs @@ -23,15 +23,15 @@ namespace DotNetNuke.UI.WebControls using DotNetNuke.Services.Localization; public class RolesSelectionGrid : Control, INamingContainer - { + { private readonly DataTable _dtRoleSelections = new DataTable(); private IList _roles; private IList _selectedRoles; private DropDownList cboRoleGroups; private DataGrid dgRoleSelection; private Label lblGroups; - private Panel pnlRoleSlections; - + private Panel pnlRoleSlections; + public TableItemStyle AlternatingItemStyle { get @@ -40,93 +40,93 @@ public TableItemStyle AlternatingItemStyle } } - public bool AutoGenerateColumns + public DataGridColumnCollection Columns { get { - return this.dgRoleSelection.AutoGenerateColumns; + return this.dgRoleSelection.Columns; } - - set + } + + public TableItemStyle FooterStyle + { + get { - this.dgRoleSelection.AutoGenerateColumns = value; + return this.dgRoleSelection.FooterStyle; } } - public int CellSpacing + public TableItemStyle HeaderStyle { get { - return this.dgRoleSelection.CellSpacing; + return this.dgRoleSelection.HeaderStyle; } - - set + } + + public TableItemStyle ItemStyle + { + get { - this.dgRoleSelection.CellSpacing = value; + return this.dgRoleSelection.ItemStyle; } } - public DataGridColumnCollection Columns + public DataGridItemCollection Items { get { - return this.dgRoleSelection.Columns; + return this.dgRoleSelection.Items; } } - public TableItemStyle FooterStyle + public TableItemStyle SelectedItemStyle { get { - return this.dgRoleSelection.FooterStyle; + return this.dgRoleSelection.SelectedItemStyle; } } - public GridLines GridLines + public bool AutoGenerateColumns { get { - return this.dgRoleSelection.GridLines; + return this.dgRoleSelection.AutoGenerateColumns; } - + set { - this.dgRoleSelection.GridLines = value; + this.dgRoleSelection.AutoGenerateColumns = value; } } - public TableItemStyle HeaderStyle + public int CellSpacing { get { - return this.dgRoleSelection.HeaderStyle; + return this.dgRoleSelection.CellSpacing; } - } - public TableItemStyle ItemStyle - { - get + set { - return this.dgRoleSelection.ItemStyle; + this.dgRoleSelection.CellSpacing = value; } } - public DataGridItemCollection Items + public GridLines GridLines { get { - return this.dgRoleSelection.Items; + return this.dgRoleSelection.GridLines; } - } - public TableItemStyle SelectedItemStyle - { - get + set { - return this.dgRoleSelection.SelectedItemStyle; + this.dgRoleSelection.GridLines = value; } - } - + } + /// /// Gets or sets list of the Names of the selected Roles. /// @@ -137,13 +137,13 @@ public ArrayList SelectedRoleNames this.UpdateRoleSelections(); return new ArrayList(this.CurrentRoleSelection.ToArray()); } - + set { this.CurrentRoleSelection = value.Cast().ToList(); } - } - + } + /// /// Gets or sets and Sets the ResourceFile to localize permissions. /// @@ -160,10 +160,10 @@ public bool ShowUnauthenticatedUsers { return false; } - + return Convert.ToBoolean(this.ViewState["ShowUnauthenticatedUsers"]); } - + set { this.ViewState["ShowUnauthenticatedUsers"] = value; @@ -181,16 +181,16 @@ public bool ShowAllUsers { return false; } - + return Convert.ToBoolean(this.ViewState["ShowAllUsers"]); } - + set { this.ViewState["ShowAllUsers"] = value; } - } - + } + private DataTable dtRolesSelection { get @@ -205,13 +205,13 @@ private IList CurrentRoleSelection { return this._selectedRoles ?? (this._selectedRoles = new List()); } - + set { this._selectedRoles = value; } - } - + } + /// /// Load the ViewState. /// @@ -242,7 +242,7 @@ protected override void LoadViewState(object savedState) /// /// Saves the ViewState. - /// + /// /// protected override object SaveViewState() { @@ -250,7 +250,7 @@ protected override object SaveViewState() // Save the Base Controls ViewState allStates[0] = base.SaveViewState(); - + // Persist the TabPermisisons var sb = new StringBuilder(); bool addDelimiter = false; @@ -264,117 +264,13 @@ protected override object SaveViewState() { addDelimiter = true; } - + sb.Append(role); } - + allStates[1] = sb.ToString(); return allStates; } - - /// - /// Bind the data to the controls. - /// - private void BindData() - { - this.EnsureChildControls(); - - this.BindRolesGrid(); - } - - /// - /// Bind the Roles data to the Grid. - /// - private void BindRolesGrid() - { - this.dtRolesSelection.Columns.Clear(); - this.dtRolesSelection.Rows.Clear(); - - // Add Roles Column - var col = new DataColumn("RoleId", typeof(string)); - this.dtRolesSelection.Columns.Add(col); - - // Add Roles Column - col = new DataColumn("RoleName", typeof(string)); - this.dtRolesSelection.Columns.Add(col); - - // Add Selected Column - col = new DataColumn("Selected", typeof(bool)); - this.dtRolesSelection.Columns.Add(col); - - this.GetRoles(); - - this.UpdateRoleSelections(); - for (int i = 0; i <= this._roles.Count - 1; i++) - { - var role = this._roles[i]; - DataRow row = this.dtRolesSelection.NewRow(); - row["RoleId"] = role.RoleID; - row["RoleName"] = Localization.LocalizeRole(role.RoleName); - row["Selected"] = this.GetSelection(role.RoleName); - - this.dtRolesSelection.Rows.Add(row); - } - - this.dgRoleSelection.DataSource = this.dtRolesSelection; - this.dgRoleSelection.DataBind(); - } - - private bool GetSelection(string roleName) - { - return this.CurrentRoleSelection.Any(r => r == roleName); - } - - /// - /// Gets the roles from the Database and loads them into the Roles property. - /// - private void GetRoles() - { - int roleGroupId = -2; - if ((this.cboRoleGroups != null) && (this.cboRoleGroups.SelectedValue != null)) - { - roleGroupId = int.Parse(this.cboRoleGroups.SelectedValue); - } - - this._roles = roleGroupId > -2 - ? RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) - : RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); - - if (roleGroupId < 0) - { - if (this.ShowUnauthenticatedUsers) - { - this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser), RoleName = Globals.glbRoleUnauthUserName }); - } - - if (this.ShowAllUsers) - { - this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }); - } - } - - this._roles = this._roles.OrderBy(r => r.RoleName).ToList(); - } - - /// - /// Sets up the columns for the Grid. - /// - private void SetUpRolesGrid() - { - this.dgRoleSelection.Columns.Clear(); - var textCol = new BoundColumn { HeaderText = " ", DataField = "RoleName" }; - textCol.ItemStyle.Width = Unit.Parse("150px"); - this.dgRoleSelection.Columns.Add(textCol); - var idCol = new BoundColumn { HeaderText = string.Empty, DataField = "roleid", Visible = false }; - this.dgRoleSelection.Columns.Add(idCol); - var checkCol = new TemplateColumn(); - var columnTemplate = new CheckBoxColumnTemplate { DataField = "Selected" }; - checkCol.ItemTemplate = columnTemplate; - checkCol.HeaderText = Localization.GetString("SelectedRole"); - checkCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center; - checkCol.HeaderStyle.Wrap = true; - this.dgRoleSelection.Columns.Add(checkCol); - } /// /// Creates the Child Controls. @@ -402,12 +298,12 @@ protected override void CreateChildControls() { this.cboRoleGroups.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString(CultureInfo.InvariantCulture))); } - + this.pnlRoleSlections.Controls.Add(this.cboRoleGroups); this.pnlRoleSlections.Controls.Add(new LiteralControl("

    ")); } - + this.dgRoleSelection = new DataGrid { AutoGenerateColumns = false, CellSpacing = 0, GridLines = GridLines.None }; this.dgRoleSelection.FooterStyle.CssClass = "dnnGridFooter"; this.dgRoleSelection.HeaderStyle.CssClass = "dnnGridHeader"; @@ -445,7 +341,7 @@ protected virtual void UpdateSelection(string roleName, bool Selected) // Remove from collection as we only keep selected roles this.CurrentRoleSelection.Remove(currentRoleName); } - + isMatch = true; break; } @@ -485,6 +381,110 @@ protected void UpdateRoleSelections() } } } - } + } + + /// + /// Bind the data to the controls. + /// + private void BindData() + { + this.EnsureChildControls(); + + this.BindRolesGrid(); + } + + /// + /// Bind the Roles data to the Grid. + /// + private void BindRolesGrid() + { + this.dtRolesSelection.Columns.Clear(); + this.dtRolesSelection.Rows.Clear(); + + // Add Roles Column + var col = new DataColumn("RoleId", typeof(string)); + this.dtRolesSelection.Columns.Add(col); + + // Add Roles Column + col = new DataColumn("RoleName", typeof(string)); + this.dtRolesSelection.Columns.Add(col); + + // Add Selected Column + col = new DataColumn("Selected", typeof(bool)); + this.dtRolesSelection.Columns.Add(col); + + this.GetRoles(); + + this.UpdateRoleSelections(); + for (int i = 0; i <= this._roles.Count - 1; i++) + { + var role = this._roles[i]; + DataRow row = this.dtRolesSelection.NewRow(); + row["RoleId"] = role.RoleID; + row["RoleName"] = Localization.LocalizeRole(role.RoleName); + row["Selected"] = this.GetSelection(role.RoleName); + + this.dtRolesSelection.Rows.Add(row); + } + + this.dgRoleSelection.DataSource = this.dtRolesSelection; + this.dgRoleSelection.DataBind(); + } + + private bool GetSelection(string roleName) + { + return this.CurrentRoleSelection.Any(r => r == roleName); + } + + /// + /// Gets the roles from the Database and loads them into the Roles property. + /// + private void GetRoles() + { + int roleGroupId = -2; + if ((this.cboRoleGroups != null) && (this.cboRoleGroups.SelectedValue != null)) + { + roleGroupId = int.Parse(this.cboRoleGroups.SelectedValue); + } + + this._roles = roleGroupId > -2 + ? RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.RoleGroupID == roleGroupId && r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved) + : RoleController.Instance.GetRoles(PortalController.Instance.GetCurrentPortalSettings().PortalId, r => r.SecurityMode != SecurityMode.SocialGroup && r.Status == RoleStatus.Approved); + + if (roleGroupId < 0) + { + if (this.ShowUnauthenticatedUsers) + { + this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleUnauthUser), RoleName = Globals.glbRoleUnauthUserName }); + } + + if (this.ShowAllUsers) + { + this._roles.Add(new RoleInfo { RoleID = int.Parse(Globals.glbRoleAllUsers), RoleName = Globals.glbRoleAllUsersName }); + } + } + + this._roles = this._roles.OrderBy(r => r.RoleName).ToList(); + } + + /// + /// Sets up the columns for the Grid. + /// + private void SetUpRolesGrid() + { + this.dgRoleSelection.Columns.Clear(); + var textCol = new BoundColumn { HeaderText = " ", DataField = "RoleName" }; + textCol.ItemStyle.Width = Unit.Parse("150px"); + this.dgRoleSelection.Columns.Add(textCol); + var idCol = new BoundColumn { HeaderText = string.Empty, DataField = "roleid", Visible = false }; + this.dgRoleSelection.Columns.Add(idCol); + var checkCol = new TemplateColumn(); + var columnTemplate = new CheckBoxColumnTemplate { DataField = "Selected" }; + checkCol.ItemTemplate = columnTemplate; + checkCol.HeaderText = Localization.GetString("SelectedRole"); + checkCol.ItemStyle.HorizontalAlign = HorizontalAlign.Center; + checkCol.HeaderStyle.Wrap = true; + this.dgRoleSelection.Columns.Add(checkCol); + } } } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs index dfb57d4a06c..a27f173b33e 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumn.cs @@ -16,23 +16,23 @@ 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; } - + public string DataField { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Text (for Header/Footer Templates). /// /// A String. /// ----------------------------------------------------------------------------- - public string Text { get; set; } - + public string Text { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Width of the Column. @@ -76,13 +76,13 @@ private TextColumnTemplate CreateTemplate(ListItemType type) { isDesignMode = true; } - + var template = new TextColumnTemplate(type); if (type != ListItemType.Header) { template.DataField = this.DataField; } - + template.Width = this.Width; if (type == ListItemType.Header) { @@ -92,7 +92,7 @@ private TextColumnTemplate CreateTemplate(ListItemType type) { template.Text = this.Text; } - + template.DesignMode = isDesignMode; return template; } diff --git a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs index 9cba6a8d033..597c3d2dba2 100644 --- a/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/DataGrids/TextColumnTemplate.cs @@ -19,10 +19,10 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class TextColumnTemplate : ITemplate - { - private ListItemType mItemType = ListItemType.Item; - - public TextColumnTemplate() + { + private ListItemType mItemType = ListItemType.Item; + + public TextColumnTemplate() : this(ListItemType.Item) { } @@ -30,8 +30,8 @@ public TextColumnTemplate() public TextColumnTemplate(ListItemType itemType) { this.ItemType = itemType; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets the Data Field is the field that binds to the Text Column. @@ -60,7 +60,7 @@ public ListItemType ItemType { return this.mItemType; } - + set { this.mItemType = value; @@ -81,8 +81,8 @@ public ListItemType ItemType /// /// A Unit. /// ----------------------------------------------------------------------------- - public Unit Width { get; set; } - + public Unit Width { get; set; } + /// ----------------------------------------------------------------------------- /// /// InstantiateIn instantiates the template (implementation of ITemplate). @@ -114,8 +114,8 @@ public void InstantiateIn(Control container) container.Controls.Add(new LiteralControl(this.Text)); break; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets the value of the Data Field. @@ -143,7 +143,7 @@ private string GetValue(DataGridItem container) } } } - + return itemValue; } @@ -175,6 +175,6 @@ private void Item_DataBinding(object sender, EventArgs e) txtText.Text = this.GetValue(container); break; } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/DualListBox.cs b/DNN Platform/Library/UI/WebControls/DualListBox.cs index ab32b367192..95e86b2dd2e 100644 --- a/DNN Platform/Library/UI/WebControls/DualListBox.cs +++ b/DNN Platform/Library/UI/WebControls/DualListBox.cs @@ -16,86 +16,42 @@ namespace DotNetNuke.UI.WebControls using DotNetNuke.Services.Localization; public class DualListBox : WebControl, IPostBackEventHandler, IPostBackDataHandler - { + { private readonly Style _AvailableListBoxStyle = new Style(); private readonly Style _ButtonStyle = new Style(); private readonly TableStyle _ContainerStyle = new TableStyle(); private readonly Style _HeaderStyle = new Style(); private readonly Style _SelectedListBoxStyle = new Style(); private List _AddValues; - private List _RemoveValues; - + private List _RemoveValues; + public DualListBox() { this.ShowAddButton = true; this.ShowAddAllButton = true; this.ShowRemoveButton = true; 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; } - - public string AddAllText { get; set; } - - public string AddImageURL { get; set; } - - public string AddKey { get; set; } - - public string AddText { get; set; } - - public object AvailableDataSource { get; set; } - - public string DataTextField { private get; set; } - - public string DataValueField { private get; set; } - - public string LocalResourceFile { get; set; } - - public string RemoveAllImageURL { get; set; } - - public string RemoveAllKey { get; set; } - - public string RemoveAllText { get; set; } - - public string RemoveImageURL { get; set; } - - public string RemoveKey { get; set; } - - public string RemoveText { get; set; } - - public object SelectedDataSource { get; set; } - - public bool ShowAddButton { get; set; } + } - public bool ShowAddAllButton { get; set; } + public event DualListBoxEventHandler AddButtonClick; - public bool ShowRemoveButton { get; set; } + public event EventHandler AddAllButtonClick; - public bool ShowRemoveAllButton { get; set; } + public event DualListBoxEventHandler RemoveButtonClick; - public bool CausesValidation { get; set; } + public event EventHandler RemoveAllButtonClick; - public string ValidationGroup { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets the value of the Available List Box Style. /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Available List Box.")] public Style AvailableListBoxStyle { @@ -111,11 +67,11 @@ public Style AvailableListBoxStyle /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Button.")] public Style ButtonStyle { @@ -125,25 +81,17 @@ public Style ButtonStyle } } - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets the value of the Container Style. /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Container.")] public TableStyle ContainerStyle { @@ -159,11 +107,11 @@ public TableStyle ContainerStyle /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Header.")] public Style HeaderStyle { @@ -179,11 +127,11 @@ public Style HeaderStyle ///
    /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Selected List Box.")] public Style SelectedListBoxStyle { @@ -191,8 +139,62 @@ public Style SelectedListBoxStyle { return this._SelectedListBoxStyle; } - } - + } + + public string AddAllImageURL { get; set; } + + public string AddAllKey { get; set; } + + public string AddAllText { get; set; } + + public string AddImageURL { get; set; } + + public string AddKey { get; set; } + + public string AddText { get; set; } + + public object AvailableDataSource { get; set; } + + public string DataTextField { private get; set; } + + public string DataValueField { private get; set; } + + public string LocalResourceFile { get; set; } + + public string RemoveAllImageURL { get; set; } + + public string RemoveAllKey { get; set; } + + public string RemoveAllText { get; set; } + + public string RemoveImageURL { get; set; } + + public string RemoveKey { get; set; } + + public string RemoveText { get; set; } + + public object SelectedDataSource { get; set; } + + public bool ShowAddButton { get; set; } + + public bool ShowAddAllButton { get; set; } + + public bool ShowRemoveButton { get; set; } + + public bool ShowRemoveAllButton { get; set; } + + public bool CausesValidation { get; set; } + + public string ValidationGroup { get; set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { bool retValue = Null.NullBoolean; @@ -204,10 +206,10 @@ public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { this._AddValues.Add(addItem); } - + retValue = true; } - + string removeItems = postCollection[postDataKey + "_Selected"]; if (!string.IsNullOrEmpty(removeItems)) { @@ -216,17 +218,17 @@ public bool LoadPostData(string postDataKey, NameValueCollection postCollection) { this._RemoveValues.Add(removeItem); } - + retValue = true; } - + return retValue; } public void RaisePostDataChangedEvent() { - } - + } + public void RaisePostBackEvent(string eventArgument) { switch (eventArgument) @@ -244,9 +246,7 @@ public void RaisePostBackEvent(string eventArgument) this.OnRemoveAllButtonClick(new EventArgs()); break; } - } - - public event EventHandler RemoveAllButtonClick; + } protected virtual PostBackOptions GetPostBackOptions(string argument) { @@ -257,10 +257,10 @@ protected virtual PostBackOptions GetPostBackOptions(string argument) postBackOptions.PerformValidation = true; postBackOptions.ValidationGroup = this.ValidationGroup; } - + return postBackOptions; - } - + } + protected void OnAddButtonClick(DualListBoxEventArgs e) { if (this.AddButtonClick != null) @@ -268,7 +268,60 @@ protected void OnAddButtonClick(DualListBoxEventArgs e) this.AddButtonClick(this, e); } } - + + protected void OnAddAllButtonClick(EventArgs e) + { + if (this.AddAllButtonClick != null) + { + this.AddAllButtonClick(this, e); + } + } + + protected void OnRemoveButtonClick(DualListBoxEventArgs e) + { + if (this.RemoveButtonClick != null) + { + this.RemoveButtonClick(this, e); + } + } + + protected void OnRemoveAllButtonClick(EventArgs e) + { + if (this.RemoveAllButtonClick != null) + { + this.RemoveAllButtonClick(this, e); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + if (this.Page != null) + { + this.Page.RegisterRequiresPostBack(this); + } + } + + protected override void RenderContents(HtmlTextWriter writer) + { + // render table + if (this.ContainerStyle != null) + { + this.ContainerStyle.AddAttributesToRender(writer); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Table); + + // Render Header Row + this.RenderHeader(writer); + + // Render ListBox row + this.RenderListBoxes(writer); + + // Render end of table + writer.RenderEndTag(); + } + private NameValueCollection GetList(string listType, object dataSource) { var dataList = dataSource as IEnumerable; @@ -290,7 +343,7 @@ private NameValueCollection GetList(string listType, object dataSource) list.Add(objText, objValue); } } - + return list; } @@ -370,7 +423,7 @@ private void RenderButtons(HtmlTextWriter writer) { this.RenderButton("Add", writer); } - + if (this.ShowAddAllButton) { this.RenderButton("AddAll", writer); @@ -394,7 +447,7 @@ private void RenderButtons(HtmlTextWriter writer) { this.RenderButton("Remove", writer); } - + if (this.ShowRemoveAllButton) { this.RenderButton("RemoveAll", writer); @@ -443,7 +496,7 @@ private void RenderHeader(HtmlTextWriter writer) { this.HeaderStyle.AddAttributesToRender(writer); } - + writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(Localization.GetString(this.ID + "_Available", this.LocalResourceFile)); writer.RenderEndTag(); @@ -454,7 +507,7 @@ private void RenderHeader(HtmlTextWriter writer) { this.HeaderStyle.AddAttributesToRender(writer); } - + writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(Localization.GetString(this.ID + "_Selected", this.LocalResourceFile)); writer.RenderEndTag(); @@ -483,58 +536,5 @@ private void RenderListBoxes(HtmlTextWriter writer) // Render end of List Boxes Row writer.RenderEndTag(); } - - protected void OnAddAllButtonClick(EventArgs e) - { - if (this.AddAllButtonClick != null) - { - this.AddAllButtonClick(this, e); - } - } - - protected void OnRemoveButtonClick(DualListBoxEventArgs e) - { - if (this.RemoveButtonClick != null) - { - this.RemoveButtonClick(this, e); - } - } - - protected void OnRemoveAllButtonClick(EventArgs e) - { - if (this.RemoveAllButtonClick != null) - { - this.RemoveAllButtonClick(this, e); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - if (this.Page != null) - { - this.Page.RegisterRequiresPostBack(this); - } - } - - protected override void RenderContents(HtmlTextWriter writer) - { - // render table - if (this.ContainerStyle != null) - { - this.ContainerStyle.AddAttributesToRender(writer); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Table); - - // Render Header Row - this.RenderHeader(writer); - - // Render ListBox row - this.RenderListBoxes(writer); - - // Render end of table - writer.RenderEndTag(); - } } } diff --git a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs index f55d64a9080..e8d74955064 100644 --- a/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/Events/DualListBoxEventArgs.cs @@ -19,9 +19,9 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class DualListBoxEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new DualListBoxEventArgs. /// diff --git a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs index 1d254d00673..ba707def61c 100644 --- a/DNN Platform/Library/UI/WebControls/LanguageSelector.cs +++ b/DNN Platform/Library/UI/WebControls/LanguageSelector.cs @@ -17,22 +17,22 @@ namespace DotNetNuke.UI.WebControls /// Language Selector control. /// public class LanguageSelector : Control, INamingContainer - { - private Panel pnlControl; - + { + private Panel pnlControl; + public enum LanguageItemStyle { FlagOnly = 1, FlagAndCaption = 2, CaptionOnly = 3, - } - + } + public enum LanguageListDirection { Horizontal = 1, Vertical = 2, - } - + } + /// /// Language Selection mode, offered to the user: single select or multiple select. /// @@ -40,8 +40,8 @@ public enum LanguageSelectionMode { Multiple = 1, Single = 2, - } - + } + /// /// Selection object: Language ("de", "en") or Locale ("de-DE", "en-US"). /// @@ -49,8 +49,8 @@ public enum LanguageSelectionObject { NeutralCulture = 1, SpecificCulture = 2, - } - + } + /// /// Gets or sets selection mode (single, multiple). /// @@ -67,7 +67,7 @@ public LanguageSelectionMode SelectionMode return (LanguageSelectionMode)this.ViewState["SelectionMode"]; } } - + set { if (this.SelectionMode != value) @@ -97,7 +97,7 @@ public LanguageSelectionObject SelectionObject return (LanguageSelectionObject)this.ViewState["SelectionObject"]; } } - + set { if ((int)this.SelectionMode != (int)value) @@ -127,7 +127,7 @@ public LanguageItemStyle ItemStyle return (LanguageItemStyle)this.ViewState["ItemStyle"]; } } - + set { if (this.ItemStyle != value) @@ -157,7 +157,7 @@ public LanguageListDirection ListDirection return (LanguageListDirection)this.ViewState["ListDirection"]; } } - + set { if (this.ListDirection != value) @@ -210,10 +210,10 @@ public string[] SelectedLanguages } } } - + return a.ToArray(typeof(string)) as string[]; } - + set { this.EnsureChildControls(); @@ -221,7 +221,7 @@ public string[] SelectedLanguages { throw new ArgumentException("Selection mode 'single' cannot have more than one selected item."); } - + foreach (CultureInfo c in this.GetCultures(this.SelectionObject == LanguageSelectionObject.SpecificCulture)) { if (this.SelectionMode == LanguageSelectionMode.Single) @@ -233,7 +233,7 @@ public string[] SelectedLanguages ((CheckBox)this.pnlControl.FindControl("chk" + c.Name)).Checked = false; } } - + foreach (string strLocale in value) { if (this.SelectionMode == LanguageSelectionMode.Single) @@ -254,8 +254,8 @@ public string[] SelectedLanguages } } } - } - + } + /// /// Create Child Controls. /// @@ -282,7 +282,7 @@ protected override void CreateChildControls() { optLocale.Checked = true; } - + this.pnlControl.Controls.Add(optLocale); lblLocale.Attributes["for"] = optLocale.ClientID; } @@ -303,15 +303,15 @@ protected override void CreateChildControls() imgLocale.Style["vertical-align"] = "middle"; lblLocale.Controls.Add(imgLocale); } - + if (this.ItemStyle != LanguageItemStyle.FlagOnly) { lblLocale.Controls.Add(new LiteralControl(" " + c.DisplayName)); } - + this.pnlControl.Controls.Add(new LiteralControl("")); } - + this.pnlControl.Controls.Add(new LiteralControl("")); // Hide if not more than one language @@ -319,8 +319,8 @@ protected override void CreateChildControls() { this.Visible = false; } - } - + } + /// /// retrieve the cultures, currently supported by the portal. /// @@ -346,8 +346,8 @@ private CultureInfo[] GetCultures(bool specific) } } } - + return (CultureInfo[])a.ToArray(typeof(CultureInfo)); - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs b/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs index 99a5481b202..d09023e4797 100644 --- a/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs +++ b/DNN Platform/Library/UI/WebControls/LiteralTemplate.cs @@ -18,8 +18,8 @@ public LiteralTemplate(string html) public LiteralTemplate(Control ctl) { this.m_objControl = ctl; - } - + } + public void InstantiateIn(Control container) { if (this.m_objControl == null) @@ -30,6 +30,6 @@ public void InstantiateIn(Control container) { container.Controls.Add(this.m_objControl); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs index 6b716a4271f..c58c373a98a 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchicalEnumerable.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.UI.WebControls /// A collection of PageHierarchyData objects. public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable - { + { /// /// Handles enumeration. /// @@ -18,6 +18,6 @@ public class NavDataPageHierarchicalEnumerable : ArrayList, IHierarchicalEnumera public virtual IHierarchyData GetHierarchyData(object enumeratedItem) { return (IHierarchyData)enumeratedItem; - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs index bb381b02efa..8543b5fe9c2 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataPageHierarchyData.cs @@ -20,8 +20,8 @@ public NavDataPageHierarchyData(DNNNode obj) /// /// Gets nodes image. /// - /// - /// Returns nodes image + /// + /// Returns nodes image /// /// /// @@ -38,13 +38,13 @@ public virtual string ImageUrl return PortalController.Instance.GetCurrentPortalSettings().HomeDirectory + this.m_objNode.Image; } } - } - + } + /// /// Gets a value indicating whether indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. /// - /// - /// Indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. + /// + /// Indicates whether the hierarchical data node that the IHierarchyData object represents has any child nodes. /// /// /// @@ -59,8 +59,8 @@ public virtual bool HasChildren /// /// Gets the hierarchical path of the node. /// - /// - /// The hierarchical path of the node. + /// + /// The hierarchical path of the node. /// /// /// @@ -75,8 +75,8 @@ public virtual string Path /// /// Gets the hierarchical data node that the IHierarchyData object represents. /// - /// - /// The hierarchical data node that the IHierarchyData object represents. + /// + /// The hierarchical data node that the IHierarchyData object represents. /// /// /// @@ -91,8 +91,8 @@ public virtual object Item /// /// Gets the name of the type of Object contained in the Item property. /// - /// - /// The name of the type of Object contained in the Item property. + /// + /// The name of the type of Object contained in the Item property. /// /// /// @@ -103,12 +103,12 @@ public virtual string Type return "NavDataPageHierarchyData"; } } - + /// /// Gets node name. /// - /// - /// Returns node name + /// + /// Returns node name /// /// /// @@ -123,8 +123,8 @@ public virtual string Name /// /// Gets value path of node. /// - /// - /// Returns value path of node + /// + /// Returns value path of node /// /// /// @@ -139,8 +139,8 @@ public virtual string Value /// /// Gets node navigation url. /// - /// - /// Returns node navigation url + /// + /// Returns node navigation url /// /// /// @@ -152,6 +152,22 @@ public virtual string NavigateUrl } } + /// + /// Gets node description. + /// + /// + /// Returns Node description + /// + /// + /// + public virtual string Description + { + get + { + return this.GetSafeValue(this.m_objNode.ToolTip, string.Empty); + } + } + /// /// Gets an enumeration object that represents all the child nodes of the current hierarchical node. /// @@ -167,7 +183,7 @@ public virtual IHierarchicalEnumerable GetChildren() objNodes.Add(new NavDataPageHierarchyData(objNode)); } } - + return objNodes; } @@ -186,24 +202,8 @@ public virtual IHierarchyData GetParent() { return null; } - } + } - /// - /// Gets node description. - /// - /// - /// Returns Node description - /// - /// - /// - public virtual string Description - { - get - { - return this.GetSafeValue(this.m_objNode.ToolTip, string.Empty); - } - } - public override string ToString() { return this.m_objNode.Text; @@ -244,10 +244,10 @@ private string GetValuePath(DNNNode objNode) { break; } - + strPath = this.GetSafeValue(objParent.Key, string.Empty) + "\\" + strPath; objParent = objParent.ParentNode; - } + } while (true); return strPath; } diff --git a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs index 370c7c78240..c3b10ba65e7 100644 --- a/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs +++ b/DNN Platform/Library/UI/WebControls/NavDataSource/NavDataSourceView.cs @@ -34,7 +34,7 @@ public string Namespace { return this.m_sNamespace; } - + set { this.m_sNamespace = value; @@ -58,12 +58,12 @@ public override IHierarchicalEnumerable Select() { objNodes = objNodes.FindNodeByKey(this.m_sKey).DNNNodes; } - + foreach (DNNNode objNode in objNodes) { objPages.Add(new NavDataPageHierarchyData(objNode)); } - + return objPages; } } diff --git a/DNN Platform/Library/UI/WebControls/PagingControl.cs b/DNN Platform/Library/UI/WebControls/PagingControl.cs index 25a50f5e8ba..6a0d41a1353 100644 --- a/DNN Platform/Library/UI/WebControls/PagingControl.cs +++ b/DNN Platform/Library/UI/WebControls/PagingControl.cs @@ -20,12 +20,12 @@ public class PagingControl : WebControl, IPostBackEventHandler protected Repeater PageNumbers; protected TableCell cellDisplayLinks; protected TableCell cellDisplayStatus; + protected Table tablePageNumbers; private int _totalPages = -1; private string _CSSClassLinkActive; private string _CSSClassLinkInactive; private string _CSSClassPagingStatus; private PagingControlMode _Mode = PagingControlMode.URL; - protected Table tablePageNumbers; public event EventHandler PageChanged; @@ -162,6 +162,25 @@ protected void OnPageChanged(EventArgs e) } } + protected override void Render(HtmlTextWriter output) + { + if (this.PageNumbers == null) + { + this.CreateChildControls(); + } + + var str = new StringBuilder(); + str.Append(this.GetFirstLink() + "   "); + str.Append(this.GetPreviousLink() + "   "); + var result = new StringBuilder(1024); + this.PageNumbers.RenderControl(new HtmlTextWriter(new StringWriter(result))); + str.Append(result.ToString()); + str.Append(this.GetNextLink() + "   "); + str.Append(this.GetLastLink() + "   "); + this.cellDisplayLinks.Controls.Add(new LiteralControl(str.ToString())); + this.tablePageNumbers.RenderControl(output); + } + private void BindPageNumbers(int TotalRecords, int RecordsPerPage) { const int pageLinksPerPage = 10; @@ -334,25 +353,6 @@ private string GetLastLink() : "" + Localization.GetString("Last", Localization.SharedResourceFile) + ""; } - protected override void Render(HtmlTextWriter output) - { - if (this.PageNumbers == null) - { - this.CreateChildControls(); - } - - var str = new StringBuilder(); - str.Append(this.GetFirstLink() + "   "); - str.Append(this.GetPreviousLink() + "   "); - var result = new StringBuilder(1024); - this.PageNumbers.RenderControl(new HtmlTextWriter(new StringWriter(result))); - str.Append(result.ToString()); - str.Append(this.GetNextLink() + "   "); - str.Append(this.GetLastLink() + "   "); - this.cellDisplayLinks.Controls.Add(new LiteralControl(str.ToString())); - this.tablePageNumbers.RenderControl(output); - } - public class PageNumberLinkTemplate : ITemplate { private readonly PagingControl _PagingControl; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs index f951cd7e603..543c61bb92f 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/CollectionEditorInfoAdapter.cs @@ -34,8 +34,8 @@ public CollectionEditorInfoAdapter(object dataSource, string name, string fieldN this.DataSource = dataSource; this.FieldNames = fieldNames; this.Name = name; - } - + } + public EditorInfo CreateEditControl() { return this.GetEditorInfo(); @@ -59,7 +59,7 @@ public bool UpdateValue(PropertyEditorEventArgs e) if (objProperty != null) { PropertyName = Convert.ToString(objProperty.GetValue(this.DataSource, null)); - + // Do we have the item in the IEnumerable Collection being changed PropertyName = PropertyName.Replace(" ", "_"); if (PropertyName == name) @@ -78,12 +78,12 @@ public bool UpdateValue(PropertyEditorEventArgs e) { objProperty.SetValue(this.DataSource, newValue, null); } - + _IsDirty = true; } } } - + return _IsDirty; } @@ -100,23 +100,23 @@ public bool UpdateVisibility(PropertyEditorEventArgs e) if (property != null) { string propertyName = Convert.ToString(property.GetValue(this.DataSource, null)); - + // Do we have the item in the IEnumerable Collection being changed propertyName = propertyName.Replace(" ", "_"); if (propertyName == name) { // Get the Value Property property = this.DataSource.GetType().GetProperty(dataField); - + // Set the Value property to the new value property.SetValue(this.DataSource, newValue, null); dirty = true; } } - + return dirty; - } - + } + /// ----------------------------------------------------------------------------- /// /// GetEditorInfo builds an EditorInfo object for a propoerty. @@ -216,9 +216,9 @@ 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)) { diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs index 0f8aefe6fd4..ee12527d647 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/SettingsEditorInfoAdapter.cs @@ -32,8 +32,8 @@ public SettingsEditorInfoAdapter(object dataSource, object dataMember, string fi this.DataMember = dataMember; this.DataSource = dataSource; this.FieldName = fieldName; - } - + } + public EditorInfo CreateEditControl() { var info = (SettingInfo)this.DataMember; @@ -86,7 +86,7 @@ public bool UpdateValue(PropertyEditorEventArgs e) while (settingsEnumerator.MoveNext()) { key = Convert.ToString(settingsEnumerator.Key); - + // Do we have the item in the Hashtable being changed if (key == name) { @@ -99,13 +99,13 @@ public bool UpdateValue(PropertyEditorEventArgs e) } } } - + return _IsDirty; } public bool UpdateVisibility(PropertyEditorEventArgs e) { return false; - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs index 4c710d3c0ab..5edec2e78a0 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Adapters/StandardEditorInfoAdapter.cs @@ -31,8 +31,8 @@ public StandardEditorInfoAdapter(object dataSource, string fieldName) { this.DataSource = dataSource; this.FieldName = fieldName; - } - + } + public EditorInfo CreateEditControl() { EditorInfo editInfo = null; @@ -41,7 +41,7 @@ public EditorInfo CreateEditControl() { editInfo = this.GetEditorInfo(this.DataSource, objProperty); } - + return editInfo; } @@ -63,15 +63,15 @@ public bool UpdateValue(PropertyEditorEventArgs e) } } } - + return _IsDirty; } public bool UpdateVisibility(PropertyEditorEventArgs e) { return false; - } - + } + /// ----------------------------------------------------------------------------- /// /// GetEditorInfo builds an EditorInfo object for a propoerty. @@ -134,7 +134,7 @@ private EditorInfo GetEditorInfo(object dataSource, PropertyInfo objProperty) break; } } - + if (editor != null) { editInfo.Editor = editor.EditorTypeName; @@ -187,9 +187,9 @@ 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 633d165788d..d03e062965b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/CollectionEditorControl.cs @@ -27,16 +27,16 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:CollectionEditorControl runat=server>")] public class CollectionEditorControl : PropertyEditorControl - { + { /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the value of the Category. /// /// A string representing the Category of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the Category.")] public string CategoryDataField { get; set; } @@ -46,25 +46,11 @@ public class CollectionEditorControl : PropertyEditorControl /// /// A string representing the Editor Type of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [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; - } - } /// ----------------------------------------------------------------------------- /// @@ -72,9 +58,9 @@ protected override IEnumerable UnderlyingDataSource /// /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that determines the length.")] public string LengthDataField { get; set; } @@ -84,9 +70,9 @@ protected override IEnumerable UnderlyingDataSource /// /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the Label's Text property.")] public string NameDataField { get; set; } @@ -96,9 +82,9 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that determines whether an item is required.")] public string RequiredDataField { get; set; } @@ -108,9 +94,9 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the EditControl's Type.")] public string TypeDataField { get; set; } @@ -121,9 +107,9 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the EditControl's Expression DynamicContentValidator.")] public string ValidationExpressionDataField { get; set; } @@ -133,9 +119,9 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the EditControl's Value property.")] public string ValueDataField { get; set; } @@ -145,9 +131,9 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that determines whether the item is visble.")] public string VisibleDataField { get; set; } @@ -157,12 +143,26 @@ protected override IEnumerable UnderlyingDataSource ///
    /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that determines the visibility.")] - public string VisibilityDataField { get; set; } - + public string VisibilityDataField { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable. + /// ----------------------------------------------------------------------------- + protected override IEnumerable UnderlyingDataSource + { + get + { + return (IEnumerable)this.DataSource; + } + } + protected override void AddEditorRow(Table table, object obj) { this.AddEditorRow(table, this.NameDataField, new CollectionEditorInfoAdapter(obj, this.ID, this.NameDataField, this.GetFieldNames())); @@ -172,22 +172,6 @@ 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(); - fields.Add("Category", this.CategoryDataField); - fields.Add("Editor", this.EditorDataField); - fields.Add("Name", this.NameDataField); - fields.Add("Required", this.RequiredDataField); - fields.Add("Type", this.TypeDataField); - fields.Add("ValidationExpression", this.ValidationExpressionDataField); - fields.Add("Value", this.ValueDataField); - fields.Add("ProfileVisibility", this.VisibilityDataField); - fields.Add("Length", this.LengthDataField); - - return fields; - } protected override void AddEditorRow(object obj) { @@ -197,7 +181,7 @@ protected override void AddEditorRow(object obj) /// ----------------------------------------------------------------------------- /// /// GetCategory gets the Category of an object. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override string GetCategory(object obj) @@ -214,14 +198,14 @@ protected override string GetCategory(object obj) _Category = Convert.ToString(objProperty.GetValue(obj, null)); } } - + return _Category; } /// ----------------------------------------------------------------------------- /// /// GetGroups gets an array of Groups/Categories from the DataSource. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected override string[] GetGroups(IEnumerable arrObjects) @@ -246,13 +230,13 @@ protected override string[] GetGroups(IEnumerable arrObjects) } } } - + var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { strGroups[i] = Convert.ToString(arrGroups[i]); } - + return strGroups; } @@ -260,7 +244,7 @@ protected override string[] GetGroups(IEnumerable arrObjects) /// /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property. + /// The property. /// /// ----------------------------------------------------------------------------- protected override bool GetRowVisibility(object obj) @@ -272,7 +256,7 @@ protected override bool GetRowVisibility(object obj) { isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); } - + if (!isVisible && this.EditMode == PropertyEditorMode.Edit) { // Check if property is required - as this will need to override visibility @@ -282,8 +266,24 @@ protected override bool GetRowVisibility(object obj) isVisible = Convert.ToBoolean(objProperty.GetValue(obj, null)); } } - + return isVisible; - } + } + + private Hashtable GetFieldNames() + { + var fields = new Hashtable(); + fields.Add("Category", this.CategoryDataField); + fields.Add("Editor", this.EditorDataField); + fields.Add("Name", this.NameDataField); + fields.Add("Required", this.RequiredDataField); + fields.Add("Type", this.TypeDataField); + fields.Add("ValidationExpression", this.ValidationExpressionDataField); + fields.Add("Value", this.ValueDataField); + fields.Add("ProfileVisibility", this.VisibilityDataField); + fields.Add("Length", this.LengthDataField); + + return fields; + } } } 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 a763276822a..a8832981f30 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/AutoCompleteControl.cs @@ -21,13 +21,13 @@ namespace DotNetNuke.UI.WebControls ///
    [ToolboxData("<{0}:TextEditControl runat=server>")] internal class AutoCompleteControl : TextEditControl - { + { public AutoCompleteControl() { this.Init += this.AutoCompleteControl_Init; this.Load += this.AutoCompleteControl_Load; - } - + } + protected override void RenderEditMode(HtmlTextWriter writer) { int length = Null.NullInteger; @@ -43,7 +43,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) } } } - + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); @@ -51,7 +51,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.AddAttribute("data-name", this.Name); @@ -60,7 +60,7 @@ 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"); @@ -71,6 +71,6 @@ private void AutoCompleteControl_Init(object sender, System.EventArgs e) private void AutoCompleteControl_Load(object sender, System.EventArgs e) { - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs index bcc5b82b1d9..4f94be50a13 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/CheckEditControl.cs @@ -35,13 +35,13 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo { boolValue = true; } - + if (!this.BooleanValue.Equals(boolValue)) { this.Value = boolValue; return true; } - + return false; } 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 6427137b25a..09b1454df55 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 @@ -17,21 +17,21 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:DnnCountryAutocompleteControl runat=server>")] public class DnnCountryAutocompleteControl : EditControl - { + { private TextBox _CountryName; private HiddenField _CountryId; - + public DnnCountryAutocompleteControl() { this.Init += this.DnnCountryRegionControl_Init; } - + public DnnCountryAutocompleteControl(string type) { this.Init += this.DnnCountryRegionControl_Init; this.SystemType = type; - } + } public override string EditControlClientId { @@ -40,8 +40,13 @@ public override string EditControlClientId this.EnsureChildControls(); return this.CountryName.ClientID; } - } - + } + + protected string OldStringValue + { + get { return Convert.ToString(this.OldValue); } + } + protected override string StringValue { get @@ -51,13 +56,13 @@ protected override string StringValue { strValue = Convert.ToString(this.Value); } - + return strValue; } - + set { this.Value = value; } } - + private TextBox CountryName { get @@ -66,11 +71,11 @@ private TextBox CountryName { this._CountryName = new TextBox(); } - + return this._CountryName; } } - + private HiddenField CountryId { get @@ -79,16 +84,11 @@ private HiddenField CountryId { this._CountryId = new HiddenField(); } - + return this._CountryId; } } - protected string OldStringValue - { - get { return Convert.ToString(this.OldValue); } - } - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { bool dataChanged = false; @@ -99,10 +99,10 @@ public override bool LoadPostData(string postDataKey, System.Collections.Special this.Value = postedValue; dataChanged = true; } - + return dataChanged; } - + protected override void OnDataChanged(EventArgs e) { PropertyEditorEventArgs args = new PropertyEditorEventArgs(this.Name); @@ -145,8 +145,8 @@ protected override void OnPreRender(System.EventArgs e) protected override void RenderEditMode(HtmlTextWriter writer) { this.RenderChildren(writer); - } - + } + private void DnnCountryRegionControl_Init(object sender, System.EventArgs e) { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); @@ -154,8 +154,8 @@ private void DnnCountryRegionControl_Init(object sender, System.EventArgs e) ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryUI); - } - + } + private void LoadControls() { this.CountryName.Text = this.StringValue; @@ -168,7 +168,7 @@ private void LoadControls() this.CountryName.Text = c.Text; countryCode = c.Value; } - + this.CountryId.Value = this.StringValue; var regionControl2 = ControlUtilities.FindFirstDescendent(this.Page, c => this.IsCoupledRegionControl(c)); @@ -188,8 +188,8 @@ private bool IsCoupledRegionControl(Control ctr) return true; } } - + return false; - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs index 2c1bfeca1b6..e02338dec81 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNCountryEditControl.cs @@ -21,9 +21,9 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DNNCountryEditControl runat=server>")] public class DNNCountryEditControl : DNNListEditControl - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a DNNCountryEditControl. /// 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 11d1cc4d0c1..7b514e9acbd 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,23 +40,9 @@ public DNNListEditControl() this.ParentKey = string.Empty; this.SortAlphabetically = false; } - - public event PropertyChangedEventHandler ItemChanged; - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. - /// - /// ----------------------------------------------------------------------------- - protected bool AutoPostBack { get; set; } + public event PropertyChangedEventHandler ItemChanged; - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets a value indicating whether if true the list will be sorted on the value of Text before rendering. - /// - /// ----------------------------------------------------------------------------- - protected bool SortAlphabetically { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets integerValue returns the Integer representation of the Value. @@ -72,7 +58,7 @@ protected int IntegerValue { return intValue; } - + try { intValue = Convert.ToInt32(this.Value); @@ -81,7 +67,7 @@ protected int IntegerValue { Logger.Error(exc); } - + return intValue; } } @@ -89,7 +75,7 @@ protected int IntegerValue /// /// Gets list gets the List associated with the control. /// - [Obsolete("Obsoleted in 6.0.1 use ListEntries instead. Scheduled removal in v10.0.0.")] + [Obsolete("Obsoleted in 6.0.1 use ListEntries instead. Scheduled removal in v10.0.0.")] [EditorBrowsable(EditorBrowsableState.Never)] protected ListEntryInfoCollection List { @@ -123,29 +109,6 @@ protected IEnumerable ListEntries return this._listEntries; } } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets listName is the name of the List to display. - /// - /// ----------------------------------------------------------------------------- - protected virtual string ListName - { - get - { - if (this._listName == Null.NullString) - { - this._listName = this.DataField; - } - - return this._listName; - } - - set - { - this._listName = value; - } - } /// ----------------------------------------------------------------------------- /// @@ -162,7 +125,7 @@ protected int OldIntegerValue { return intValue; } - + try { // Try and cast the value to an Integer @@ -172,16 +135,11 @@ protected int OldIntegerValue { Logger.Error(exc); } - + return intValue; } } - /// - /// Gets or sets the parent key of the List to display. - /// - protected virtual string ParentKey { get; set; } - protected int PortalId { get @@ -190,30 +148,72 @@ protected int PortalId } } + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the field to display in the combo. + /// Gets oldStringValue returns the Boolean representation of the OldValue. /// - protected virtual ListBoundField TextField { get; set; } + /// A String representing the OldValue. + /// ----------------------------------------------------------------------------- + protected string OldStringValue + { + get + { + return Convert.ToString(this.OldValue); + } + } + /// ----------------------------------------------------------------------------- /// - /// Gets or sets the field to use as the combo item values. + /// Gets or sets a value indicating whether determines whether the List Auto Posts Back. /// - protected virtual ListBoundField ValueField { get; set; } + /// ----------------------------------------------------------------------------- + protected bool AutoPostBack { get; set; } /// ----------------------------------------------------------------------------- /// - /// Gets oldStringValue returns the Boolean representation of the OldValue. + /// Gets or sets a value indicating whether if true the list will be sorted on the value of Text before rendering. /// - /// A String representing the OldValue. /// ----------------------------------------------------------------------------- - protected string OldStringValue + protected bool SortAlphabetically { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets listName is the name of the List to display. + /// + /// ----------------------------------------------------------------------------- + protected virtual string ListName { get { - return Convert.ToString(this.OldValue); + if (this._listName == Null.NullString) + { + this._listName = this.DataField; + } + + return this._listName; + } + + set + { + this._listName = value; } } + /// + /// Gets or sets the parent key of the List to display. + /// + protected virtual string ParentKey { get; set; } + + /// + /// Gets or sets the field to display in the combo. + /// + protected virtual ListBoundField TextField { get; set; } + + /// + /// Gets or sets the field to use as the combo item values. + /// + protected virtual ListBoundField ValueField { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets stringValue is the value of the control expressed as a String. @@ -226,7 +226,7 @@ protected override string StringValue { return Convert.ToString(this.Value); } - + set { if (this.ValueField == ListBoundField.Id) @@ -240,16 +240,16 @@ protected override string StringValue this.Value = value; } } - } - + } + public void RaisePostBackEvent(string eventArgument) { if (this.AutoPostBack) { this.OnItemChanged(this.GetEventArgs()); } - } - + } + /// ----------------------------------------------------------------------------- /// /// OnAttributesChanged runs when the CustomAttributes property has changed. @@ -285,26 +285,6 @@ 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; - } /// ----------------------------------------------------------------------------- /// @@ -342,7 +322,7 @@ protected override void RenderViewMode(HtmlTextWriter writer) entry = objListController.GetListEntryInfo(this.ListName, this.StringValue); break; } - + this.ControlStyle.AddAttributesToRender(writer); writer.RenderBeginTag(HtmlTextWriterTag.Span); if (entry != null) @@ -389,7 +369,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Onchange, this.Page.ClientScript.GetPostBackEventReference(this, this.ID)); } - + writer.RenderBeginTag(HtmlTextWriterTag.Select); // Add the Not Specified Option @@ -401,7 +381,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Value, Null.NullString); } - + if (this.StringValue == Null.NullString) { // Add the Selected Attribute @@ -430,7 +410,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) itemValue = item.Value; break; } - + writer.AddAttribute(HtmlTextWriterAttribute.Value, itemValue); if (this.StringValue == itemValue) { @@ -452,12 +432,32 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.Write(item.Value.Trim()); break; } - + writer.RenderEndTag(); } // Close Select Tag writer.RenderEndTag(); - } + } + + 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 1bd721ad2e8..5356027ceee 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 @@ -45,13 +45,13 @@ protected PortalSettings PortalSettings { return PortalController.Instance.GetCurrentPortalSettings(); } - } - + } + public void RaisePostBackEvent(string eventArgument) { this._DisplayMode = eventArgument; - } - + } + /// /// OnAttributesChanged runs when the CustomAttributes property has changed. /// @@ -86,77 +86,10 @@ protected override void RenderViewMode(HtmlTextWriter writer) { writer.Write(locale.Text); } - - writer.RenderEndTag(); - } - - private bool IsSelected(string locale) - { - return locale == this.StringValue; - } - private void RenderModeButtons(HtmlTextWriter writer) - { - writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - writer.AddAttribute("aria-label", "Mode"); - if (this.DisplayMode == "English") - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "English")); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.RenderEndTag(); - writer.Write(Localization.GetString("EnglishName", Localization.GlobalResourceFile)); - - // writer.Write("
    "); - writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - writer.AddAttribute("aria-label", "Mode"); - if (this.DisplayMode == "Native") - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - else - { - writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "Native")); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); - - writer.Write(Localization.GetString("NativeName", Localization.GlobalResourceFile)); } - private void RenderOption(HtmlTextWriter writer, CultureInfo culture) - { - string localeName; - - if (this.DisplayMode == "Native") - { - localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.NativeName); - } - else - { - localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.EnglishName); - } - - // Add the Value Attribute - writer.AddAttribute(HtmlTextWriterAttribute.Value, culture.Name); - - if (this.IsSelected(culture.Name)) - { - writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); - } - - // Render Option Tag - writer.RenderBeginTag(HtmlTextWriterTag.Option); - writer.Write(localeName); - writer.RenderEndTag(); - } - /// /// RenderEditMode renders the Edit mode of the control. /// @@ -196,7 +129,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Onchange, "onLocaleChanged(this)"); } - + writer.RenderBeginTag(HtmlTextWriterTag.Select); // Render None selected option @@ -208,7 +141,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) // Add the Selected Attribute writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); } - + writer.RenderBeginTag(HtmlTextWriterTag.Option); writer.Write(Localization.GetString("Not_Specified", Localization.SharedResourceFile)); writer.RenderEndTag(); @@ -258,6 +191,73 @@ function onLocaleChanged(element){ // close div writer.RenderEndTag(); - } + } + + private bool IsSelected(string locale) + { + return locale == this.StringValue; + } + + private void RenderModeButtons(HtmlTextWriter writer) + { + writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); + writer.AddAttribute("aria-label", "Mode"); + if (this.DisplayMode == "English") + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "English")); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + writer.Write(Localization.GetString("EnglishName", Localization.GlobalResourceFile)); + + // writer.Write("
    "); + writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); + writer.AddAttribute("aria-label", "Mode"); + if (this.DisplayMode == "Native") + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + else + { + writer.AddAttribute(HtmlTextWriterAttribute.Onclick, this.Page.ClientScript.GetPostBackEventReference(this, "Native")); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.RenderEndTag(); + + writer.Write(Localization.GetString("NativeName", Localization.GlobalResourceFile)); + } + + private void RenderOption(HtmlTextWriter writer, CultureInfo culture) + { + string localeName; + + if (this.DisplayMode == "Native") + { + localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.NativeName); + } + else + { + localeName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(culture.EnglishName); + } + + // Add the Value Attribute + writer.AddAttribute(HtmlTextWriterAttribute.Value, culture.Name); + + if (this.IsSelected(culture.Name)) + { + writer.AddAttribute(HtmlTextWriterAttribute.Selected, "selected"); + } + + // Render Option Tag + writer.RenderBeginTag(HtmlTextWriterTag.Option); + writer.Write(localeName); + writer.RenderEndTag(); + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs index d71197a46ce..0d41bc4fe53 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNPageEditControl.cs @@ -25,7 +25,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DNNPageEditControl runat=server>")] public class DNNPageEditControl : IntegerEditControl - { + { /// ----------------------------------------------------------------------------- /// /// RenderEditMode renders the Edit mode of the control. @@ -94,6 +94,6 @@ protected override void RenderViewMode(HtmlTextWriter writer) writer.Write(linkedTabInfo.LocalizedTabName); writer.RenderEndTag(); } - } + } } } 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 32b02addf70..0540f808833 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 @@ -31,7 +31,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:DNNRegionEditControl runat=server>")] public class DNNRegionEditControl : EditControl - { + { private DropDownList _Regions; private TextBox _Region; @@ -39,23 +39,53 @@ public class DNNRegionEditControl : EditControl 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 string OldStringValue + { + get { return Convert.ToString(this.OldValue); } + } + + /// + /// Gets the ListEntryInfo objects associated witht the control. + /// + protected IEnumerable ListEntries + { + get + { + if (this._listEntries == null) + { + var listController = new ListController(); + this._listEntries = listController.GetListEntryInfoItems("Region", this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); + } + + return this._listEntries; + } + } + + protected int PortalId + { + get + { + return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); + } + } + protected override string StringValue { get @@ -65,18 +95,13 @@ protected override string StringValue { strValue = Convert.ToString(this.Value); } - + return strValue; } - + set { this.Value = value; } } - protected string OldStringValue - { - get { return Convert.ToString(this.OldValue); } - } - private DropDownList Regions { get @@ -85,11 +110,11 @@ private DropDownList Regions { this._Regions = new DropDownList(); } - + return this._Regions; } } - + private TextBox Region { get @@ -98,11 +123,11 @@ private TextBox Region { this._Region = new TextBox(); } - + return this._Region; } } - + private HtmlInputHidden RegionCode { get @@ -111,36 +136,11 @@ private HtmlInputHidden RegionCode { this._InitialValue = new HtmlInputHidden(); } - - return this._InitialValue; - } - } - - /// - /// Gets the ListEntryInfo objects associated witht the control. - /// - protected IEnumerable ListEntries - { - get - { - if (this._listEntries == null) - { - var listController = new ListController(); - this._listEntries = listController.GetListEntryInfoItems("Region", this.ParentKey, this.PortalId).OrderBy(s => s.SortOrder).ThenBy(s => s.Text).ToList(); - } - return this._listEntries; + return this._InitialValue; } } - protected int PortalId - { - get - { - return PortalController.GetEffectivePortalId(PortalSettings.Current.PortalId); - } - } - public override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { bool dataChanged = false; @@ -151,10 +151,10 @@ public override bool LoadPostData(string postDataKey, System.Collections.Special this.Value = postedValue; dataChanged = true; } - + return dataChanged; } - + /// ----------------------------------------------------------------------------- /// /// OnAttributesChanged runs when the CustomAttributes property has changed. @@ -230,7 +230,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) this.Regions.Items.Add(new ListItem() { Text = item.Text, Value = item.EntryID.ToString() }); } } - + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute("data-name", this.Name); writer.AddAttribute("data-list", "Region"); @@ -239,8 +239,8 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.RenderBeginTag(HtmlTextWriterTag.Div); this.RenderChildren(writer); writer.RenderEndTag(); - } - + } + private void DnnRegionControl_Init(object sender, System.EventArgs e) { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); @@ -248,11 +248,11 @@ private void DnnRegionControl_Init(object sender, System.EventArgs e) ClientResourceManager.RegisterFeatureStylesheet(this.Page, "~/Resources/Shared/components/CountriesRegions/dnn.CountriesRegions.css"); JavaScript.RequestRegistration(CommonJs.jQuery); JavaScript.RequestRegistration(CommonJs.jQueryUI); - } - + } + private void LoadControls() { this.RegionCode.Value = this.StringValue; - } + } } } 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 db3b7659971..98c58df20bf 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 @@ -46,7 +46,7 @@ protected string EditorText return this._defaultTextEditor.Text; } - + set { if (this._richTextEditor != null) @@ -70,7 +70,7 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.Value = postedValue; dataChanged = true; } - + return dataChanged; } @@ -87,7 +87,7 @@ protected override void CreateChildControls() { pnlEditor.CssClass = string.Format("{0} dnnLeft", this.CssClass); } - + this._richTextEditor = HtmlEditorProvider.Instance(); if (this._richTextEditor != null) { @@ -104,12 +104,12 @@ 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"); } @@ -118,7 +118,7 @@ protected override void CreateChildControls() pnlEditor.Controls.Add(this.TextEditControl); this.Controls.Add(pnlEditor); } - + base.CreateChildControls(); } @@ -143,18 +143,13 @@ protected override void OnPreRender(EventArgs e) { this.EditorText = this.Page.Server.HtmlDecode(Convert.ToString(this.Value)); } - + if (this.Page != null && this.EditMode == PropertyEditorMode.Edit) { this.Page.RegisterRequiresPostBack(this); } } - private string RemoveBaseTags(string strInput) - { - return Globals.BaseTagRegex.Replace(strInput, " "); - } - protected override void RenderEditMode(HtmlTextWriter writer) { this.RenderChildren(writer); @@ -168,5 +163,10 @@ protected override void RenderViewMode(HtmlTextWriter writer) writer.Write(propValue); writer.RenderEndTag(); } + + private string RemoveBaseTags(string strInput) + { + return Globals.BaseTagRegex.Replace(strInput, " "); + } } } 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 d954242d792..6a4878c079e 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateEditControl.cs @@ -33,8 +33,8 @@ public class DateEditControl : EditControl { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(DateEditControl)); private TextBox dateField; - private HyperLink linkCalendar; - + private HyperLink linkCalendar; + /// ----------------------------------------------------------------------------- /// /// Gets dateValue returns the Date representation of the Value. @@ -55,7 +55,7 @@ protected DateTime DateValue { Logger.Error(exc); } - + return dteValue; } } @@ -100,7 +100,7 @@ protected virtual string Format } } } - + return _Format; } } @@ -126,7 +126,7 @@ protected DateTime OldDateValue { Logger.Error(exc); } - + return dteValue; } } @@ -143,15 +143,15 @@ protected override string StringValue { _StringValue = this.DateValue.ToString(this.Format); } - + return _StringValue; } - + set { this.Value = DateTime.Parse(value); } - } + } public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -167,7 +167,7 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo return dataChanged; } - + protected override void CreateChildControls() { base.CreateChildControls(); 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 890ea5ebc8a..e51f68ca213 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DateTimeEditControl.cs @@ -60,28 +60,28 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo { DateTime.TryParse(postedDate, out postedValue); } - + if (postedHours != "12" || this.is24HourClock) { int hours = 0; - if (int.TryParse(postedHours, out hours)) - { - postedValue = postedValue.AddHours(hours); - } + 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; } @@ -106,12 +106,12 @@ protected override void CreateChildControls() minHour = 0; maxHour = 23; } - + for (int i = minHour; i <= maxHour; i++) { this.hourField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); } - + this.hourField.ControlStyle.CopyFrom(this.ControlStyle); this.hourField.ID = this.ID + "hours"; this.Controls.Add(this.hourField); @@ -121,7 +121,7 @@ protected override void CreateChildControls() { this.minutesField.Items.Add(new ListItem(i.ToString("00"), i.ToString())); } - + this.minutesField.ControlStyle.CopyFrom(this.ControlStyle); this.minutesField.ID = this.ID + "minutes"; this.Controls.Add(this.minutesField); @@ -150,23 +150,23 @@ protected override void LoadDateControls() hour -= 12; isAM = false; } - + if (hour == 0) { hour = 12; } } - + if (this.hourField.Items.FindByValue(hour.ToString()) != null) { this.hourField.Items.FindByValue(hour.ToString()).Selected = true; } - + if (this.minutesField.Items.FindByValue(minute.ToString()) != null) { this.minutesField.Items.FindByValue(minute.ToString()).Selected = true; } - + if (!this.is24HourClock) { if (isAM) 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 cffd578b371..b307d9da7f0 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControl.cs @@ -34,6 +34,28 @@ public abstract class EditControl : WebControl, IPostBackDataHandler public event PropertyChangedEventHandler ValueChanged; + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether returns whether the. + /// + /// A boolean. + /// ----------------------------------------------------------------------------- + public virtual bool IsValid + { + get + { + return true; + } + } + + public virtual string EditControlClientId + { + get + { + return this.ClientID; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Custom Attributes for this Control. @@ -65,20 +87,6 @@ public object[] CustomAttributes /// ----------------------------------------------------------------------------- public PropertyEditorMode EditMode { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether returns whether the. - /// - /// A boolean. - /// ----------------------------------------------------------------------------- - public virtual bool IsValid - { - get - { - return true; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the Local Resource File for the Control. @@ -142,14 +150,6 @@ public virtual bool IsValid public UserInfo User { get; set; } - public virtual string EditControlClientId - { - get - { - return this.ClientID; - } - } - /// ----------------------------------------------------------------------------- /// /// Gets or sets stringValue is the value of the control expressed as a String. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs index 3b15b0bc4f3..17f0a4f8120 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EditControlFactory.cs @@ -24,7 +24,7 @@ public class EditControlFactory /// CreateEditControl creates the appropriate Control based on the EditorField or /// TypeDataField. /// - /// An EditorInfo object. + /// An EditorInfo object. /// /// ----------------------------------------------------------------------------- public static EditControl CreateEditControl(EditorInfo editorInfo) @@ -50,7 +50,7 @@ public static EditControl CreateEditControl(EditorInfo editorInfo) propEditor = CreateEditControlInternal(editorInfo.Type); } } - + propEditor.ID = editorInfo.Name; propEditor.Name = editorInfo.Name; propEditor.DataField = editorInfo.Name; @@ -92,7 +92,7 @@ private static EditControl CreateEditControlInternal(string systemType) { propEditor = new EnumEditControl(systemType); } - + break; } } @@ -101,7 +101,7 @@ private static EditControl CreateEditControlInternal(string systemType) { // ignore } - + return propEditor ?? new TextEditControl(systemType); } } 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 a5272269387..ede563513b3 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/EnumEditControl.cs @@ -22,20 +22,20 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:EnumEditControl runat=server>")] public class EnumEditControl : EditControl { - private readonly Type EnumType; - + private readonly Type EnumType; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs an EnumEditControl. /// /// ----------------------------------------------------------------------------- public EnumEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs an EnumEditControl. /// @@ -44,8 +44,8 @@ public EnumEditControl(string type) { this.SystemType = type; this.EnumType = Type.GetType(type); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets stringValue is the value of the control expressed as a String. @@ -59,14 +59,14 @@ protected override string StringValue var retValue = Convert.ToInt32(this.Value); return retValue.ToString(CultureInfo.InvariantCulture); } - + set { int setValue = int.Parse(value); this.Value = setValue; } - } - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged @@ -78,7 +78,7 @@ protected override void OnDataChanged(EventArgs e) int intValue = Convert.ToInt32(this.Value); int intOldValue = Convert.ToInt32(this.OldValue); - var args = new PropertyEditorEventArgs(this.Name) + var args = new PropertyEditorEventArgs(this.Name) { Value = Enum.ToObject(this.EnumType, intValue), OldValue = Enum.ToObject(this.EnumType, intOldValue) }; this.OnValueChanged(args); @@ -142,6 +142,6 @@ protected override void RenderViewMode(HtmlTextWriter writer) writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(enumValue); writer.RenderEndTag(); - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs index a9d01bffb12..0ad7d531eb2 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/IntegerEditControl.cs @@ -24,10 +24,10 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:IntegerEditControl runat=server>")] public class IntegerEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IntegerEditControl)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(IntegerEditControl)); + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs an IntegerEditControl. /// @@ -35,26 +35,6 @@ public class IntegerEditControl : EditControl public IntegerEditControl() { this.SystemType = "System.Int32"; - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets or sets stringValue is the value of the control expressed as a String. - /// - /// A string representing the Value. - /// ----------------------------------------------------------------------------- - protected override string StringValue - { - get - { - return this.IntegerValue.ToString(); - } - - set - { - int setValue = int.Parse(value); - this.Value = setValue; - } } /// ----------------------------------------------------------------------------- @@ -80,7 +60,7 @@ protected int IntegerValue { Logger.Error(exc); } - + return intValue; } } @@ -105,11 +85,31 @@ protected int OldIntegerValue { Logger.Error(exc); } - + return intValue; } - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets stringValue is the value of the control expressed as a String. + /// + /// A string representing the Value. + /// ----------------------------------------------------------------------------- + protected override string StringValue + { + get + { + return this.IntegerValue.ToString(); + } + + set + { + int setValue = int.Parse(value); + this.Value = setValue; + } + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged @@ -141,6 +141,6 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); writer.RenderEndTag(); - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs index 4613a83d074..334d4e1901a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TextEditControl.cs @@ -22,19 +22,19 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:TextEditControl runat=server>")] public class TextEditControl : EditControl - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a TextEditControl. /// /// ----------------------------------------------------------------------------- public TextEditControl() { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a TextEditControl. /// @@ -74,10 +74,10 @@ protected override string StringValue { strValue = Convert.ToString(this.Value); } - + return strValue; } - + set { this.Value = value; @@ -120,7 +120,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) } } } - + this.ControlStyle.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Type, "text"); writer.AddAttribute(HtmlTextWriterAttribute.Value, this.StringValue); @@ -128,7 +128,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, length.ToString()); } - + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID); writer.RenderBeginTag(HtmlTextWriterTag.Input); diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs index 732537d83fe..82974c07e6b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/TrueFalseEditControl.cs @@ -26,10 +26,10 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:TrueFalseEditControl runat=server>")] public class TrueFalseEditControl : EditControl { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TrueFalseEditControl)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(TrueFalseEditControl)); + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a TrueFalseEditControl. /// @@ -37,8 +37,8 @@ public class TrueFalseEditControl : EditControl public TrueFalseEditControl() { this.SystemType = "System.Boolean"; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether booleanValue returns the Boolean representation of the Value. @@ -59,7 +59,7 @@ protected bool BooleanValue { Logger.Error(exc); } - + return boolValue; } } @@ -84,7 +84,7 @@ protected bool OldBooleanValue { Logger.Error(exc); } - + return boolValue; } } @@ -101,14 +101,14 @@ protected override string StringValue { return this.BooleanValue.ToString(); } - + set { bool setValue = bool.Parse(value); this.Value = setValue; } - } - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged @@ -137,7 +137,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } - + writer.AddAttribute(HtmlTextWriterAttribute.Value, "True"); writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Input); @@ -151,7 +151,7 @@ protected override void RenderEditMode(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); } - + writer.AddAttribute(HtmlTextWriterAttribute.Value, "False"); writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); writer.RenderBeginTag(HtmlTextWriterTag.Input); @@ -160,6 +160,6 @@ protected override void RenderEditMode(HtmlTextWriter writer) writer.RenderBeginTag(HtmlTextWriterTag.Span); writer.Write(Localization.GetString("False", Localization.SharedResourceFile)); writer.RenderEndTag(); - } + } } } 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 3d3956fea8a..c4dc7f1743b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/VersionEditControl.cs @@ -19,7 +19,15 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:VersionEditControl runat=server>")] public class VersionEditControl : EditControl - { + { + protected Version Version + { + get + { + return this.Value as Version; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets stringValue is the value of the control expressed as a String. @@ -32,21 +40,13 @@ protected override string StringValue { return this.Value.ToString(); } - + set { this.Value = new Version(value); } } - protected Version Version - { - get - { - return this.Value as Version; - } - } - public override bool LoadPostData(string postDataKey, NameValueCollection postCollection) { string majorVersion = postCollection[postDataKey + "_Major"]; @@ -60,10 +60,10 @@ public override bool LoadPostData(string postDataKey, NameValueCollection postCo this.Value = postedValue; dataChanged = true; } - + return dataChanged; - } - + } + protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) { // Render the Select Tag @@ -89,8 +89,8 @@ protected void RenderDropDownList(HtmlTextWriter writer, string type, int val) // Close Select Tag writer.RenderEndTag(); - } - + } + /// ----------------------------------------------------------------------------- /// /// OnDataChanged runs when the PostbackData has changed. It raises the ValueChanged @@ -166,7 +166,7 @@ protected override void RenderViewMode(HtmlTextWriter writer) { writer.Write(this.Version.ToString(3)); } - + writer.RenderEndTag(); } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs index 246f6904a72..2217d2e6611 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/EditorInfo.cs @@ -64,7 +64,7 @@ public EditorInfo() /// GetEditor gets the appropriate Editor based on ID /// properties. /// - /// The Id of the Editor. + /// The Id of the Editor. /// /// ----------------------------------------------------------------------------- public static string GetEditor(int editorType) @@ -79,7 +79,7 @@ public static string GetEditor(int editorType) editor = definitionEntry.TextNonLocalized; } } - + return editor; } @@ -92,7 +92,7 @@ public static string GetEditor(string editorValue) { editor = definitionEntry.TextNonLocalized; } - + return editor; } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs index 6147bf73b25..98a419de6b5 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorEventArgs.cs @@ -18,21 +18,21 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class PropertyEditorEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new PropertyEditorEventArgs. /// /// The name of the property. /// ----------------------------------------------------------------------------- - public PropertyEditorEventArgs(string name) + public PropertyEditorEventArgs(string name) : this(name, null, null) { - } - + } + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new PropertyEditorEventArgs. /// diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs index a78c185ba5b..c9c6e7c8f84 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/Events/PropertyEditorItemEventArgs.cs @@ -18,9 +18,9 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class PropertyEditorItemEventArgs : EventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new PropertyEditorItemEventArgs. /// diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs index a219e91e3bc..003c730d982 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/FieldEditorControl.cs @@ -42,13 +42,13 @@ public enum HelpDisplayMode /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:FieldEditorControl runat=server>")] public class FieldEditorControl : WebControl, INamingContainer - { + { private readonly List Validators = new List(); private IEditorInfoAdapter _EditorInfoAdapter; private bool _IsValid = true; private StandardEditorInfoAdapter _StdAdapter; - private bool _Validated; - + private bool _Validated; + public FieldEditorControl() { this.ValidationExpression = Null.NullString; @@ -63,14 +63,35 @@ public FieldEditorControl() this.EditControlStyle = new Style(); this.ErrorStyle = new Style(); this.ViewStateMode = ViewStateMode.Disabled; - } - + } + public event PropertyChangedEventHandler ItemAdded; - + public event PropertyChangedEventHandler ItemChanged; - + public event EditorCreatedEventHandler ItemCreated; - + + public event PropertyChangedEventHandler ItemDeleted; + + /// ----------------------------------------------------------------------------- + /// + /// Gets a value indicating whether gets whether all of the properties are Valid. + /// + /// A Boolean. + /// ----------------------------------------------------------------------------- + public bool IsValid + { + get + { + if (!this._Validated) + { + this.Validate(); + } + + return this._IsValid; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the DataSource that is bound to this control. @@ -86,19 +107,11 @@ public FieldEditorControl() /// /// A string representing the Name of the Field. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [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; - } - } /// ----------------------------------------------------------------------------- /// @@ -139,7 +152,7 @@ public IEditorInfoAdapter EditorInfoAdapter { this._StdAdapter = new StandardEditorInfoAdapter(this.DataSource, this.DataField); } - + return this._StdAdapter; } else @@ -147,7 +160,7 @@ public IEditorInfoAdapter EditorInfoAdapter return this._EditorInfoAdapter; } } - + set { this._EditorInfoAdapter = value; @@ -187,25 +200,6 @@ public IEditorInfoAdapter EditorInfoAdapter /// ----------------------------------------------------------------------------- public bool IsDirty { get; private set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether all of the properties are Valid. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - public bool IsValid - { - get - { - if (!this._Validated) - { - this.Validate(); - } - - return this._IsValid; - } - } - public LabelMode LabelMode { get; set; } /// ----------------------------------------------------------------------------- @@ -242,19 +236,19 @@ public bool IsValid public UserInfo User { get; set; } - public string ValidationExpression { get; set; } - + public string ValidationExpression { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets the value of the Field Style. /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Edit Control.")] public Style EditControlStyle { get; private set; } @@ -264,8 +258,8 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Appearance")] + [Browsable(true)] + [Category("Appearance")] [Description("Set the Width for the Edit Control.")] public Unit EditControlWidth { get; set; } @@ -275,11 +269,11 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Error Text.")] public Style ErrorStyle { get; private set; } @@ -289,11 +283,11 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Help Text.")] public Style HelpStyle { get; private set; } @@ -303,11 +297,11 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Label Text")] public Style LabelStyle { get; private set; } @@ -317,8 +311,8 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Appearance")] + [Browsable(true)] + [Category("Appearance")] [Description("Set the Width for the Label Control.")] public Unit LabelWidth { get; set; } @@ -328,16 +322,22 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [PersistenceMode(PersistenceMode.InnerProperty)] - [TypeConverter(typeof(ExpandableObjectConverter))] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [PersistenceMode(PersistenceMode.InnerProperty)] + [TypeConverter(typeof(ExpandableObjectConverter))] [Description("Set the Style for the Visibility Control")] - public Style VisibilityStyle { get; private set; } - - public event PropertyChangedEventHandler ItemDeleted; - + public Style VisibilityStyle { get; private set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + /// ----------------------------------------------------------------------------- /// /// Binds the controls to the DataSource. @@ -386,11 +386,11 @@ public virtual void Validate() break; } } - + this._Validated = true; } - } - + } + /// ----------------------------------------------------------------------------- /// /// CreateEditor creates the control collection for this control. @@ -460,7 +460,100 @@ protected virtual void CollectionItemAdded(object sender, PropertyEditorEventArg { this.OnItemAdded(e); } - + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is removed from a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void CollectionItemDeleted(object sender, PropertyEditorEventArgs e) + { + this.OnItemDeleted(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is added to a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemAdded(PropertyEditorEventArgs e) + { + if (this.ItemAdded != null) + { + this.ItemAdded(this, e); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Editor is Created. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemCreated(PropertyEditorItemEventArgs e) + { + if (this.ItemCreated != null) + { + this.ItemCreated(this, e); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an item is removed from a collection type property. + /// + /// ----------------------------------------------------------------------------- + protected virtual void OnItemDeleted(PropertyEditorEventArgs e) + { + if (this.ItemDeleted != null) + { + this.ItemDeleted(this, e); + } + } + + protected override void OnPreRender(EventArgs e) + { + base.OnPreRender(e); + + if (string.IsNullOrEmpty(this.CssClass)) + { + this.CssClass = "dnnFormItem"; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Value of a Property changes. + /// + /// ----------------------------------------------------------------------------- + protected virtual void ValueChanged(object sender, PropertyEditorEventArgs e) + { + this.IsDirty = this.EditorInfoAdapter.UpdateValue(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when the Visibility of a Property changes. + /// + /// ----------------------------------------------------------------------------- + protected virtual void VisibilityChanged(object sender, PropertyEditorEventArgs e) + { + this.IsDirty = this.EditorInfoAdapter.UpdateVisibility(e); + } + + /// ----------------------------------------------------------------------------- + /// + /// Runs when an Item in the List Is Changed. + /// + /// Raises an ItemChanged event. + /// ----------------------------------------------------------------------------- + protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) + { + if (this.ItemChanged != null) + { + this.ItemChanged(this, e); + } + } + /// /// BuildDiv creates the Control as a Div. /// @@ -501,7 +594,7 @@ private void BuildDiv(EditorInfo editInfo) { this.Controls.Add(visibility); } - + if (propLabel != null) { this.Controls.Add(propLabel); @@ -536,7 +629,7 @@ private EditControl BuildEditor(EditorInfo editInfo) { propEditor.ControlStyle.CopyFrom(editInfo.ControlStyle); } - + propEditor.ItemAdded += this.CollectionItemAdded; propEditor.ItemDeleted += this.CollectionItemDeleted; propEditor.ValueChanged += this.ValueChanged; @@ -545,7 +638,7 @@ private EditControl BuildEditor(EditorInfo editInfo) var listEditor = (DNNListEditControl)propEditor; listEditor.ItemChanged += this.ListItemChanged; } - + this.Editor = propEditor; return propEditor; @@ -575,13 +668,13 @@ private PropertyLabelControl BuildLabel(EditorInfo editInfo) { propLabel.ShowHelp = false; } - + break; case HelpDisplayMode.Never: propLabel.ShowHelp = false; break; } - + propLabel.Caption = editInfo.Name; propLabel.HelpText = editInfo.Name; propLabel.ResourceKey = editInfo.ResourceKey; @@ -589,7 +682,7 @@ private PropertyLabelControl BuildLabel(EditorInfo editInfo) { propLabel.Width = this.LabelWidth; } - + return propLabel; } @@ -612,10 +705,10 @@ private Image BuildRequiredIcon(EditorInfo editInfo) { img.ImageUrl = this.RequiredUrl; } - + img.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); } - + return img; } @@ -638,7 +731,7 @@ private void BuildTable(EditorInfo editInfo) { labelCell.Width = this.LabelWidth; } - + // Build Editor Cell editorCell.VerticalAlign = VerticalAlign.Top; EditControl propEditor = this.BuildEditor(editInfo); @@ -648,12 +741,12 @@ private void BuildTable(EditorInfo editInfo) { editorCell.Controls.Add(requiredIcon); } - + if (editInfo.LabelMode == LabelMode.Left || editInfo.LabelMode == LabelMode.Right) { editorCell.Width = this.EditControlWidth; } - + VisibilityControl visibility = this.BuildVisibility(editInfo); if (visibility != null) { @@ -673,12 +766,12 @@ private void BuildTable(EditorInfo editInfo) labelCell.ColumnSpan = 2; labelRow.Cells.Add(labelCell); } - + if (editInfo.LabelMode == LabelMode.Top) { tbl.Rows.Add(labelRow); } - + tbl.Rows.Add(editorRow); if (editInfo.LabelMode == LabelMode.Bottom) { @@ -704,13 +797,13 @@ private void BuildTable(EditorInfo editInfo) var validatorsRow = new TableRow(); var validatorsCell = new TableCell(); validatorsCell.ColumnSpan = 2; - + // Add the Validators to the editor cell foreach (BaseValidator validator in this.Validators) { validatorsCell.Controls.Add(validator); } - + validatorsRow.Cells.Add(validatorsCell); tbl.Rows.Add(validatorsRow); @@ -741,7 +834,7 @@ private void BuildValidators(EditorInfo editInfo, string targetId) { reqValidator.CssClass = "dnnFormMessage dnnFormError"; } - + reqValidator.EnableClientScript = this.EnableClientValidation; reqValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Required"); reqValidator.ErrorMessage = editInfo.Name + " is Required"; @@ -761,7 +854,7 @@ private void BuildValidators(EditorInfo editInfo, string targetId) { regExValidator.CssClass = "dnnFormMessage dnnFormError"; } - + regExValidator.EnableClientScript = this.EnableClientValidation; regExValidator.Attributes.Add("resourcekey", editInfo.ResourceKey + ".Validation"); regExValidator.ErrorMessage = editInfo.Name + " is Invalid"; @@ -779,111 +872,18 @@ 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; - } - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is removed from a collection type property. - /// - /// ----------------------------------------------------------------------------- - protected virtual void CollectionItemDeleted(object sender, PropertyEditorEventArgs e) - { - this.OnItemDeleted(e); - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is added to a collection type property. - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemAdded(PropertyEditorEventArgs e) - { - if (this.ItemAdded != null) - { - this.ItemAdded(this, e); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Editor is Created. - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemCreated(PropertyEditorItemEventArgs e) - { - if (this.ItemCreated != null) - { - this.ItemCreated(this, e); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an item is removed from a collection type property. - /// - /// ----------------------------------------------------------------------------- - protected virtual void OnItemDeleted(PropertyEditorEventArgs e) - { - if (this.ItemDeleted != null) - { - this.ItemDeleted(this, e); - } - } - - protected override void OnPreRender(EventArgs e) - { - base.OnPreRender(e); - - if (string.IsNullOrEmpty(this.CssClass)) - { - this.CssClass = "dnnFormItem"; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Value of a Property changes. - /// - /// ----------------------------------------------------------------------------- - protected virtual void ValueChanged(object sender, PropertyEditorEventArgs e) - { - this.IsDirty = this.EditorInfoAdapter.UpdateValue(e); + return visControl; } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when the Visibility of a Property changes. - /// - /// ----------------------------------------------------------------------------- - protected virtual void VisibilityChanged(object sender, PropertyEditorEventArgs e) - { - this.IsDirty = this.EditorInfoAdapter.UpdateVisibility(e); - } - - /// ----------------------------------------------------------------------------- - /// - /// Runs when an Item in the List Is Changed. - /// - /// Raises an ItemChanged event. - /// ----------------------------------------------------------------------------- - protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) - { - if (this.ItemChanged != null) - { - this.ItemChanged(this, e); - } - } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs index e59b355158f..7edb0ef201d 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/ProfileEditorControl.cs @@ -29,7 +29,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:ProfileEditorControl runat=server>")] public class ProfileEditorControl : CollectionEditorControl - { + { /// ----------------------------------------------------------------------------- /// /// CreateEditor creates the control collection. @@ -94,13 +94,13 @@ protected override void CreateEditor() countryKey = item.Value; } } - + countryKey = "Country." + countryKey; var attributes = new object[1]; attributes[0] = new ListAttribute("Region", countryKey, ListBoundField.Id, ListBoundField.Text); editor.Editor.CustomAttributes = attributes; } } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs index 946332d752b..e0f1c3733f0 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ControlStyleAttribute.cs @@ -11,18 +11,18 @@ public sealed class ControlStyleAttribute : Attribute { private readonly string _CssClass; private readonly Unit _Height; - private readonly Unit _Width; - - /// + private readonly Unit _Width; + + /// /// Initializes a new instance of the class. /// /// The css class to apply to the associated property. public ControlStyleAttribute(string cssClass) { this._CssClass = cssClass; - } - - /// + } + + /// /// Initializes a new instance of the class. /// /// The css class to apply to the associated property. @@ -31,9 +31,9 @@ public ControlStyleAttribute(string cssClass, string width) { this._CssClass = cssClass; this._Width = Unit.Parse(width); - } - - /// + } + + /// /// Initializes a new instance of the class. /// /// The css class to apply to the associated property. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs index 3022d4d254b..32eba44c8c7 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/FormatAttribute.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class FormatAttribute : Attribute { - private readonly string _Format; - - /// + private readonly string _Format; + + /// /// Initializes a new instance of the class. /// public FormatAttribute(string format) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs index 6914ea512e2..27e5b7d3db2 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/IsReadOnlyAttribute.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class IsReadOnlyAttribute : Attribute { - private readonly bool _IsReadOnly; - - /// + private readonly bool _IsReadOnly; + + /// /// Initializes a new instance of the class. /// /// A boolean that indicates whether the property is ReadOnly. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs index 065878be742..e923d98399f 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LabelModeAttribute.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class LabelModeAttribute : Attribute { - private readonly LabelMode _Mode; - - /// + private readonly LabelMode _Mode; + + /// /// Initializes a new instance of the class. /// /// The label mode to apply to the associated property. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs index cb701383bd5..1f5eb7125d1 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/LanguagesListTypeAttribute.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class LanguagesListTypeAttribute : Attribute { - private readonly LanguagesListType _ListType; - - /// + private readonly LanguagesListType _ListType; + + /// /// Initializes a new instance of the class. /// /// The type of List. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs index 56681affd37..8ae3dd98615 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/ListAttribute.cs @@ -11,9 +11,9 @@ public sealed class ListAttribute : Attribute private readonly string _ListName; private readonly string _ParentKey; private readonly ListBoundField _TextField; - private readonly ListBoundField _ValueField; - - /// + private readonly ListBoundField _ValueField; + + /// /// Initializes a new instance of the class. /// /// The name of the List to use for this property. diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs index 80bb7b81819..22e6a365247 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/MaxLengthAttribute.cs @@ -10,9 +10,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class MaxLengthAttribute : Attribute { - private readonly int _Length = Null.NullInteger; - - /// + private readonly int _Length = Null.NullInteger; + + /// /// Initializes a new instance of the class. /// public MaxLengthAttribute(int length) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs index 4bb52b53781..73f317693d6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RegularExpressionValidatorAttribute.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class RegularExpressionValidatorAttribute : Attribute { - private readonly string _Expression; - - /// + private readonly string _Expression; + + /// /// Initializes a new instance of the class. /// public RegularExpressionValidatorAttribute(string expression) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs index acc606ff994..bc035504c60 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/RequiredAttribute.cs @@ -8,9 +8,9 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class RequiredAttribute : Attribute { - private readonly bool _Required; - - /// + private readonly bool _Required; + + /// /// Initializes a new instance of the class. /// public RequiredAttribute(bool required) diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs index f5099522114..7b9fef07990 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyAttributes/SortOrderAttribute.cs @@ -7,8 +7,8 @@ namespace DotNetNuke.UI.WebControls [AttributeUsage(AttributeTargets.Property)] public sealed class SortOrderAttribute : Attribute - { - /// + { + /// /// Initializes a new instance of the class. /// /// diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs index 9638939f036..95053f20428 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyCategoryComparer.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.UI.WebControls using System.Reflection; public class PropertyCategoryComparer : IComparer - { + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) @@ -26,7 +26,7 @@ public int Compare(object x, object y) { xCategoryName = CategoryAttribute.Default.Category; } - + object[] yCategory = yProp.GetCustomAttributes(typeof(CategoryAttribute), true); string yCategoryName = string.Empty; if (yCategory.Length > 0) @@ -37,7 +37,7 @@ public int Compare(object x, object y) { yCategoryName = CategoryAttribute.Default.Category; } - + if (xCategoryName == yCategoryName) { return string.Compare(xProp.Name, yProp.Name); @@ -51,6 +51,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type PropertyInfo"); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs index d4d0a0c24ab..3d235ed8447 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertyNameComparer.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.UI.WebControls using System.Reflection; public class PropertyNameComparer : IComparer - { + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) @@ -19,6 +19,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type PropertyInfo"); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs index 3b1fa66f23a..39232df5dc6 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/PropertySortOrderComparer.cs @@ -8,7 +8,7 @@ namespace DotNetNuke.UI.WebControls using System.Reflection; public class PropertySortOrderComparer : IComparer - { + { public int Compare(object x, object y) { if (x is PropertyInfo && y is PropertyInfo) @@ -25,7 +25,7 @@ public int Compare(object x, object y) { xSortOrderValue = SortOrderAttribute.DefaultOrder; } - + object[] ySortOrder = yProp.GetCustomAttributes(typeof(SortOrderAttribute), true); int ySortOrderValue; if (ySortOrder.Length > 0) @@ -36,7 +36,7 @@ public int Compare(object x, object y) { ySortOrderValue = SortOrderAttribute.DefaultOrder; } - + if (xSortOrderValue == ySortOrderValue) { return string.Compare(xProp.Name, yProp.Name); @@ -50,6 +50,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type PropertyInfo"); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs index 0676ff91345..a60832b513b 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyComparers/SettingNameComparer.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.UI.WebControls using System.Collections; public class SettingNameComparer : IComparer - { + { public int Compare(object x, object y) { if (x is SettingInfo && y is SettingInfo) @@ -18,6 +18,6 @@ public int Compare(object x, object y) { throw new ArgumentException("Object is not of type SettingInfo"); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs index 52389aa4173..bf0bd5595e3 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyEditorControl.cs @@ -31,10 +31,10 @@ namespace DotNetNuke.UI.WebControls /// /// ----------------------------------------------------------------------------- public class PropertyEditorControl : WebControl, INamingContainer - { + { private bool _itemChanged; - private Hashtable _sections; - + private Hashtable _sections; + public PropertyEditorControl() { this.VisibilityStyle = new Style(); @@ -50,51 +50,62 @@ public PropertyEditorControl() this.HelpDisplayMode = HelpDisplayMode.Always; this.Groups = Null.NullString; this.AutoGenerate = true; - } - + } + public event PropertyChangedEventHandler ItemAdded; - + public event EditorCreatedEventHandler ItemCreated; - - public event PropertyChangedEventHandler ItemDeleted; - + + public event PropertyChangedEventHandler ItemDeleted; + /// ----------------------------------------------------------------------------- /// - /// Gets or sets a value indicating whether gets and sets whether the editor Autogenerates its editors. + /// Gets a value indicating whether gets whether any of the properties have been changed. /// - /// The DataSource object. + /// A Boolean. /// ----------------------------------------------------------------------------- - [Category("Behavior")] - public bool AutoGenerate { get; set; } + [Browsable(false)] + public bool IsDirty + { + get + { + return this.Fields.Cast().Any(editor => editor.Visible && editor.IsDirty); + } + } /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the DataSource that is bound to this control. + /// Gets a value indicating whether gets whether all of the properties are Valid. /// - /// The DataSource object. + /// A Boolean. /// ----------------------------------------------------------------------------- - [Browsable(false)] - [Category("Data")] - public object DataSource { get; set; } - - protected override HtmlTextWriterTag TagKey + [Browsable(false)] + public bool IsValid { get { - return HtmlTextWriterTag.Div; + return this.Fields.Cast().All(editor => !editor.Visible || editor.IsValid); } } /// ----------------------------------------------------------------------------- /// - /// Gets the Underlying DataSource. + /// Gets or sets a value indicating whether gets and sets whether the editor Autogenerates its editors. /// - /// An IEnumerable Boolean. + /// The DataSource object. /// ----------------------------------------------------------------------------- - protected virtual IEnumerable UnderlyingDataSource - { - get { return this.GetProperties(); } - } + [Category("Behavior")] + public bool AutoGenerate { get; set; } + + /// ----------------------------------------------------------------------------- + /// + /// Gets or sets and sets the DataSource that is bound to this control. + /// + /// The DataSource object. + /// ----------------------------------------------------------------------------- + [Browsable(false)] + [Category("Data")] + public object DataSource { get; set; } /// ----------------------------------------------------------------------------- /// @@ -143,36 +154,6 @@ protected virtual IEnumerable UnderlyingDataSource /// ----------------------------------------------------------------------------- public HelpDisplayMode HelpDisplayMode { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether any of the properties have been changed. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - [Browsable(false)] - public bool IsDirty - { - get - { - return this.Fields.Cast().Any(editor => editor.Visible && editor.IsDirty); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Gets a value indicating whether gets whether all of the properties are Valid. - /// - /// A Boolean. - /// ----------------------------------------------------------------------------- - [Browsable(false)] - public bool IsValid - { - get - { - return this.Fields.Cast().All(editor => !editor.Visible || editor.IsValid); - } - } - public LabelMode LabelMode { get; set; } /// ----------------------------------------------------------------------------- @@ -227,22 +208,22 @@ public bool IsValid /// /// A collection of FieldEditorControl objects. /// ----------------------------------------------------------------------------- - [Category("Behavior")] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Category("Behavior")] + [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - public ArrayList Fields { get; private set; } - + public ArrayList Fields { get; private set; } + /// ----------------------------------------------------------------------------- /// /// Gets the value of the Field Style. /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Edit Control.")] public Style EditControlStyle { get; private set; } @@ -252,8 +233,8 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Appearance")] + [Browsable(true)] + [Category("Appearance")] [Description("Set the Width for the Edit Control.")] public Unit EditControlWidth { get; set; } @@ -263,11 +244,11 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Error Text.")] public Style ErrorStyle { get; private set; } @@ -277,11 +258,11 @@ public bool IsValid /// /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Group Header Control.")] public Style GroupHeaderStyle { get; private set; } @@ -291,16 +272,16 @@ public bool IsValid /// /// A boolean. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Appearance")] + [Browsable(true)] + [Category("Appearance")] [Description("Set whether to include a rule
    in the Group Header.")] public bool GroupHeaderIncludeRule { get; set; } - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Help Text.")] public Style HelpStyle { get; private set; } @@ -310,11 +291,11 @@ public bool IsValid ///
    /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Label Text")] public Style ItemStyle { get; private set; } @@ -324,11 +305,11 @@ public bool IsValid ///
    /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Label Text")] public Style LabelStyle { get; private set; } @@ -338,8 +319,8 @@ public bool IsValid ///
    /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Appearance")] + [Browsable(true)] + [Category("Appearance")] [Description("Set the Width for the Label Control.")] public Unit LabelWidth { get; set; } @@ -349,14 +330,33 @@ public bool IsValid ///
    /// A Style object. /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [PersistenceMode(PersistenceMode.InnerProperty)] + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [PersistenceMode(PersistenceMode.InnerProperty)] [Description("Set the Style for the Visibility Control")] - public Style VisibilityStyle { get; private set; } - + public Style VisibilityStyle { get; private set; } + + protected override HtmlTextWriterTag TagKey + { + get + { + return HtmlTextWriterTag.Div; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets the Underlying DataSource. + /// + /// An IEnumerable Boolean. + /// ----------------------------------------------------------------------------- + protected virtual IEnumerable UnderlyingDataSource + { + get { return this.GetProperties(); } + } + /// ----------------------------------------------------------------------------- /// /// Binds the controls to the DataSource. @@ -381,8 +381,8 @@ public override void DataBind() // Set flag so CreateChildConrols should not be invoked later in control's lifecycle this.ChildControlsCreated = true; - } - + } + /// ----------------------------------------------------------------------------- /// /// AddEditorRow builds a sigle editor row and adds it to the Table, using the @@ -401,17 +401,17 @@ protected void AddEditorRow(Table table, string name, IEditorInfoAdapter adapter 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, + 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); @@ -436,74 +436,6 @@ protected void AddEditorRow(WebControl container, string name, IEditorInfoAdapte this.Fields.Add(editor); } - - /// ----------------------------------------------------------------------------- - /// - /// GetProperties returns an array of PropertyInfo. - /// - /// An array of PropertyInfo objects - /// for the current DataSource object. - /// - /// GetProperties will return an array of public properties for the current DataSource - /// object. The properties will be sorted according to the SortMode property. - /// - /// ----------------------------------------------------------------------------- - private IEnumerable GetProperties() - { - if (this.DataSource != null) - { - // TODO: We need to add code to support using the cache in the future - const BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; - - var properties = this.DataSource.GetType().GetProperties(bindings); - - // Apply sort method - switch (this.SortMode) - { - case PropertySortType.Alphabetical: - Array.Sort(properties, new PropertyNameComparer()); - break; - case PropertySortType.Category: - Array.Sort(properties, new PropertyCategoryComparer()); - break; - case PropertySortType.SortOrderAttribute: - Array.Sort(properties, new PropertySortOrderComparer()); - break; - } - - return properties; - } - - return null; - } - - private void AddEditorRow(FieldEditorControl editor, WebControl container) - { - editor.ControlStyle.CopyFrom(this.ItemStyle); - editor.LabelStyle.CopyFrom(this.LabelStyle); - editor.HelpStyle.CopyFrom(this.HelpStyle); - editor.ErrorStyle.CopyFrom(this.ErrorStyle); - editor.VisibilityStyle.CopyFrom(this.VisibilityStyle); - editor.EditControlStyle.CopyFrom(this.EditControlStyle); - if (editor.EditControlWidth == Unit.Empty) - { - editor.EditControlWidth = this.EditControlWidth; - } - - editor.LocalResourceFile = this.LocalResourceFile; - editor.RequiredUrl = this.RequiredUrl; - editor.ShowRequired = this.ShowRequired; - editor.ShowVisibility = this.ShowVisibility; - editor.User = this.User; - editor.Width = this.Width; - editor.ItemAdded += this.CollectionItemAdded; - editor.ItemChanged += this.ListItemChanged; - editor.ItemCreated += this.EditorItemCreated; - editor.ItemDeleted += this.CollectionItemDeleted; - - editor.DataBind(); - container.Controls.Add(editor); - } /// ----------------------------------------------------------------------------- /// @@ -544,13 +476,13 @@ protected virtual void AddFields() { editor.EditMode = this.EditMode; } - + editor.HelpDisplayMode = this.HelpDisplayMode; if (editor.LabelMode == LabelMode.None) { editor.LabelMode = this.LabelMode; } - + if (editor.LabelWidth == Unit.Empty) { editor.LabelWidth = this.LabelWidth; @@ -583,13 +515,13 @@ protected virtual void AddFields(Table tbl) { editor.EditMode = this.EditMode; } - + editor.HelpDisplayMode = this.HelpDisplayMode; if (editor.LabelMode == LabelMode.None) { editor.LabelMode = this.LabelMode; } - + if (editor.LabelWidth == Unit.Empty) { editor.LabelWidth = this.LabelWidth; @@ -629,7 +561,7 @@ protected virtual void AddHeader(Table tbl, string header) { panel.Controls.Add(new LiteralControl("
    ")); } - + this.Controls.Add(panel); // Get the Hashtable @@ -637,7 +569,7 @@ protected virtual void AddHeader(Table tbl, string header) { this._sections = new Hashtable(); } - + this._sections[icon] = tbl; } @@ -701,7 +633,7 @@ protected virtual void CreateEditor() { localizedGroupName = strGroup; } - + var link = new HyperLink() { Text = localizedGroupName, NavigateUrl = "#" }; header.Controls.Add(link); @@ -714,7 +646,7 @@ protected virtual void CreateEditor() { this.AddEditorRow(container, obj); } - + this.Controls.Add(fieldset); } } @@ -784,7 +716,7 @@ protected virtual void CreateEditor() /// ----------------------------------------------------------------------------- /// /// GetCategory gets the Category of an object. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected virtual string GetCategory(object obj) @@ -799,14 +731,14 @@ protected virtual string GetCategory(object obj) var category = (CategoryAttribute)categoryAttributes[0]; categoryString = category.Category; } - + return categoryString; } /// ----------------------------------------------------------------------------- /// /// GetGroups gets an array of Groups/Categories from the DataSource. - /// + ///
    /// /// ----------------------------------------------------------------------------- protected virtual string[] GetGroups(IEnumerable arrObjects) @@ -826,13 +758,13 @@ protected virtual string[] GetGroups(IEnumerable arrObjects) } } } - + var strGroups = new string[arrGroups.Count]; for (int i = 0; i <= arrGroups.Count - 1; i++) { strGroups[i] = Convert.ToString(arrGroups[i]); } - + return strGroups; } @@ -840,7 +772,7 @@ protected virtual string[] GetGroups(IEnumerable arrObjects) /// /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property. + /// The property. /// /// ----------------------------------------------------------------------------- protected virtual bool GetRowVisibility(object obj) @@ -857,7 +789,7 @@ protected virtual bool GetRowVisibility(object obj) isVisible = false; } } - + if (!isVisible && this.EditMode == PropertyEditorMode.Edit) { // Check if property is required - as this will need to override visibility @@ -871,7 +803,7 @@ protected virtual bool GetRowVisibility(object obj) } } } - + return isVisible; } @@ -927,7 +859,7 @@ protected override void OnPreRender(EventArgs e) // editors are updated this.DataBind(); } - + if (string.IsNullOrEmpty(this.CssClass)) { this.CssClass = "dnnForm"; @@ -943,10 +875,10 @@ protected override void OnPreRender(EventArgs e) DNNClientAPI.EnableMinMax(icon, tbl, false, IconController.IconURL("Minus", "12X15"), IconController.IconURL("Plus", "12X15"), DNNClientAPI.MinMaxPersistanceType.Page); } } - + base.OnPreRender(e); - } - + } + /// ----------------------------------------------------------------------------- /// /// Runs when an item is added to a collection type property. @@ -985,6 +917,74 @@ protected virtual void EditorItemCreated(object sender, PropertyEditorItemEventA protected virtual void ListItemChanged(object sender, PropertyEditorEventArgs e) { this._itemChanged = true; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// GetProperties returns an array of PropertyInfo. + /// + /// An array of PropertyInfo objects + /// for the current DataSource object. + /// + /// GetProperties will return an array of public properties for the current DataSource + /// object. The properties will be sorted according to the SortMode property. + /// + /// ----------------------------------------------------------------------------- + private IEnumerable GetProperties() + { + if (this.DataSource != null) + { + // TODO: We need to add code to support using the cache in the future + const BindingFlags bindings = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; + + var properties = this.DataSource.GetType().GetProperties(bindings); + + // Apply sort method + switch (this.SortMode) + { + case PropertySortType.Alphabetical: + Array.Sort(properties, new PropertyNameComparer()); + break; + case PropertySortType.Category: + Array.Sort(properties, new PropertyCategoryComparer()); + break; + case PropertySortType.SortOrderAttribute: + Array.Sort(properties, new PropertySortOrderComparer()); + break; + } + + return properties; + } + + return null; + } + + private void AddEditorRow(FieldEditorControl editor, WebControl container) + { + editor.ControlStyle.CopyFrom(this.ItemStyle); + editor.LabelStyle.CopyFrom(this.LabelStyle); + editor.HelpStyle.CopyFrom(this.HelpStyle); + editor.ErrorStyle.CopyFrom(this.ErrorStyle); + editor.VisibilityStyle.CopyFrom(this.VisibilityStyle); + editor.EditControlStyle.CopyFrom(this.EditControlStyle); + if (editor.EditControlWidth == Unit.Empty) + { + editor.EditControlWidth = this.EditControlWidth; + } + + editor.LocalResourceFile = this.LocalResourceFile; + editor.RequiredUrl = this.RequiredUrl; + editor.ShowRequired = this.ShowRequired; + editor.ShowVisibility = this.ShowVisibility; + editor.User = this.User; + editor.Width = this.Width; + editor.ItemAdded += this.CollectionItemAdded; + editor.ItemChanged += this.ListItemChanged; + editor.ItemCreated += this.EditorItemCreated; + editor.ItemDeleted += this.CollectionItemDeleted; + + editor.DataBind(); + container.Controls.Add(editor); + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs index b91117e7165..f8d80f2338a 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/PropertyLabelControl.cs @@ -24,26 +24,66 @@ namespace DotNetNuke.UI.WebControls /// [ToolboxData("<{0}:PropertyLabelControl runat=server>")] public class PropertyLabelControl : WebControl - { + { protected LinkButton cmdHelp; protected HtmlGenericControl label; - private string _ResourceKey; protected Label lblHelp; protected Label lblLabel; protected Panel pnlTooltip; - protected Panel pnlHelp; - + protected Panel pnlHelp; + private string _ResourceKey; + public PropertyLabelControl() { } - + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the value of the Label Style. + /// + /// A string representing the Name of the Field. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Help Text.")] + public Style HelpStyle + { + get + { + this.EnsureChildControls(); + return this.pnlHelp.ControlStyle; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Gets and sets the value of the Label Style. + /// + /// A string representing the Name of the Field. + /// ----------------------------------------------------------------------------- + [Browsable(true)] + [Category("Styles")] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] + [TypeConverter(typeof(ExpandableObjectConverter))] + [Description("Set the Style for the Label Text")] + public Style LabelStyle + { + get + { + this.EnsureChildControls(); + return this.lblLabel.ControlStyle; + } + } + /// /// Gets or sets and Sets the Caption Text if no ResourceKey is provided. /// /// A string representing the Caption. - [Browsable(true)] - [Category("Appearance")] - [DefaultValue("Property")] + [Browsable(true)] + [Category("Appearance")] + [DefaultValue("Property")] [Description("Enter Caption for the control.")] public string Caption { @@ -52,7 +92,7 @@ public string Caption this.EnsureChildControls(); return this.lblLabel.Text; } - + set { this.EnsureChildControls(); @@ -67,21 +107,13 @@ public string AssociatedControlId this.EnsureChildControls(); return this.lblLabel.AssociatedControlID; } - + set { this.EnsureChildControls(); this.lblLabel.AssociatedControlID = value; } } - - protected override HtmlTextWriterTag TagKey - { - get - { - return HtmlTextWriterTag.Div; - } - } /// /// Gets or sets and Sets the related Edit Control. @@ -94,9 +126,9 @@ protected override HtmlTextWriterTag TagKey /// Gets or sets text is value of the Label Text if no ResourceKey is provided. /// /// A string representing the Text. - [Browsable(true)] - [Category("Appearance")] - [DefaultValue("")] + [Browsable(true)] + [Category("Appearance")] + [DefaultValue("")] [Description("Enter Help Text for the control.")] public string HelpText { @@ -105,7 +137,7 @@ public string HelpText this.EnsureChildControls(); return this.lblHelp.Text; } - + set { this.EnsureChildControls(); @@ -122,9 +154,9 @@ public string HelpText /// is the label help text, Control.ErrorMessage is the Validation Error Message for the /// control. /// - [Browsable(true)] - [Category("Localization")] - [DefaultValue("")] + [Browsable(true)] + [Category("Localization")] + [DefaultValue("")] [Description("Enter the Resource key for the control.")] public string ResourceKey { @@ -132,7 +164,7 @@ public string ResourceKey { return this._ResourceKey; } - + set { this._ResourceKey = value; @@ -145,9 +177,9 @@ public string ResourceKey } } - [Browsable(true)] - [Category("Behavior")] - [DefaultValue(false)] + [Browsable(true)] + [Category("Behavior")] + [DefaultValue(false)] [Description("Set whether the Help icon is displayed.")] public bool ShowHelp { @@ -156,21 +188,21 @@ public bool ShowHelp this.EnsureChildControls(); return this.cmdHelp.Visible; } - + set { this.EnsureChildControls(); this.cmdHelp.Visible = value; } - } - + } + /// /// Gets or sets and sets the value of the Field that is bound to the Label. /// /// A string representing the Name of the Field. - [Browsable(true)] - [Category("Data")] - [DefaultValue("")] + [Browsable(true)] + [Category("Data")] + [DefaultValue("")] [Description("Enter the name of the field that is data bound to the Label's Text property.")] public string DataField { get; set; } @@ -179,50 +211,18 @@ public bool ShowHelp /// /// The DataSource object. [Browsable(false)] - public object DataSource { get; set; } - - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the value of the Label Style. - /// - /// A string representing the Name of the Field. - /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [Description("Set the Style for the Help Text.")] - public Style HelpStyle - { - get - { - this.EnsureChildControls(); - return this.pnlHelp.ControlStyle; - } - } + public object DataSource { get; set; } - /// ----------------------------------------------------------------------------- - /// - /// Gets and sets the value of the Label Style. - /// - /// A string representing the Name of the Field. - /// ----------------------------------------------------------------------------- - [Browsable(true)] - [Category("Styles")] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] - [TypeConverter(typeof(ExpandableObjectConverter))] - [Description("Set the Style for the Label Text")] - public Style LabelStyle + public bool Required { get; set; } + + protected override HtmlTextWriterTag TagKey { get { - this.EnsureChildControls(); - return this.lblLabel.ControlStyle; + return HtmlTextWriterTag.Div; } } - public bool Required { get; set; } - /// /// CreateChildControls creates the control collection. /// @@ -281,7 +281,7 @@ protected override void OnDataBinding(EventArgs e) { this.ResourceKey = Convert.ToString(dataRow[this.DataField]); } - + if (this.DesignMode) { this.label.InnerText = Convert.ToString(dataRow[this.DataField]); @@ -324,11 +324,11 @@ protected override void OnPreRender(EventArgs e) { this.pnlHelp.ControlStyle.CssClass = string.Format("dnnClear {0}", this.pnlHelp.ControlStyle.CssClass); } - + if (!this.pnlHelp.ControlStyle.CssClass.Contains("dnnFormHelpContent")) { this.pnlHelp.ControlStyle.CssClass = string.Format("dnnFormHelpContent {0}", this.pnlHelp.ControlStyle.CssClass); } - } + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs index 5aca6713b91..384884f9213 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingInfo.cs @@ -35,7 +35,7 @@ public SettingInfo(object name, object value) { IsFound = true; } - + if (!IsFound) { try @@ -49,7 +49,7 @@ public SettingInfo(object name, object value) Logger.Error(exc); } } - + if (!IsFound) { try @@ -77,7 +77,7 @@ public Type Type { return this._Type; } - + set { this._Type = value; diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs index f972a980dec..d74469c451e 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/SettingsEditorControl.cs @@ -24,7 +24,7 @@ namespace DotNetNuke.UI.WebControls /// ----------------------------------------------------------------------------- [ToolboxData("<{0}:SettingsEditorControl runat=server>")] public class SettingsEditorControl : PropertyEditorControl - { + { /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the CustomEditors that are used by this control. @@ -40,8 +40,8 @@ public class SettingsEditorControl : PropertyEditorControl /// /// The CustomEditors object. /// ----------------------------------------------------------------------------- - public Hashtable Visibility { get; set; } - + public Hashtable Visibility { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets the Underlying DataSource. @@ -54,8 +54,8 @@ protected override IEnumerable UnderlyingDataSource { return this.GetSettings(); } - } - + } + protected override void AddEditorRow(Table table, object obj) { var info = (SettingInfo)obj; @@ -67,31 +67,6 @@ 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). - /// - /// ----------------------------------------------------------------------------- - private ArrayList GetSettings() - { - var settings = (Hashtable)this.DataSource; - var arrSettings = new ArrayList(); - IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); - while (settingsEnumerator.MoveNext()) - { - var info = new SettingInfo(settingsEnumerator.Key, settingsEnumerator.Value); - if ((this.CustomEditors != null) && (this.CustomEditors[settingsEnumerator.Key] != null)) - { - info.Editor = Convert.ToString(this.CustomEditors[settingsEnumerator.Key]); - } - - arrSettings.Add(info); - } - - arrSettings.Sort(new SettingNameComparer()); - return arrSettings; - } protected override void AddEditorRow(object obj) { @@ -103,7 +78,7 @@ protected override void AddEditorRow(object obj) /// /// GetRowVisibility determines the Visibility of a row in the table. /// - /// The property. + /// The property. /// /// ----------------------------------------------------------------------------- protected override bool GetRowVisibility(object obj) @@ -114,8 +89,33 @@ protected override bool GetRowVisibility(object obj) { _IsVisible = Convert.ToBoolean(this.Visibility[info.Name]); } - + return _IsVisible; - } + } + + /// ----------------------------------------------------------------------------- + /// + /// GetSettings converts the DataSource into an ArrayList (IEnumerable). + /// + /// ----------------------------------------------------------------------------- + private ArrayList GetSettings() + { + var settings = (Hashtable)this.DataSource; + var arrSettings = new ArrayList(); + IDictionaryEnumerator settingsEnumerator = settings.GetEnumerator(); + while (settingsEnumerator.MoveNext()) + { + var info = new SettingInfo(settingsEnumerator.Key, settingsEnumerator.Value); + if ((this.CustomEditors != null) && (this.CustomEditors[settingsEnumerator.Key] != null)) + { + info.Editor = Convert.ToString(this.CustomEditors[settingsEnumerator.Key]); + } + + arrSettings.Add(info); + } + + arrSettings.Sort(new SettingNameComparer()); + return arrSettings; + } } } diff --git a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs index 2244c67add4..0d3186fda93 100644 --- a/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs +++ b/DNN Platform/Library/UI/WebControls/PropertyEditor/VisibilityControl.cs @@ -32,8 +32,8 @@ namespace DotNetNuke.UI.WebControls [ToolboxData("<{0}:VisibilityControl runat=server>")] public class VisibilityControl : WebControl, IPostBackDataHandler, INamingContainer { - public event PropertyChangedEventHandler VisibilityChanged; - + public event PropertyChangedEventHandler VisibilityChanged; + /// /// Gets or sets caption. /// @@ -45,12 +45,6 @@ public class VisibilityControl : WebControl, IPostBackDataHandler, INamingContai /// /// 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. @@ -61,13 +55,19 @@ protected ProfileVisibility Visibility /// Gets or sets stringValue is the value of the control expressed as a String. /// /// A string representing the Value. - public object Value { get; set; } - + public object Value { get; set; } + + protected ProfileVisibility Visibility + { + get { return this.Value as ProfileVisibility; } + set { this.Value = value; } + } + /// /// LoadPostData loads the Post Back Data and determines whether the value has change. /// /// A key to the PostBack Data to load. - /// A name value collection of postback data. + /// A name value collection of postback data. /// public virtual bool LoadPostData(string postDataKey, NameValueCollection postCollection) { @@ -98,22 +98,22 @@ 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; } - + return dataChanged; } @@ -126,8 +126,8 @@ public void RaisePostDataChangedEvent() // Raise the VisibilityChanged Event var args = new PropertyEditorEventArgs(this.Name) { Value = this.Value }; this.OnVisibilityChanged(args); - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -142,72 +142,6 @@ protected override void OnPreRender(EventArgs 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) - { - // Render Li - writer.RenderBeginTag(HtmlTextWriterTag.Li); - - // Render radio button - writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); - writer.AddAttribute("aria-label", this.ID); - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); - writer.AddAttribute(HtmlTextWriterAttribute.Value, optionValue); - if (this.Visibility.VisibilityMode == selectedVisibility) - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.Write(optionText); - writer.RenderEndTag(); - - // Close Li - writer.RenderEndTag(); - } - - private void RenderCheckboxItem(HtmlTextWriter writer, string prefix, string value, string text, bool selected) - { - // Render Li - writer.RenderBeginTag(HtmlTextWriterTag.Li); - - // Render radio button - writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox"); - writer.AddAttribute("aria-label", this.ID); - writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + prefix + value); - writer.AddAttribute(HtmlTextWriterAttribute.Value, value); - if (selected) - { - writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); - } - - writer.RenderBeginTag(HtmlTextWriterTag.Input); - writer.Write(text); - writer.RenderEndTag(); - - // Close Li - writer.RenderEndTag(); - } - - private void RenderGroups(HtmlTextWriter writer) - { - foreach (var group in this.User.Social.Roles.Where((role) => role.SecurityMode != SecurityMode.SecurityRole)) - { - this.RenderCheckboxItem(writer, ":group_", group.RoleID.ToString(CultureInfo.InvariantCulture), - group.RoleName, - this.Visibility.RoleVisibilities.Count(r => r.RoleID == group.RoleID) == 1); - } - } - - private void RenderRelationships(HtmlTextWriter writer) - { - foreach (var relationship in this.User.Social.Relationships) - { - this.RenderCheckboxItem(writer, ":relationship_", relationship.RelationshipId.ToString(CultureInfo.InvariantCulture), - relationship.Name, - this.Visibility.RelationshipVisibilities.Count(r => r.RelationshipId == relationship.RelationshipId) == 1); - } - } /// /// OnVisibilityChanged runs when the Visibility has changed. It raises the VisibilityChanged @@ -286,6 +220,72 @@ protected override void Render(HtmlTextWriter writer) // Close Div writer.RenderEndTag(); - } + } + + private void RenderVisibility(HtmlTextWriter writer, string optionValue, UserVisibilityMode selectedVisibility, string optionText) + { + // Render Li + writer.RenderBeginTag(HtmlTextWriterTag.Li); + + // Render radio button + writer.AddAttribute(HtmlTextWriterAttribute.Type, "radio"); + writer.AddAttribute("aria-label", this.ID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID); + writer.AddAttribute(HtmlTextWriterAttribute.Value, optionValue); + if (this.Visibility.VisibilityMode == selectedVisibility) + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.Write(optionText); + writer.RenderEndTag(); + + // Close Li + writer.RenderEndTag(); + } + + private void RenderCheckboxItem(HtmlTextWriter writer, string prefix, string value, string text, bool selected) + { + // Render Li + writer.RenderBeginTag(HtmlTextWriterTag.Li); + + // Render radio button + writer.AddAttribute(HtmlTextWriterAttribute.Type, "checkbox"); + writer.AddAttribute("aria-label", this.ID); + writer.AddAttribute(HtmlTextWriterAttribute.Name, this.UniqueID + prefix + value); + writer.AddAttribute(HtmlTextWriterAttribute.Value, value); + if (selected) + { + writer.AddAttribute(HtmlTextWriterAttribute.Checked, "checked"); + } + + writer.RenderBeginTag(HtmlTextWriterTag.Input); + writer.Write(text); + writer.RenderEndTag(); + + // Close Li + writer.RenderEndTag(); + } + + private void RenderGroups(HtmlTextWriter writer) + { + foreach (var group in this.User.Social.Roles.Where((role) => role.SecurityMode != SecurityMode.SecurityRole)) + { + this.RenderCheckboxItem(writer, ":group_", group.RoleID.ToString(CultureInfo.InvariantCulture), + group.RoleName, + this.Visibility.RoleVisibilities.Count(r => r.RoleID == group.RoleID) == 1); + } + } + + private void RenderRelationships(HtmlTextWriter writer) + { + foreach (var relationship in this.User.Social.Relationships) + { + this.RenderCheckboxItem(writer, ":relationship_", relationship.RelationshipId.ToString(CultureInfo.InvariantCulture), + relationship.Name, + this.Visibility.RelationshipVisibilities.Count(r => r.RelationshipId == relationship.RelationshipId) == 1); + } + } } } diff --git a/DNN Platform/Library/WebControls/WebControlBase.cs b/DNN Platform/Library/WebControls/WebControlBase.cs index 0d2a4471df4..a39ef14e9ba 100644 --- a/DNN Platform/Library/WebControls/WebControlBase.cs +++ b/DNN Platform/Library/WebControls/WebControlBase.cs @@ -12,22 +12,9 @@ namespace DotNetNuke.UI.WebControls using DotNetNuke.Entities.Portals; public abstract class WebControlBase : WebControl - { + { private string _styleSheetUrl = string.Empty; - private string _theme = string.Empty; - - public string Theme - { - get - { - return this._theme; - } - - set - { - this._theme = value; - } - } + private string _theme = string.Empty; public string ResourcesFolderUrl { @@ -37,26 +24,6 @@ public string ResourcesFolderUrl } } - public string StyleSheetUrl - { - get - { - if (this._styleSheetUrl.StartsWith("~")) - { - return Globals.ResolveUrl(this._styleSheetUrl); - } - else - { - return this._styleSheetUrl; - } - } - - set - { - this._styleSheetUrl = value; - } - } - public bool IsHostMenu { get @@ -65,7 +32,7 @@ public bool IsHostMenu } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public PortalSettings PortalSettings { @@ -73,8 +40,8 @@ public PortalSettings PortalSettings { return PortalController.Instance.GetCurrentPortalSettings(); } - } - + } + public abstract string HtmlOutput { get; } [Obsolete("There is no longer the concept of an Admin Page. All pages are controlled by Permissions. Scheduled removal in v11.0.0.", true)] @@ -87,6 +54,39 @@ public bool IsAdminMenu } } + public string Theme + { + get + { + return this._theme; + } + + set + { + this._theme = value; + } + } + + public string StyleSheetUrl + { + get + { + if (this._styleSheetUrl.StartsWith("~")) + { + return Globals.ResolveUrl(this._styleSheetUrl); + } + else + { + return this._styleSheetUrl; + } + } + + set + { + this._styleSheetUrl = value; + } + } + protected override void RenderContents(HtmlTextWriter output) { output.Write(this.HtmlOutput); diff --git a/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs b/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs index 2f06dabc0df..24ba9e4efaa 100644 --- a/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs +++ b/DNN Platform/Modules/CoreMessaging/Components/CoreMessagingBusinessController.cs @@ -17,8 +17,8 @@ namespace DotNetNuke.Modules.CoreMessaging.Components public class CoreMessagingBusinessController : IUpgradeable { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreMessagingBusinessController)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(CoreMessagingBusinessController)); + public string UpgradeModule(string Version) { try @@ -55,10 +55,10 @@ public string UpgradeModule(string Version) } } } - + break; } - + return "Success"; } catch (Exception exc) @@ -67,6 +67,6 @@ public string UpgradeModule(string Version) return "Failed"; } - } + } } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs b/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs index 04c2fe2daa6..acaef0bde75 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/FileUploadController.cs @@ -58,11 +58,11 @@ private void UploadWholeFile(HttpContextBase context, ICollection s for (var i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; - if (file == null) - { - continue; - } - + if (file == null) + { + continue; + } + var fileName = Path.GetFileName(file.FileName); try @@ -76,7 +76,7 @@ private void UploadWholeFile(HttpContextBase context, ICollection s { fileIcon = Entities.Icons.IconController.IconURL("File", "32x32"); } - + statuses.Add(new FilesStatus { success = true, diff --git a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs index 489aec3f998..0bba0dc3fbb 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/FilesStatus.cs @@ -7,29 +7,28 @@ namespace DotNetNuke.Modules.CoreMessaging.Services public class FilesStatus { // ReSharper restore InconsistentNaming + public FilesStatus() { - } - - // ReSharper disable InconsistentNaming + } // ReSharper disable InconsistentNaming public bool success { get; set; } - + public string name { get; set; } - + public string extension { get; set; } - + public string type { get; set; } - + public int size { get; set; } - + public string progress { get; set; } - + public string url { get; set; } - + public string thumbnail_url { get; set; } - + public string message { get; set; } - + public int id { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs index 3a7d22425bc..9d3ca30ac4a 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/MessagingServiceController.cs @@ -30,8 +30,8 @@ namespace DotNetNuke.Modules.CoreMessaging.Services [DnnAuthorize] public class MessagingServiceController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MessagingServiceController)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MessagingServiceController)); + [HttpGet] public HttpResponseMessage Inbox(int afterMessageId, int numberOfRecords) { @@ -368,22 +368,22 @@ public HttpResponseMessage DismissAllNotifications() Logger.Error(exc); return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - } - + } + private string LocalizeActionString(string key, int desktopModuleId) { - if (string.IsNullOrEmpty(key)) - { - return string.Empty; - } - + if (string.IsNullOrEmpty(key)) + { + return string.Empty; + } + string actionString; if (desktopModuleId > 0) { var desktopModule = DesktopModuleController.GetDesktopModule(desktopModuleId, this.PortalSettings.PortalId); - var resourceFile = string.Format( + var resourceFile = string.Format( "~/DesktopModules/{0}/{1}/{2}", desktopModule.FolderName.Replace("\\", "/"), Localization.LocalResourceDirectory, @@ -413,7 +413,7 @@ private dynamic ToExpandoObject(Message message) messageObj.Body = message.Body; messageObj.DisplayDate = message.DisplayDate; messageObj.ReplyAllAllowed = message.ReplyAllAllowed; - + // base entity properties messageObj.CreatedByUserID = message.CreatedByUserID; messageObj.CreatedOnDate = message.CreatedOnDate; @@ -421,8 +421,8 @@ private dynamic ToExpandoObject(Message message) messageObj.LastModifiedOnDate = message.LastModifiedOnDate; return messageObj; - } - + } + public class ConversationDTO { public int ConversationId { get; set; } @@ -431,8 +431,8 @@ public class ConversationDTO 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 7eae090255a..44c0f81d714 100644 --- a/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs +++ b/DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs @@ -27,18 +27,18 @@ namespace DotNetNuke.Modules.CoreMessaging.Services public class SubscriptionsController : DnnApiController { private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; - private const string ViewControlResources = "~/DesktopModules/CoreMessaging/App_LocalResources/View.ascx.resx"; - + private const string ViewControlResources = "~/DesktopModules/CoreMessaging/App_LocalResources/View.ascx.resx"; + private string LocalizationFolder { get { - return string.Format( + return string.Format( "~/DesktopModules/{0}/App_LocalResources/", DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.Modules.CoreMessaging", this.PortalSettings.PortalId).FolderName); } - } - + } + /// /// Perform a search on Scoring Activities registered in the system. /// @@ -83,11 +83,11 @@ 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,12 +106,12 @@ 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); @@ -181,8 +181,8 @@ public HttpResponseMessage GetLocalizationTable(string culture) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } - } - + } + private static SubscriptionViewModel GetSubscriptionViewModel(Subscription subscription) { var model = new SubscriptionViewModel @@ -243,13 +243,13 @@ private static IEnumerable> GetLocalizationValues(s // ReSharper disable AssignNullToNotNullAttribute var headers = document.SelectNodes(@"/root/resheader").Cast().ToArray(); - + // ReSharper restore AssignNullToNotNullAttribute AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); // ReSharper disable AssignNullToNotNullAttribute foreach (var xmlNode in document.SelectNodes("/root/data").Cast()) - + // ReSharper restore AssignNullToNotNullAttribute { var name = GetNameAttribute(xmlNode).Replace(".Text", string.Empty); @@ -294,6 +294,6 @@ private static string GetNameAttribute(XmlNode node) } return null; - } + } } } diff --git a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs index a7e80124f31..74b28d3536e 100644 --- a/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/Subscriptions.ascx.cs @@ -27,22 +27,22 @@ namespace DotNetNuke.Modules.CoreMessaging public partial class Subscriptions : UserControl { - private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; - + private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; + public ModuleInstanceContext ModuleContext { get; set; } public ModuleInfo ModuleConfiguration { get { return this.ModuleContext != null ? this.ModuleContext.Configuration : null; } - + set { this.ModuleContext.Configuration = value; } } - public string LocalResourceFile { get; set; } - + public string LocalResourceFile { get; set; } + public string GetSettingsAsJson() { var settings = GetModuleSettings(PortalSettings.Current, this.ModuleConfiguration, Null.NullInteger); @@ -59,13 +59,13 @@ 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); @@ -83,7 +83,7 @@ protected override void OnLoad(EventArgs e) { this.Response.Redirect(Globals.AccessDeniedURL(), false); } - } + } private static Hashtable GetModuleSettings(PortalSettings portalSettings, ModuleInfo moduleInfo, int uniqueId) { @@ -149,33 +149,6 @@ 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() { @@ -224,6 +197,33 @@ private static string GetLoginUrl(PortalSettings portalSettings) } return returnUrl; - } + } + + /// + /// 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 }, + }; + } } } diff --git a/DNN Platform/Modules/CoreMessaging/View.ascx.cs b/DNN Platform/Modules/CoreMessaging/View.ascx.cs index 9d47e9fbc35..66545ee62ab 100644 --- a/DNN Platform/Modules/CoreMessaging/View.ascx.cs +++ b/DNN Platform/Modules/CoreMessaging/View.ascx.cs @@ -25,7 +25,7 @@ namespace DotNetNuke.Modules.CoreMessaging /// /// ----------------------------------------------------------------------------- public partial class View : PortalModuleBase - { + { public int ProfileUserId { get @@ -35,7 +35,7 @@ public int ProfileUserId { userId = int.Parse(this.Request.Params["UserId"]); } - + return userId; } } @@ -65,8 +65,8 @@ public bool DisablePrivateMessage return this.PortalSettings.DisablePrivateMessage && !this.UserInfo.IsSuperUser && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName); } - } - + } + protected override void OnInit(EventArgs e) { if (!this.Request.IsAuthenticated) @@ -76,7 +76,7 @@ protected override void OnInit(EventArgs e) UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("ContentNotAvailable", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); return; } - + if (this.UserId != this.ProfileUserId && (this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.UserTabId || this.TabId == this.PortalSettings.UserTabId)) { // Do not redirect but hide the content of the module. @@ -98,13 +98,13 @@ protected override void OnInit(EventArgs e) this.AddIe7StyleSheet(); 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() { var browser = this.Request.Browser; diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs index ea3590f5c9c..9fea793e96b 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationActionViewModel.cs @@ -7,11 +7,11 @@ namespace DotNetNuke.Modules.CoreMessaging.ViewModels public class NotificationActionViewModel { public string Name { get; set; } - + public string Description { get; set; } - + public string Confirm { get; set; } - + public string APICall { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs index da6fb9d7c24..f656003063a 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationViewModel.cs @@ -9,21 +9,21 @@ namespace DotNetNuke.Modules.CoreMessaging.ViewModels public class NotificationViewModel { public int NotificationId { get; set; } - + public string Subject { get; set; } - + public string From { get; set; } - + public string Body { get; set; } - + public string SenderAvatar { get; set; } - + public string SenderProfileUrl { get; set; } - + public string SenderDisplayName { get; set; } - + public string DisplayDate { get; set; } - + public IList Actions { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs index b20f89f5992..364bb97fc38 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/NotificationsViewModel.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Modules.CoreMessaging.ViewModels public class NotificationsViewModel { public int TotalNotifications { get; set; } - + public IList Notifications { get; set; } } } diff --git a/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs b/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs index bfa0f70bc7b..92b5a7ebd90 100644 --- a/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs +++ b/DNN Platform/Modules/CoreMessaging/ViewModels/TotalsViewModel.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Modules.CoreMessaging.ViewModels public class TotalsViewModel { public int TotalUnreadMessages { get; set; } - + public int TotalNotifications { get; set; } } } diff --git a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs index d0c93911861..2af03f13848 100644 --- a/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs +++ b/DNN Platform/Modules/DDRMenu/Common/DNNContext.cs @@ -40,12 +40,6 @@ public DNNContext(Control hostControl) Current = this; } - 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()); } @@ -62,7 +56,11 @@ public static string ModuleFolder } } - public Control HostControl { get; private set; } + public static DNNContext Current + { + get { return (DNNContext)HttpContext.Current.Items[DataName]; } + private set { HttpContext.Current.Items[DataName] = value; } + } public Page Page { @@ -84,6 +82,8 @@ public string SkinPath get { return this._SkinPath ?? (this._SkinPath = this.ActiveTab.SkinPath); } } + public Control HostControl { get; private set; } + private static string DataName { get { return _DataName ?? (_DataName = "DDRMenu.DNNContext." + ModuleName); } diff --git a/DNN Platform/Modules/DDRMenu/Controller.cs b/DNN Platform/Modules/DDRMenu/Controller.cs index 50b1bad8ff7..516855cf41e 100644 --- a/DNN Platform/Modules/DDRMenu/Controller.cs +++ b/DNN Platform/Modules/DDRMenu/Controller.cs @@ -21,11 +21,10 @@ public class Controller : IUpgradeable, IPortable { 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); + private const string ddrMenuModuleName = "DDRMenu"; + private const string ddrMenuMmoduleDefinitionName = "DDR Menu"; public string UpgradeModule(string version) { diff --git a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs index d6f13fc60b3..22f49a1e6c5 100644 --- a/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs +++ b/DNN Platform/Modules/DDRMenu/DDRMenuNavigationProvider.cs @@ -19,6 +19,16 @@ public class DDRMenuNavigationProvider : NavigationProvider { private DDRMenuControl menuControl; + public override Control NavigationControl + { + get { return this.menuControl; } + } + + public override bool SupportsPopulateOnDemand + { + get { return false; } + } + public override Alignment ControlAlignment { get; set; } public override bool IndicateChildren { get; set; } @@ -173,18 +183,8 @@ public class DDRMenuNavigationProvider : NavigationProvider public override List CustomAttributes { get; set; } - public override Control NavigationControl - { - get { return this.menuControl; } - } - public override string ControlID { get; set; } - public override bool SupportsPopulateOnDemand - { - get { return false; } - } - public override string CSSControl { get; set; } public string MenuStyle { get; set; } diff --git a/DNN Platform/Modules/DDRMenu/MenuBase.cs b/DNN Platform/Modules/DDRMenu/MenuBase.cs index 862921f6a49..f60b93dc234 100644 --- a/DNN Platform/Modules/DDRMenu/MenuBase.cs +++ b/DNN Platform/Modules/DDRMenu/MenuBase.cs @@ -43,10 +43,20 @@ public class MenuBase public TemplateDefinition TemplateDef { get; set; } + internal PortalSettings HostPortalSettings + { + get { return this.hostPortalSettings ?? (this.hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } + } + internal MenuNode RootNode { get; set; } internal bool SkipLocalisation { get; set; } + private HttpContext CurrentContext + { + get { return this.currentContext ?? (this.currentContext = HttpContext.Current); } + } + public static MenuBase Instantiate(string menuStyle) { try @@ -60,16 +70,6 @@ public static MenuBase Instantiate(string menuStyle) } } - internal PortalSettings HostPortalSettings - { - get { return this.hostPortalSettings ?? (this.hostPortalSettings = PortalController.Instance.GetCurrentPortalSettings()); } - } - - private HttpContext CurrentContext - { - get { return this.currentContext ?? (this.currentContext = HttpContext.Current); } - } - internal void ApplySettings(Settings settings) { this.menuSettings = settings; diff --git a/DNN Platform/Modules/DDRMenu/MenuNode.cs b/DNN Platform/Modules/DDRMenu/MenuNode.cs index 5c0877e25fb..366c2ac0be7 100644 --- a/DNN Platform/Modules/DDRMenu/MenuNode.cs +++ b/DNN Platform/Modules/DDRMenu/MenuNode.cs @@ -35,41 +35,34 @@ public MenuNode(List nodes) this.Children.ForEach(c => c.Parent = this); } - public int TabId { get; set; } - - public string Text { get; set; } + public MenuNode(DNNNode dnnNode, MenuNode parent) + { + this.TabId = Convert.ToInt32(dnnNode.ID); + this.Text = dnnNode.Text; + this.Url = (dnnNode.ClickAction == eClickAction.PostBack) + ? "postback:" + dnnNode.ID + : string.IsNullOrEmpty(dnnNode.JSFunction) ? dnnNode.NavigateURL : "javascript:" + dnnNode.JSFunction; + this.Enabled = dnnNode.Enabled; + this.Selected = dnnNode.Selected; + this.Breadcrumb = dnnNode.BreadCrumb; + this.Separator = dnnNode.IsBreak; + this.Icon = dnnNode.Image; + this.Target = dnnNode.Target; + this.Title = null; + this.Keywords = null; + this.Description = null; + this.Parent = parent; + this.CommandName = dnnNode.get_CustomAttribute("CommandName"); + this.CommandArgument = dnnNode.get_CustomAttribute("CommandArgument"); - public string Title { get; set; } + DNNAbstract.DNNNodeToMenuNode(dnnNode, this); - public static List ConvertDNNNodeCollection(DNNNodeCollection dnnNodes, MenuNode parent) - { - var result = new List(); - foreach (DNNNode node in dnnNodes) + if ((dnnNode.DNNNodes != null) && (dnnNode.DNNNodes.Count > 0)) { - result.Add(new MenuNode(node, parent)); + this.Children = ConvertDNNNodeCollection(dnnNode.DNNNodes, this); } - - return result; } - public string Url { get; set; } - - public bool Enabled { get; set; } - - public bool Selected { get; set; } - - public bool Breadcrumb { get; set; } - - public bool Separator { get; set; } - - public string Icon { get; set; } - - public string LargeImage { get; set; } - - public string CommandName { get; set; } - - public string CommandArgument { get; set; } - public bool First { get { return (this.Parent == null) || (this.Parent.Children[0] == this); } @@ -80,8 +73,6 @@ public bool Last get { return (this.Parent == null) || (this.Parent.Children[this.Parent.Children.Count - 1] == this); } } - public string Target { get; set; } - public int Depth { get @@ -98,6 +89,32 @@ public int Depth } } + 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; } + + public bool Selected { get; set; } + + public bool Breadcrumb { get; set; } + + public bool Separator { get; set; } + + public string Icon { get; set; } + + public string LargeImage { get; set; } + + public string CommandName { get; set; } + + public string CommandArgument { get; set; } + + public string Target { get; set; } + public string Keywords { get; set; } public string Description { get; set; } @@ -110,32 +127,15 @@ public List Children public MenuNode Parent { get; set; } - public MenuNode(DNNNode dnnNode, MenuNode parent) + public static List ConvertDNNNodeCollection(DNNNodeCollection dnnNodes, MenuNode parent) { - this.TabId = Convert.ToInt32(dnnNode.ID); - this.Text = dnnNode.Text; - this.Url = (dnnNode.ClickAction == eClickAction.PostBack) - ? "postback:" + dnnNode.ID - : string.IsNullOrEmpty(dnnNode.JSFunction) ? dnnNode.NavigateURL : "javascript:" + dnnNode.JSFunction; - this.Enabled = dnnNode.Enabled; - this.Selected = dnnNode.Selected; - this.Breadcrumb = dnnNode.BreadCrumb; - this.Separator = dnnNode.IsBreak; - this.Icon = dnnNode.Image; - this.Target = dnnNode.Target; - this.Title = null; - this.Keywords = null; - this.Description = null; - this.Parent = parent; - this.CommandName = dnnNode.get_CustomAttribute("CommandName"); - this.CommandArgument = dnnNode.get_CustomAttribute("CommandArgument"); - - DNNAbstract.DNNNodeToMenuNode(dnnNode, this); - - if ((dnnNode.DNNNodes != null) && (dnnNode.DNNNodes.Count > 0)) + var result = new List(); + foreach (DNNNode node in dnnNodes) { - this.Children = ConvertDNNNodeCollection(dnnNode.DNNNodes, this); + result.Add(new MenuNode(node, parent)); } + + return result; } public MenuNode FindById(int tabId) @@ -325,47 +325,6 @@ 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) @@ -401,6 +360,29 @@ public void WriteXml(XmlWriter writer) } } + 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 static void AddXmlAttribute(XmlWriter writer, string name, string value) { if (!string.IsNullOrEmpty(value)) @@ -426,5 +408,23 @@ private static void AddXmlElement(XmlWriter writer, string name, string value) writer.WriteElementString(name, value); } } + + 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; + } } } diff --git a/DNN Platform/Modules/DDRMenu/Settings.cs b/DNN Platform/Modules/DDRMenu/Settings.cs index 9c91c538144..6f1cfb77cfe 100644 --- a/DNN Platform/Modules/DDRMenu/Settings.cs +++ b/DNN Platform/Modules/DDRMenu/Settings.cs @@ -85,6 +85,16 @@ public static List TemplateArgumentsFromSettingString(string s return result; } + public static string ToSettingString(List clientOptions) + { + return string.Join("\r\n", clientOptions.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); + } + + public static string ToSettingString(List templateArguments) + { + return string.Join("\r\n", templateArguments.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); + } + public string ToXml() { var sb = new StringBuilder(); @@ -109,16 +119,6 @@ public override string ToString() } } - public static string ToSettingString(List clientOptions) - { - return string.Join("\r\n", clientOptions.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); - } - - public static string ToSettingString(List templateArguments) - { - return string.Join("\r\n", templateArguments.ConvertAll(o => o.Name + "=" + o.Value).ToArray()); - } - private static IEnumerable SplitIntoStrings(string fullString) { var strings = new List(fullString.Split('\r', '\n')); diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs index dd253c12942..5c9f1e69494 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TemplateDefinition.cs @@ -24,11 +24,6 @@ public class TemplateDefinition { public List ClientOptions = new List(); public List TemplateArguments = new List(); - - internal string Folder; - internal string TemplatePath; - internal string TemplateVirtualPath; - internal string TemplateHeadPath; internal readonly Dictionary> ScriptLibraries = new Dictionary>(); internal readonly List ScriptUrls = new List(); internal readonly List ScriptKeys = new List(); @@ -36,6 +31,11 @@ public class TemplateDefinition internal readonly List StyleSheets = new List(); internal readonly List DefaultClientOptions = new List(); internal readonly List DefaultTemplateArguments = new List(); + + internal string Folder; + internal string TemplatePath; + internal string TemplateVirtualPath; + internal string TemplateHeadPath; internal ITemplateProcessor Processor; private static readonly Regex RegexLinks = @@ -54,6 +54,46 @@ public void Reset() this.TemplateArguments = new List(this.DefaultTemplateArguments); } + public void AddClientOptions(List options, bool replace) + { + if (options != null) + { + foreach (var option in options) + { + var option1 = option; + if (replace) + { + this.ClientOptions.RemoveAll(o => o.Name == option1.Name); + } + + if (!this.ClientOptions.Exists(o => o.Name == option1.Name)) + { + this.ClientOptions.Add(option); + } + } + } + } + + public void AddTemplateArguments(List args, bool replace) + { + if (args != null) + { + foreach (var arg in args) + { + var arg1 = arg; + if (replace) + { + this.TemplateArguments.RemoveAll(a => a.Name == arg1.Name); + } + + if (!this.TemplateArguments.Exists(a => a.Name == arg1.Name)) + { + this.TemplateArguments.Add(arg); + } + } + } + } + internal static TemplateDefinition FromName(string templateName, string manifestName) { var manifestUrl = new PathResolver(null).Resolve( @@ -232,6 +272,59 @@ internal static TemplateDefinition FromManifest(string manifestUrl) return result; } + internal void PreRender() + { + var page = DNNContext.Current.Page; + + foreach (var stylesheet in this.StyleSheets) + { + ClientResourceManager.RegisterStyleSheet(page, stylesheet); + } + + foreach (var scriptUrl in this.ScriptUrls) + { + ClientResourceManager.RegisterScript(page, scriptUrl); + } + + foreach (var libraryInfo in this.ScriptLibraries) + { + var libraryName = libraryInfo.Key; + var parameters = libraryInfo.Value; + var libraryVersion = parameters.Item1; + var specificVersion = parameters.Item2; + if (libraryVersion == null) + { + JavaScript.RequestRegistration(libraryName); + } + else if (specificVersion == null) + { + JavaScript.RequestRegistration(libraryName, libraryVersion); + } + else + { + JavaScript.RequestRegistration(libraryName, libraryVersion, specificVersion.Value); + } + } + + foreach (var scriptKey in this.ScriptKeys) + { + var clientScript = page.ClientScript; + if (!clientScript.IsClientScriptBlockRegistered(typeof(TemplateDefinition), scriptKey)) + { + clientScript.RegisterClientScriptBlock(typeof(TemplateDefinition), scriptKey, this.Scripts[scriptKey], false); + } + } + + var headContent = string.IsNullOrEmpty(this.TemplateHeadPath) ? string.Empty : Utilities.CachedFileContent(this.TemplateHeadPath); + var expandedHead = RegexLinks.Replace(headContent, "$1" + DNNContext.Current.ActiveTab.SkinPath + "$3"); + page.Header.Controls.Add(new LiteralControl(expandedHead)); + } + + internal void Render(object source, HtmlTextWriter htmlWriter) + { + this.Processor.Render(source, htmlWriter, this); + } + private static string GetResolvedPath(XmlNode scriptElt, PathResolver pathResolver) { return pathResolver.Resolve( @@ -295,98 +388,5 @@ private static string GetObjectCheckScript(string jsObject) return string.Join(" && ", objectsToCheck.ToArray()); } - - public void AddClientOptions(List options, bool replace) - { - if (options != null) - { - foreach (var option in options) - { - var option1 = option; - if (replace) - { - this.ClientOptions.RemoveAll(o => o.Name == option1.Name); - } - - if (!this.ClientOptions.Exists(o => o.Name == option1.Name)) - { - this.ClientOptions.Add(option); - } - } - } - } - - public void AddTemplateArguments(List args, bool replace) - { - if (args != null) - { - foreach (var arg in args) - { - var arg1 = arg; - if (replace) - { - this.TemplateArguments.RemoveAll(a => a.Name == arg1.Name); - } - - if (!this.TemplateArguments.Exists(a => a.Name == arg1.Name)) - { - this.TemplateArguments.Add(arg); - } - } - } - } - - internal void PreRender() - { - var page = DNNContext.Current.Page; - - foreach (var stylesheet in this.StyleSheets) - { - ClientResourceManager.RegisterStyleSheet(page, stylesheet); - } - - foreach (var scriptUrl in this.ScriptUrls) - { - ClientResourceManager.RegisterScript(page, scriptUrl); - } - - foreach (var libraryInfo in this.ScriptLibraries) - { - var libraryName = libraryInfo.Key; - var parameters = libraryInfo.Value; - var libraryVersion = parameters.Item1; - var specificVersion = parameters.Item2; - if (libraryVersion == null) - { - JavaScript.RequestRegistration(libraryName); - } - else if (specificVersion == null) - { - JavaScript.RequestRegistration(libraryName, libraryVersion); - } - else - { - JavaScript.RequestRegistration(libraryName, libraryVersion, specificVersion.Value); - } - } - - foreach (var scriptKey in this.ScriptKeys) - { - var clientScript = page.ClientScript; - if (!clientScript.IsClientScriptBlockRegistered(typeof(TemplateDefinition), scriptKey)) - { - clientScript.RegisterClientScriptBlock(typeof(TemplateDefinition), scriptKey, this.Scripts[scriptKey], false); - } - } - - var headContent = string.IsNullOrEmpty(this.TemplateHeadPath) ? string.Empty : Utilities.CachedFileContent(this.TemplateHeadPath); - var expandedHead = RegexLinks.Replace(headContent, "$1" + DNNContext.Current.ActiveTab.SkinPath + "$3"); - page.Header.Controls.Add(new LiteralControl(expandedHead)); - } - - internal void Render(object source, HtmlTextWriter htmlWriter) - { - this.Processor.Render(source, htmlWriter, this); - } } } diff --git a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs index 039b8a02d35..bc745dee861 100644 --- a/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs +++ b/DNN Platform/Modules/DDRMenu/TemplateEngine/TokenTemplateProcessor.cs @@ -20,6 +20,7 @@ public class TokenTemplateProcessor : ITemplateProcessor { private static readonly Dictionary aliases = new Dictionary { { "page", "node" }, { "name", "text" } }; + private static readonly Regex TemplatesRegex = new Regex( @"(\[(?(\*|\*\>|\/\*|\>|\/\>|\?|\?!|\/\?|\=))(?[A-Z]*)(-(?[0-9A-Z]*))?\])", diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs index ba6b3ccbd3a..78d832913f6 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsController.cs @@ -40,8 +40,8 @@ namespace DotNetNuke.Modules.DigitalAssets.Components.Controllers public class DigitalAssetsController : IDigitalAssetsController, IUpgradeable { protected static readonly DigitalAssetsSettingsRepository SettingsRepository = new DigitalAssetsSettingsRepository(); - private static readonly Hashtable MappedPathsSupported = new Hashtable(); - + private static readonly Hashtable MappedPathsSupported = new Hashtable(); + private static bool IsHostMenu { get @@ -49,7 +49,7 @@ private static bool IsHostMenu return Globals.IsHostTab(PortalSettings.Current.ActiveTab.TabID); } } - + public IEnumerable GetDefaultFolderProviderValues(int moduleId) { var portalId = this.GetCurrentPortalId(moduleId); @@ -74,182 +74,10 @@ public IEnumerable GetDefaultFolderProviderValues(int moduleI { folderTypeId = FolderMappingController.Instance.GetDefaultFolderMapping(this.GetCurrentPortalId(moduleId)).FolderMappingID; } - - return folderTypeId; - } - - private static string GetFileIconUrl(string extension) - { - if (!string.IsNullOrEmpty(extension) && File.Exists(HttpContext.Current.Server.MapPath(IconController.IconURL("Ext" + extension, "32x32", "Standard")))) - { - return IconController.IconURL("Ext" + extension, "32x32", "Standard"); - } - - return IconController.IconURL("ExtFile", "32x32", "Standard"); - } - - private IFolderInfo GetFolderInfo(int folderId) - { - var folder = FolderManager.Instance.GetFolder(folderId); - if (folder == null) - { - throw new DotNetNukeException(LocalizationHelper.GetString("FolderDoesNotExists.Error")); - } - - return folder; - } - - private IEnumerable GetPermissionViewModelCollection(IFolderInfo folder) - { - // TODO Split permission between CE and PE packages - string[] permissionKeys = { "ADD", "BROWSE", "COPY", "READ", "WRITE", "DELETE", "MANAGE", "VIEW", "FULLCONTROL" }; - - return permissionKeys.Select(permissionKey => new PermissionViewModel { Key = permissionKey, Value = this.HasPermission(folder, permissionKey) }).ToList(); - } - - private FolderMappingViewModel GetFolderMappingViewModel(FolderMappingInfo folderMapping) - { - return new FolderMappingViewModel - { - Id = folderMapping.FolderMappingID, - FolderTypeName = folderMapping.FolderProviderType, - Name = folderMapping.MappingName, - }; - } - - private Field GetTotalFilesField(IFolderInfo folder) - { - var field = new Field(DefaultMetadataNames.TotalFiles); - field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); - var totalFiles = Convert.ToInt32(FolderManager.Instance.GetFiles(folder, true, false).Count()); - field.Type = totalFiles.GetType(); - field.Value = totalFiles; - field.StringValue = field.Value.ToString(); - return field; - } - - private Field GetFolderSizeField(IFolderInfo folder) - { - var field = new Field(DefaultMetadataNames.Size); - var size = FolderManager.Instance.GetFiles(folder, true, false).Sum(f => (long)f.Size); - field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); - field.Type = size.GetType(); - field.Value = size; - field.StringValue = string.Format(new FileSizeFormatProvider(), "{0:fs}", size); - - return field; - } - - private Field GetFileKindField(IFileInfo file) - { - var field = new Field(DefaultMetadataNames.Type); - field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); - field.Type = file.Extension.GetType(); - field.Value = file.Extension; - field.StringValue = field.Value.ToString(); - - return field; - } - - private Field GetFileSizeField(IFileInfo file) - { - var field = new Field(DefaultMetadataNames.Size); - field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); - field.Type = file.Size.GetType(); - field.Value = file.Size; - field.StringValue = string.Format(new FileSizeFormatProvider(), "{0:fs}", file.Size); - - return field; - } - - private List GetFolderPreviewFields(IFolderInfo folder) - { - var fields = new List - { - this.GetFolderSizeField(folder), - this.GetTotalFilesField(folder), - }; - fields.AddRange(this.GetAuditFields((FolderInfo)folder, folder.PortalID)); - return fields; - } - - private List GetFilePreviewFields(IFileInfo file) - { - var fields = new List - { - this.GetFileKindField(file), - this.GetFileSizeField(file), - }; - fields.AddRange(this.GetAuditFields((FileInfo)file, file.PortalId)); - return fields; - } - - private IEnumerable GetAuditFields(BaseEntityInfo item, int portalId) - { - var createdByUser = item.CreatedByUser(portalId); - var lastModifiedByUser = item.LastModifiedByUser(portalId); - return new List - { - new Field(DefaultMetadataNames.Created) - { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Created + ".DisplayName"), - Type = typeof(DateTime), - Value = item.CreatedOnDate, - StringValue = item.CreatedOnDate.ToString(CultureInfo.CurrentCulture), - }, - new Field(DefaultMetadataNames.CreatedBy) - { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.CreatedBy + ".DisplayName"), - Type = typeof(int), - Value = item.CreatedByUserID, - StringValue = createdByUser != null ? createdByUser.DisplayName : string.Empty, - }, - new Field(DefaultMetadataNames.Modified) - { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Modified + ".DisplayName"), - Type = typeof(DateTime), - Value = item.LastModifiedOnDate, - StringValue = item.LastModifiedOnDate.ToString(CultureInfo.CurrentCulture), - }, - new Field(DefaultMetadataNames.ModifiedBy) - { - DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.ModifiedBy + ".DisplayName"), - Type = typeof(int), - Value = item.LastModifiedByUserID, - StringValue = lastModifiedByUser != null ? lastModifiedByUser.DisplayName : string.Empty - }, - }; - } - private bool AreMappedPathsSupported(int folderMappingId) - { - if (MappedPathsSupported.ContainsKey(folderMappingId)) - { - return (bool)MappedPathsSupported[folderMappingId]; - } - - var folderMapping = FolderMappingController.Instance.GetFolderMapping(folderMappingId); - var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); - var result = folderProvider.SupportsMappedPaths; - MappedPathsSupported[folderMappingId] = result; - return result; + return folderTypeId; } - private string GetUnlinkAllowedStatus(IFolderInfo folder) - { - if (this.AreMappedPathsSupported(folder.FolderMappingID) && folder.ParentID > 0 && this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID) - { - return "onlyUnlink"; - } - - if (this.AreMappedPathsSupported(folder.FolderMappingID)) - { - return "true"; - } - - return "false"; - } - public int GetCurrentPortalId(int moduleId) { if (PortalSettings.Current.UserInfo.IsSuperUser) @@ -284,7 +112,7 @@ public IEnumerable GetFolders(int moduleId, int folderId) // The user cannot access the content return new List(); } - + return AssetManager.Instance.GetFolders(folder, "FolderName", true).Select(this.GetFolderViewModel); } @@ -379,42 +207,6 @@ public FolderViewModel CreateFolder(string folderName, int folderParentID, int f return this.GetFolderViewModel(AssetManager.Instance.CreateFolder(folderName, folderParentID, folderMappingID, mappedPath)); } - private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings) - { - const int AllUsersRoleId = -1; - var groupFolderPath = "Groups/" + groupId; - - if (!FolderManager.Instance.FolderExists(portalSettings.PortalId, groupFolderPath)) - { - var pc = new PermissionController(); - var browsePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "BROWSE").Cast().FirstOrDefault(); - var readPermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ").Cast().FirstOrDefault(); - var writePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "WRITE").Cast().FirstOrDefault(); - - if (!FolderManager.Instance.FolderExists(portalSettings.PortalId, "Groups")) - { - var folder = FolderManager.Instance.AddFolder(portalSettings.PortalId, "Groups"); - - folder.FolderPermissions.Remove(browsePermission.PermissionID, AllUsersRoleId, Null.NullInteger); - folder.FolderPermissions.Remove(readPermission.PermissionID, AllUsersRoleId, Null.NullInteger); - folder.IsProtected = true; - FolderManager.Instance.UpdateFolder(folder); - } - - var groupFolder = FolderManager.Instance.AddFolder(portalSettings.PortalId, groupFolderPath); - - groupFolder.FolderPermissions.Add(new FolderPermissionInfo(browsePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); - groupFolder.FolderPermissions.Add(new FolderPermissionInfo(readPermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); - groupFolder.FolderPermissions.Add(new FolderPermissionInfo(writePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); - - groupFolder.IsProtected = true; - FolderManager.Instance.UpdateFolder(groupFolder); - return groupFolder; - } - - return FolderManager.Instance.GetFolder(portalSettings.PortalId, groupFolderPath); - } - public ItemViewModel GetFile(int fileID) { return this.GetItemViewModel(FileManager.Instance.GetFile(fileID, true)); @@ -423,13 +215,13 @@ public ItemViewModel GetFile(int fileID) public void UnlinkFolder(int folderID) { var folder = FolderManager.Instance.GetFolder(folderID); - + // Check if user has appropiate permissions if (!this.HasPermission(folder, "DELETE")) { throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToUnlinkFolder.Error")); } - + FolderManager.Instance.UnlinkFolder(folder); } @@ -440,7 +232,7 @@ public int GetMappedSubFoldersCount(IEnumerable items, int po { return totalSubfoldersCount; } - + var allFolders = FolderManager.Instance.GetFolders(portalID); foreach (var item in items.Where(i => i.IsFolder && this.HasPermission(FolderManager.Instance.GetFolder(i.ItemID), "VIEW"))) { @@ -448,7 +240,7 @@ public int GetMappedSubFoldersCount(IEnumerable items, int po var allSubFolders = allFolders.Where(f => f.FolderPath.StartsWith(folder.FolderPath)); totalSubfoldersCount = totalSubfoldersCount + allSubFolders.Count(f => this.GetUnlinkAllowedStatus(f) == "onlyUnlink"); } - + return totalSubfoldersCount; } @@ -496,10 +288,10 @@ 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; } @@ -588,7 +380,7 @@ public string GetUrl(int fileId) throw new DotNetNukeException(LocalizationHelper.GetString("UserHasNoPermissionToDownload.Error")); } } - + return FileManager.Instance.GetUrl(file); } @@ -649,8 +441,8 @@ public ZipExtractViewModel UnzipFile(int fileId, bool overwrite) public virtual int GetInitialTab(NameValueCollection requestParams, NameValueCollection damState) { return 0; // Always - } - + } + public bool HasPermission(IFolderInfo folder, string permissionKey) { var hasPermision = PortalSettings.Current.UserInfo.IsSuperUser; @@ -662,7 +454,7 @@ public bool HasPermission(IFolderInfo folder, string permissionKey) return hasPermision; } - + public string UpgradeModule(string version) { try @@ -675,7 +467,7 @@ public string UpgradeModule(string version) // Add tab to Admin Menu if (mDef != null) { - var hostPage = Upgrade.AddHostPage( + var hostPage = Upgrade.AddHostPage( "File Management", "Manage assets.", "~/Icons/Sigma/Files_16X16_Standard.png", @@ -685,7 +477,7 @@ public string UpgradeModule(string version) // Add module to page Upgrade.AddModuleToPage(hostPage, mDef.ModuleDefID, "File Management", "~/Icons/Sigma/Files_32X32_Standard.png", true); - Upgrade.AddAdminPages( + Upgrade.AddAdminPages( "File Management", "Manage assets within the portal", "~/Icons/Sigma/Files_16X16_Standard.png", @@ -705,7 +497,7 @@ public string UpgradeModule(string version) break; } - + return "Success"; } catch (Exception) @@ -805,18 +597,6 @@ 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"); @@ -828,6 +608,226 @@ protected string GetFolderIconUrl(int portalId, int folderMappingID) } return imageUrl; - } + } + + private static string GetFileIconUrl(string extension) + { + if (!string.IsNullOrEmpty(extension) && File.Exists(HttpContext.Current.Server.MapPath(IconController.IconURL("Ext" + extension, "32x32", "Standard")))) + { + return IconController.IconURL("Ext" + extension, "32x32", "Standard"); + } + + return IconController.IconURL("ExtFile", "32x32", "Standard"); + } + + private IFolderInfo GetFolderInfo(int folderId) + { + var folder = FolderManager.Instance.GetFolder(folderId); + if (folder == null) + { + throw new DotNetNukeException(LocalizationHelper.GetString("FolderDoesNotExists.Error")); + } + + return folder; + } + + private IEnumerable GetPermissionViewModelCollection(IFolderInfo folder) + { + // TODO Split permission between CE and PE packages + string[] permissionKeys = { "ADD", "BROWSE", "COPY", "READ", "WRITE", "DELETE", "MANAGE", "VIEW", "FULLCONTROL" }; + + return permissionKeys.Select(permissionKey => new PermissionViewModel { Key = permissionKey, Value = this.HasPermission(folder, permissionKey) }).ToList(); + } + + private FolderMappingViewModel GetFolderMappingViewModel(FolderMappingInfo folderMapping) + { + return new FolderMappingViewModel + { + Id = folderMapping.FolderMappingID, + FolderTypeName = folderMapping.FolderProviderType, + Name = folderMapping.MappingName, + }; + } + + private Field GetTotalFilesField(IFolderInfo folder) + { + var field = new Field(DefaultMetadataNames.TotalFiles); + field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); + var totalFiles = Convert.ToInt32(FolderManager.Instance.GetFiles(folder, true, false).Count()); + field.Type = totalFiles.GetType(); + field.Value = totalFiles; + field.StringValue = field.Value.ToString(); + return field; + } + + private Field GetFolderSizeField(IFolderInfo folder) + { + var field = new Field(DefaultMetadataNames.Size); + var size = FolderManager.Instance.GetFiles(folder, true, false).Sum(f => (long)f.Size); + field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); + field.Type = size.GetType(); + field.Value = size; + field.StringValue = string.Format(new FileSizeFormatProvider(), "{0:fs}", size); + + return field; + } + + private Field GetFileKindField(IFileInfo file) + { + var field = new Field(DefaultMetadataNames.Type); + field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); + field.Type = file.Extension.GetType(); + field.Value = file.Extension; + field.StringValue = field.Value.ToString(); + + return field; + } + + private Field GetFileSizeField(IFileInfo file) + { + var field = new Field(DefaultMetadataNames.Size); + field.DisplayName = LocalizationHelper.GetString("Field" + field.Name + ".DisplayName"); + field.Type = file.Size.GetType(); + field.Value = file.Size; + field.StringValue = string.Format(new FileSizeFormatProvider(), "{0:fs}", file.Size); + + return field; + } + + private List GetFolderPreviewFields(IFolderInfo folder) + { + var fields = new List + { + this.GetFolderSizeField(folder), + this.GetTotalFilesField(folder), + }; + fields.AddRange(this.GetAuditFields((FolderInfo)folder, folder.PortalID)); + return fields; + } + + private List GetFilePreviewFields(IFileInfo file) + { + var fields = new List + { + this.GetFileKindField(file), + this.GetFileSizeField(file), + }; + fields.AddRange(this.GetAuditFields((FileInfo)file, file.PortalId)); + return fields; + } + + private IEnumerable GetAuditFields(BaseEntityInfo item, int portalId) + { + var createdByUser = item.CreatedByUser(portalId); + var lastModifiedByUser = item.LastModifiedByUser(portalId); + return new List + { + new Field(DefaultMetadataNames.Created) + { + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Created + ".DisplayName"), + Type = typeof(DateTime), + Value = item.CreatedOnDate, + StringValue = item.CreatedOnDate.ToString(CultureInfo.CurrentCulture), + }, + new Field(DefaultMetadataNames.CreatedBy) + { + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.CreatedBy + ".DisplayName"), + Type = typeof(int), + Value = item.CreatedByUserID, + StringValue = createdByUser != null ? createdByUser.DisplayName : string.Empty, + }, + new Field(DefaultMetadataNames.Modified) + { + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.Modified + ".DisplayName"), + Type = typeof(DateTime), + Value = item.LastModifiedOnDate, + StringValue = item.LastModifiedOnDate.ToString(CultureInfo.CurrentCulture), + }, + new Field(DefaultMetadataNames.ModifiedBy) + { + DisplayName = LocalizationHelper.GetString("Field" + DefaultMetadataNames.ModifiedBy + ".DisplayName"), + Type = typeof(int), + Value = item.LastModifiedByUserID, + StringValue = lastModifiedByUser != null ? lastModifiedByUser.DisplayName : string.Empty + }, + }; + } + + private bool AreMappedPathsSupported(int folderMappingId) + { + if (MappedPathsSupported.ContainsKey(folderMappingId)) + { + return (bool)MappedPathsSupported[folderMappingId]; + } + + var folderMapping = FolderMappingController.Instance.GetFolderMapping(folderMappingId); + var folderProvider = FolderProvider.Instance(folderMapping.FolderProviderType); + var result = folderProvider.SupportsMappedPaths; + MappedPathsSupported[folderMappingId] = result; + return result; + } + + private string GetUnlinkAllowedStatus(IFolderInfo folder) + { + if (this.AreMappedPathsSupported(folder.FolderMappingID) && folder.ParentID > 0 && this.GetFolder(folder.ParentID).FolderMappingID != folder.FolderMappingID) + { + return "onlyUnlink"; + } + + if (this.AreMappedPathsSupported(folder.FolderMappingID)) + { + return "true"; + } + + return "false"; + } + + private IFolderInfo EnsureGroupFolder(int groupId, PortalSettings portalSettings) + { + const int AllUsersRoleId = -1; + var groupFolderPath = "Groups/" + groupId; + + if (!FolderManager.Instance.FolderExists(portalSettings.PortalId, groupFolderPath)) + { + var pc = new PermissionController(); + var browsePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "BROWSE").Cast().FirstOrDefault(); + var readPermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "READ").Cast().FirstOrDefault(); + var writePermission = pc.GetPermissionByCodeAndKey("SYSTEM_FOLDER", "WRITE").Cast().FirstOrDefault(); + + if (!FolderManager.Instance.FolderExists(portalSettings.PortalId, "Groups")) + { + var folder = FolderManager.Instance.AddFolder(portalSettings.PortalId, "Groups"); + + folder.FolderPermissions.Remove(browsePermission.PermissionID, AllUsersRoleId, Null.NullInteger); + folder.FolderPermissions.Remove(readPermission.PermissionID, AllUsersRoleId, Null.NullInteger); + folder.IsProtected = true; + FolderManager.Instance.UpdateFolder(folder); + } + + var groupFolder = FolderManager.Instance.AddFolder(portalSettings.PortalId, groupFolderPath); + + groupFolder.FolderPermissions.Add(new FolderPermissionInfo(browsePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); + groupFolder.FolderPermissions.Add(new FolderPermissionInfo(readPermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); + groupFolder.FolderPermissions.Add(new FolderPermissionInfo(writePermission) { FolderPath = groupFolder.FolderPath, RoleID = groupId, AllowAccess = true }); + + groupFolder.IsProtected = true; + FolderManager.Instance.UpdateFolder(groupFolder); + return groupFolder; + } + + return FolderManager.Instance.GetFolder(portalSettings.PortalId, groupFolderPath); + } + + 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); + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs index 0e82983c477..46af25bb46d 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/DigitalAssetsSettingsRepository.cs @@ -83,18 +83,6 @@ 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)); @@ -128,10 +116,22 @@ internal bool SettingExists(int moduleId, string settingName) internal void SetDefaultFilterCondition(int moduleId) { // handle upgrades where FilterCondition didn't exist - if (this.SettingExists(moduleId, "RootFolderId") && !this.SettingExists(moduleId, "FilterCondition")) - { - this.SaveFilterCondition(moduleId, FilterCondition.FilterByFolder); - } + if (this.SettingExists(moduleId, "RootFolderId") && !this.SettingExists(moduleId, "FilterCondition")) + { + this.SaveFilterCondition(moduleId, FilterCondition.FilterByFolder); + } + } + + private bool IsGroupMode(int moduleId) + { + var groupMode = this.GetSettingByKey(moduleId, GroupModeSetting); + + if (string.IsNullOrEmpty(groupMode)) + { + return false; + } + + return Convert.ToBoolean(groupMode); } private string GetSettingByKey(int moduleId, string key) diff --git a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs index 3231ef00325..9ba8eef41dc 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/Controllers/IDigitalAssetsController.cs @@ -133,7 +133,7 @@ public interface IDigitalAssetsController /// Get the number of subfolders which support Mapped Path. ///
    /// Items list. - /// Portal ID. + /// Portal ID. /// int GetMappedSubFoldersCount(IEnumerable items, int portalID); diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs index a8ceec9cb68..4b51245d2ff 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/DefaultMenuButtonItem.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Modules.DigitalAssets.Components.ExtensionPoint.ToolBarButt using DotNetNuke.UI.Modules; public class DefaultMenuButtonItem : IMenuButtonItemExtensionPoint - { + { public DefaultMenuButtonItem(string itemId, string itemType, string itemCssClass, string itemText, string itemAction, string itemIcon, int itemOrder, string itemAttributes) { this.ItemId = itemId; @@ -23,6 +23,11 @@ public DefaultMenuButtonItem(string itemId, string itemType, string itemCssClass this.Action = itemAction; } + public bool Visible + { + get { return true; } + } + public string ItemId { get; private set; } public string Attributes { get; private set; } @@ -39,11 +44,6 @@ public DefaultMenuButtonItem(string itemId, string itemType, string itemCssClass public string CssClass { get; private set; } - public bool Visible - { - get { return true; } - } - public ModuleInstanceContext ModuleContext { get; set; } } } diff --git a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs index 9a5a53cfbb9..68fb600e5a2 100644 --- a/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs +++ b/DNN Platform/Modules/DigitalAssets/Components/ExtensionPoint/ToolBarButton/ManageFolderTypesToolBarButtonExtensionPoint.cs @@ -83,10 +83,10 @@ public int Order public bool Enabled { - get - { + get + { return this.ModuleContext != null - && ModulePermissionController.CanManageModule(this.ModuleContext.Configuration); + && ModulePermissionController.CanManageModule(this.ModuleContext.Configuration); } } diff --git a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs index 0250971fc19..784bc99a88e 100644 --- a/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/EditFolderMapping.ascx.cs @@ -21,15 +21,15 @@ namespace DotNetNuke.Modules.DigitalAssets public partial class EditFolderMapping : PortalModuleBase { private readonly INavigationManager _navigationManager; - + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - private int _folderMappingID = Null.NullInteger; - + private int _folderMappingID = Null.NullInteger; + public EditFolderMapping() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + public int FolderPortalID { get @@ -49,11 +49,11 @@ public int FolderMappingID int.TryParse(this.Request.QueryString["ItemID"], out this._folderMappingID); } } - + return this._folderMappingID; } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -110,17 +110,17 @@ 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"); - if (!this.Page.IsValid) - { - return; - } - + if (!this.Page.IsValid) + { + return; + } + try { var folderMapping = new FolderMappingInfo(); @@ -164,7 +164,7 @@ private void cmdUpdate_Click(object sender, EventArgs e) { this._folderMappingController.DeleteFolderMapping(this.FolderPortalID, folderMappingID); } - + return; } } @@ -192,17 +192,17 @@ private void cmdUpdate_Click(object sender, EventArgs e) return; } - if (!this.Response.IsRequestBeingRedirected) - { - this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "FolderMappings", "mid=" + this.ModuleId, "popUp=true")); - } + if (!this.Response.IsRequestBeingRedirected) + { + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, "FolderMappings", "mid=" + this.ModuleId, "popUp=true")); + } } catch (Exception exc) { Exceptions.ProcessModuleLoadException(this, exc); } } - + private void BindFolderProviders() { var defaultProviders = DefaultFolderProviders.GetDefaultProviders(); @@ -211,7 +211,7 @@ private void BindFolderProviders() { this.FolderProvidersComboBox.AddItem(provider, provider); } - + this.FolderProvidersComboBox.InsertItem(0, string.Empty, string.Empty); } @@ -239,24 +239,24 @@ private void BindFolderMappingSettings() folderProviderType = this.FolderProvidersComboBox.SelectedValue; } - if (string.IsNullOrEmpty(folderProviderType)) - { - return; - } - + if (string.IsNullOrEmpty(folderProviderType)) + { + return; + } + var settingsControlVirtualPath = FolderProvider.Instance(folderProviderType).GetSettingsControlVirtualPath(); - if (string.IsNullOrEmpty(settingsControlVirtualPath)) - { - return; - } - + if (string.IsNullOrEmpty(settingsControlVirtualPath)) + { + return; + } + var settingsControl = this.LoadControl(settingsControlVirtualPath); - if (settingsControl == null || !(settingsControl is FolderMappingSettingsControlBase)) - { - return; - } - - // This is important to allow settings control to be localizable + if (settingsControl == null || !(settingsControl is FolderMappingSettingsControlBase)) + { + return; + } + + // This is important to allow settings control to be localizable var baseType = settingsControl.GetType().BaseType; if (baseType != null) { @@ -265,6 +265,6 @@ private void BindFolderMappingSettings() this.ProviderSettingsPlaceHolder.Controls.Clear(); this.ProviderSettingsPlaceHolder.Controls.Add(settingsControl); - } + } } } diff --git a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs index 182d69904f2..7e76bc30894 100644 --- a/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FileFieldsControl.ascx.cs @@ -23,7 +23,7 @@ public partial class FileFieldsControl : PortalModuleBase, IFieldsControl public ItemViewModel Item { get; private set; } protected IFileInfo File { get; private set; } - + public virtual void PrepareProperties() { this.FileNameInput.Text = this.Item.ItemName; @@ -31,24 +31,6 @@ public virtual void PrepareProperties() this.FileNameInvalidCharactersValidator.ErrorMessage = this.Controller.GetInvalidCharsErrorText(); } - private void PrepareFileAttributes() - { - this.FileAttributeArchiveCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Archive) == FileAttributes.Archive; - this.FileAttributeHiddenCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; - this.FileAttributeReadonlyCheckBox.Checked = (this.File.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; - this.FileAttributeSystemCheckBox.Checked = (this.File.FileAttributes & FileAttributes.System) == FileAttributes.System; - } - - private FileAttributes GetFileAttributesUpdated(FileAttributes? attributes) - { - var result = this.FileAttributeArchiveCheckBox.Checked ? (attributes | FileAttributes.Archive) : (attributes & ~FileAttributes.Archive); - result = this.FileAttributeHiddenCheckBox.Checked ? (result | FileAttributes.Hidden) : (result & ~FileAttributes.Hidden); - result = this.FileAttributeReadonlyCheckBox.Checked ? (result | FileAttributes.ReadOnly) : (result & ~FileAttributes.ReadOnly); - result = this.FileAttributeSystemCheckBox.Checked ? (result | FileAttributes.System) : (result & ~FileAttributes.System); - - return result.Value; - } - public void SetController(IDigitalAssetsController damController) { this.Controller = damController; @@ -59,27 +41,6 @@ public void SetModuleConfiguration(ModuleInfo moduleConfiguration) this.ModuleConfiguration = moduleConfiguration; } - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - if (!this.Page.IsPostBack) - { - this.PrepareProperties(); - this.FileAttributesContainer.Visible = this.File.SupportsFileAttributes; - if (this.File.SupportsFileAttributes) - { - this.PrepareFileAttributes(); - } - } - } - public void SetItemViewModel(ItemViewModel itemViewModel) { this.Item = itemViewModel; @@ -116,5 +77,44 @@ public virtual object SaveProperties() return this.File; } + + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + if (!this.Page.IsPostBack) + { + this.PrepareProperties(); + this.FileAttributesContainer.Visible = this.File.SupportsFileAttributes; + if (this.File.SupportsFileAttributes) + { + this.PrepareFileAttributes(); + } + } + } + + private void PrepareFileAttributes() + { + this.FileAttributeArchiveCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Archive) == FileAttributes.Archive; + this.FileAttributeHiddenCheckBox.Checked = (this.File.FileAttributes & FileAttributes.Hidden) == FileAttributes.Hidden; + this.FileAttributeReadonlyCheckBox.Checked = (this.File.FileAttributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly; + this.FileAttributeSystemCheckBox.Checked = (this.File.FileAttributes & FileAttributes.System) == FileAttributes.System; + } + + private FileAttributes GetFileAttributesUpdated(FileAttributes? attributes) + { + var result = this.FileAttributeArchiveCheckBox.Checked ? (attributes | FileAttributes.Archive) : (attributes & ~FileAttributes.Archive); + result = this.FileAttributeHiddenCheckBox.Checked ? (result | FileAttributes.Hidden) : (result & ~FileAttributes.Hidden); + result = this.FileAttributeReadonlyCheckBox.Checked ? (result | FileAttributes.ReadOnly) : (result & ~FileAttributes.ReadOnly); + result = this.FileAttributeSystemCheckBox.Checked ? (result | FileAttributes.System) : (result & ~FileAttributes.System); + + return result.Value; + } } } diff --git a/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs b/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs index 5c103561ced..6ebe96a1878 100644 --- a/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FileProperties.ascx.cs @@ -61,7 +61,7 @@ protected string ActiveTab return string.IsNullOrEmpty(activeTab) ? string.Empty : System.Text.RegularExpressions.Regex.Replace(activeTab, "[^\\w]", string.Empty); } } - + protected override void OnInit(EventArgs e) { try @@ -114,12 +114,12 @@ protected override void OnInit(EventArgs e) contentControl.OnItemUpdated += this.OnItemUpdated; tabContentControlsInstances.Add(contentControl); } - + container.Controls.Add(control); this.TabsPanel.Controls.Add(container); } } - + this.tabContentControls = tabContentControlsInstances.ToList(); } } @@ -181,9 +181,9 @@ private void OnSaveClick(object sender, EventArgs e) this.SaveFileProperties(); this.Page.CloseClientDialog(true); } - catch (ThreadAbortException) - { - } + catch (ThreadAbortException) + { + } catch (DotNetNukeException dnnex) { UI.Skins.Skin.AddModuleMessage(this, dnnex.Message, ModuleMessage.ModuleMessageType.RedError); diff --git a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs index 488ffc601ea..1c07286c59e 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderMappings.ascx.cs @@ -25,14 +25,14 @@ namespace DotNetNuke.Modules.DigitalAssets public partial class FolderMappings : PortalModuleBase { private readonly INavigationManager _navigationManager; - - private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; - + + private readonly IFolderMappingController _folderMappingController = FolderMappingController.Instance; + public FolderMappings() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + public int FolderPortalID { get @@ -60,20 +60,20 @@ protected List FolderMappingsList obj = new List(); } } - + return (List)obj; } catch { this.Session["FolderMappingsList"] = null; } - + return new List(); } - + set { this.Session["FolderMappingsList"] = value; } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -130,11 +130,11 @@ protected void MappingsGrid_OnItemCommand(object source, GridCommandEventArgs e) protected void MappingsGrid_OnItemDataBound(object sender, GridItemEventArgs e) { - if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem) - { - return; - } - + if (e.Item.ItemType != GridItemType.Item && e.Item.ItemType != GridItemType.AlternatingItem) + { + return; + } + var folderMapping = e.Item.DataItem as FolderMappingInfo; if (folderMapping == null || !folderMapping.IsEditable) { @@ -142,17 +142,17 @@ protected void MappingsGrid_OnItemDataBound(object sender, GridItemEventArgs e) } var cmdEditMapping = e.Item.FindControl("EditMappingButton") as CommandButton; - if (cmdEditMapping != null) - { - cmdEditMapping.ToolTip = Localization.GetString("cmdEdit"); - } - + if (cmdEditMapping != null) + { + cmdEditMapping.ToolTip = Localization.GetString("cmdEdit"); + } + var cmdDeleteMapping = e.Item.FindControl("DeleteMappingButton") as CommandButton; - if (cmdDeleteMapping == null) - { - return; - } - + if (cmdDeleteMapping == null) + { + return; + } + cmdDeleteMapping.ToolTip = Localization.GetString("cmdDelete"); var deleteMessage = string.Format(Localization.GetString("DeleteConfirm", this.LocalResourceFile), folderMapping.MappingName); @@ -174,8 +174,8 @@ protected void OnNewMappingClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } - + } + private void UpdateFolderMappings(IList folderMappingsList) { for (var i = 3; i < folderMappingsList.Count; i++) @@ -183,6 +183,6 @@ private void UpdateFolderMappings(IList folderMappingsList) folderMappingsList[i].Priority = i + 1; this._folderMappingController.UpdateFolderMapping(folderMappingsList[i]); } - } + } } } diff --git a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs index ab39be08eb3..4ef5dbd1e72 100644 --- a/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/FolderProperties.ascx.cs @@ -32,8 +32,6 @@ public partial class FolderProperties : PortalModuleBase private bool isRootFolder; private Control folderFieldsControl; - protected IFolderInfo Folder { get; private set; } - protected bool CanManageFolder { get @@ -42,8 +40,6 @@ protected bool CanManageFolder } } - protected bool HasFullControl { get; private set; } - protected string DialogTitle { get @@ -60,6 +56,10 @@ protected bool IsHostPortal } } + protected IFolderInfo Folder { get; private set; } + + protected bool HasFullControl { get; private set; } + protected override void OnInit(EventArgs e) { try @@ -82,7 +82,7 @@ protected override void OnInit(EventArgs e) { throw new Exception("Invalid group folder"); } - + break; case DigitalAssestsMode.User: diff --git a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs index d6d31b4ea50..161e95313f9 100644 --- a/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/PreviewFieldsControl.ascx.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Modules.DigitalAssets public partial class PreviewFieldsControl : UserControl { public List Fields { get; set; } - + public void GenerateFieldsTable() { this.FieldsTable.Rows.Clear(); diff --git a/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs b/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs index c8bacdf54a8..6cd1c34dc3a 100644 --- a/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/PreviewPanelControl.ascx.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Modules.DigitalAssets using DotNetNuke.Modules.DigitalAssets.Components.Controllers.Models; public partial class PreviewPanelControl : System.Web.UI.UserControl - { + { protected string Title { get @@ -30,8 +30,8 @@ protected string PreviewImageUrl protected IDigitalAssetsController Controller { get; private set; } - protected ModuleInfo ModuleConfiguration { get; private set; } - + protected ModuleInfo ModuleConfiguration { get; private set; } + public void SetPreviewInfo(PreviewInfoViewModel previewInfoViewModel) { this.PreviewInfo = previewInfoViewModel; @@ -51,6 +51,6 @@ public void SetController(IDigitalAssetsController damController) public void SetModuleConfiguration(ModuleInfo moduleConfiguration) { this.ModuleConfiguration = moduleConfiguration; - } + } } } diff --git a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs index 110e72cc3f1..570478f908f 100644 --- a/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/Settings.ascx.cs @@ -81,11 +81,11 @@ public override void LoadSettings() public override void UpdateSettings() { this.Page.Validate(); - if (!this.Page.IsValid) - { - return; - } - + if (!this.Page.IsValid) + { + return; + } + try { SettingsRepository.SaveDefaultFolderTypeId(this.ModuleId, Convert.ToInt32(this.DefaultFolderTypeComboBox.SelectedValue)); diff --git a/DNN Platform/Modules/DigitalAssets/View.ascx.cs b/DNN Platform/Modules/DigitalAssets/View.ascx.cs index c86396010b0..d8f2eeea9a7 100644 --- a/DNN Platform/Modules/DigitalAssets/View.ascx.cs +++ b/DNN Platform/Modules/DigitalAssets/View.ascx.cs @@ -46,10 +46,10 @@ public partial class View : PortalModuleBase, IActionable private readonly IDigitalAssetsController controller; private readonly ExtensionPointManager epm = new ExtensionPointManager(); - private NameValueCollection damState; private readonly INavigationManager _navigationManager; - + private NameValueCollection damState; + public View() { this.controller = new Factory().DigitalAssetsController; @@ -78,7 +78,7 @@ public ModuleActionCollection ModuleActions return actions; } } - + protected int InitialTab { get @@ -95,30 +95,6 @@ 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 @@ -184,10 +160,34 @@ protected bool FilteredContent protected string PageSize { get; private set; } - protected string ActiveView { get; private set; } - + protected string ActiveView { get; private set; } + protected FolderViewModel RootFolderViewModel { get; private set; } + 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 override void OnLoad(EventArgs e) { try @@ -304,7 +304,36 @@ protected override void OnInit(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + + protected void GridOnItemCreated(object sender, GridItemEventArgs e) + { + if (!(e.Item is GridPagerItem)) + { + return; + } + + var items = new[] + { + new RadComboBoxItem { Text = "10", Value = "10" }, + new RadComboBoxItem { Text = "25", Value = "25" }, + new RadComboBoxItem { Text = "50", Value = "50" }, + new RadComboBoxItem { Text = "100", Value = "100" }, + new RadComboBoxItem + { + Text = Localization.GetString("All", this.LocalResourceFile), + Value = int.MaxValue.ToString(CultureInfo.InvariantCulture) + }, + }; + + var dropDown = (RadComboBox)e.Item.FindControl("PageSizeComboBox"); + dropDown.Items.Clear(); + foreach (var item in items) + { + item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID); + dropDown.Items.Add(item); + } + } + private static string GetNoControlCharsString(string text) { var result = new StringBuilder(); @@ -332,15 +361,15 @@ 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; @@ -591,12 +620,12 @@ 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, }); } } @@ -661,35 +690,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 void GridOnItemCreated(object sender, GridItemEventArgs e) - { - if (!(e.Item is GridPagerItem)) - { - return; - } - - var items = new[] - { - new RadComboBoxItem { Text = "10", Value = "10" }, - new RadComboBoxItem { Text = "25", Value = "25" }, - new RadComboBoxItem { Text = "50", Value = "50" }, - new RadComboBoxItem { Text = "100", Value = "100" }, - new RadComboBoxItem - { - Text = Localization.GetString("All", this.LocalResourceFile), - Value = int.MaxValue.ToString(CultureInfo.InvariantCulture) - }, - }; - - var dropDown = (RadComboBox)e.Item.FindControl("PageSizeComboBox"); - dropDown.Items.Clear(); - foreach (var item in items) - { - item.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID); - dropDown.Items.Add(item); - } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs index 96007bd709f..540b3d5aa2c 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/CompressionUtil.cs @@ -22,11 +22,11 @@ public static class CompressionUtil /// Full path of the archived file. public static void ZipFolder(string folderPath, string archivePath) { - if (File.Exists(archivePath)) - { - File.Delete(archivePath); - } - + if (File.Exists(archivePath)) + { + File.Delete(archivePath); + } + ZipFile.CreateFromDirectory(folderPath, archivePath, CompressionLevel.Fastest, false); } @@ -52,11 +52,11 @@ public static void UnZipArchive(string archivePath, string extractFolder, bool o public static void UnZipArchiveExcept(string archivePath, string extractFolder, bool overwrite = true, IEnumerable exceptionList = null, bool deleteFromSoure = false) { - if (!File.Exists(archivePath)) - { - return; - } - + if (!File.Exists(archivePath)) + { + return; + } + using (var archive = OpenCreate(archivePath)) { foreach ( @@ -68,20 +68,20 @@ var entry in !entry.FullName.EndsWith("\\") && !entry.FullName.EndsWith("/") && entry.Length > 0)) { var path = Path.GetDirectoryName(Path.Combine(extractFolder, entry.FullName)); - if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) - { - Directory.CreateDirectory(path); - } - - if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) - { - entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); - } - - if (deleteFromSoure) - { - entry.Delete(); - } + if (!string.IsNullOrEmpty(path) && !Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + + if (!File.Exists(Path.Combine(extractFolder, entry.FullName)) || overwrite) + { + entry.ExtractToFile(Path.Combine(extractFolder, entry.FullName), overwrite); + } + + if (deleteFromSoure) + { + entry.Delete(); + } } } } @@ -97,29 +97,29 @@ var entry in public static void UnZipFileFromArchive(string fileName, string archivePath, string extractFolder, bool overwrite = true, bool deleteFromSoure = false) { - if (!File.Exists(archivePath)) - { - return; - } - + if (!File.Exists(archivePath)) + { + return; + } + using (var archive = OpenCreate(archivePath)) { var fileUnzipFullName = Path.Combine(extractFolder, fileName); - if (File.Exists(fileUnzipFullName) && !overwrite) - { - return; - } - + if (File.Exists(fileUnzipFullName) && !overwrite) + { + return; + } + var fileEntry = archive.GetEntry(fileName); - if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) - { - fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); - } - - if (deleteFromSoure) - { - fileEntry?.Delete(); - } + if (!File.Exists(Path.Combine(extractFolder, fileEntry.FullName)) || overwrite) + { + fileEntry?.ExtractToFile(Path.Combine(extractFolder, fileName), overwrite); + } + + if (deleteFromSoure) + { + fileEntry?.Delete(); + } } } @@ -136,11 +136,11 @@ public static void AddFilesToArchive(ZipArchive archive, IEnumerable fil string folder = null) { var enumerable = files as IList ?? files.ToList(); - if (!enumerable.Any()) - { - return; - } - + if (!enumerable.Any()) + { + return; + } + foreach (var file in enumerable.Where(File.Exists)) { AddFileToArchive(archive, file, folderOffset, folder); @@ -155,7 +155,7 @@ public static void AddFilesToArchive(ZipArchive archive, IEnumerable fil /// Starting index(Index in file url) of the root folder in archive based on what the folder structure starts in archive. /// e.g. if file url is c:\\dnn\files\archived\foldername\1\file.jpg and we want to add all files in foldername folder /// then the folder offset would be starting index of foldername. - /// Additional root folder to be added into archive. + /// Additional root folder to be added into archive. /// public static bool AddFileToArchive(string file, string archivePath, int folderOffset, string folder = null) { @@ -166,15 +166,15 @@ public static bool AddFileToArchive(string file, string archivePath, int folderO return AddFileToArchive(archive, file, folderOffset, folder); } } - + return false; - } - + } + public static bool AddFileToArchive(ZipArchive archive, string file, int folderOffset, string folder = null) { var entryName = file.Substring(folderOffset); // Makes the name in zip based on the folder ZipArchiveEntry existingEntry; - + // Deletes if the entry already exists in archive. if ((existingEntry = archive.GetEntry(entryName)) != null) { @@ -184,12 +184,12 @@ public static bool AddFileToArchive(ZipArchive archive, string file, int folderO var fileInfo = new FileInfo(file); if (fileInfo.Length < 1610612736) { - archive.CreateEntryFromFile( + archive.CreateEntryFromFile( file, string.IsNullOrEmpty(folder) ? entryName : Path.Combine(folder, entryName), CompressionLevel.Fastest); return true; } - + return false; } @@ -203,6 +203,6 @@ public static ZipArchive OpenCreate(string archiveFileName) return File.Exists(archiveFileName) ? ZipFile.Open(archiveFileName, ZipArchiveMode.Update, Encoding.UTF8) : new ZipArchive(new FileStream(archiveFileName, FileMode.Create), ZipArchiveMode.Update); - } + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs index bd120ad62d8..a218b8f208e 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Constants.cs @@ -18,6 +18,14 @@ public class Constants // 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"; + public const string Category_Templates = "TEMPLATES"; + public const string Category_Assets = "ASSETS"; + public const string Category_Packages = "PACKAGES"; + public const string Category_Themes = "THEMES"; + public const string Category_Workflows = "WORKFLOW"; internal const string ExportFolder = @"\App_Data\ExportImport\"; internal const string ExportManifestName = "export.json"; // export manifest file name @@ -42,21 +50,13 @@ public class Constants 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 - public const string Category_Roles = "ROLES"; - public const string Category_ProfileProps = "PROFILE_PROPERTIES"; - public const string Category_Content = "CONTENT"; - public const string Category_Templates = "TEMPLATES"; - public const string Category_Assets = "ASSETS"; - public const string Category_Packages = "PACKAGES"; - public const string Category_Themes = "THEMES"; - public const string Category_Workflows = "WORKFLOW"; - // these are added internally by the engine internal const string Category_Portal = "PORTAL"; internal const string Category_Pages = "PAGES"; internal const string Category_UsersData = "USERS_DATA"; + + 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 } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs index 78e62d437c4..7aecb653fc0 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Common/Util.cs @@ -28,12 +28,12 @@ public static class Util { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Util)); private static int _noRole = Convert.ToInt32(Globals.glbRoleNothing); - + // some string extension helpers public static bool IsNullOrEmpty(this string s) => string.IsNullOrEmpty(s); - + public static bool IsNullOrWhiteSpace(this string s) => string.IsNullOrWhiteSpace(s); - + public static bool HasValue(this string s) => !string.IsNullOrEmpty(s); public static IEnumerable GetPortableImplementors() @@ -52,7 +52,7 @@ public static IEnumerable GetPortableImplementors() } catch (Exception e) { - Logger.ErrorFormat( + Logger.ErrorFormat( "Unable to create {0} while calling BasePortableService implementors. {1}", type.FullName, e.Message); portable2Type = null; @@ -71,21 +71,21 @@ public static string FormatSize(long bytes, byte decimals = 1) const long mb = kb * kb; const long gb = mb * kb; - if (bytes < kb) - { - return bytes + " B"; - } - - if (bytes < mb) - { - return (1.0 * bytes / kb).ToString("F" + decimals) + " KB"; - } - - if (bytes < gb) - { - return (1.0 * bytes / mb).ToString("F" + decimals) + " MB"; - } - + if (bytes < kb) + { + return bytes + " B"; + } + + if (bytes < mb) + { + return (1.0 * bytes / kb).ToString("F" + decimals) + " KB"; + } + + if (bytes < gb) + { + return (1.0 * bytes / mb).ToString("F" + decimals) + " MB"; + } + return (1.0 * bytes / gb).ToString("F" + decimals) + " GB"; } @@ -96,48 +96,48 @@ public static string GetExpImpJobCacheKey(ExportImportJob job) public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId, string exportUsername) { - if (!exportedUserId.HasValue || exportedUserId <= 0) - { - return -1; - } - - if (exportedUserId == 1) - { - return 1; // default HOST user - } - - if (string.IsNullOrEmpty(exportUsername)) - { - return -1; - } - + if (!exportedUserId.HasValue || exportedUserId <= 0) + { + return -1; + } + + if (exportedUserId == 1) + { + return 1; // default HOST user + } + + if (string.IsNullOrEmpty(exportUsername)) + { + return -1; + } + var user = UserController.GetUserByName(importJob.PortalId, exportUsername); - if (user == null) - { - return -1; - } - + if (user == null) + { + return -1; + } + return user.UserID < 0 ? importJob.CreatedByUserId : user.UserID; } public static int? GetRoleIdByName(int portalId, int exportRoleId, string exportRolename) { - if (string.IsNullOrEmpty(exportRolename)) - { - return null; - } - + if (string.IsNullOrEmpty(exportRolename)) + { + return null; + } + var roleId = DataProvider.Instance().GetRoleIdByName(exportRoleId >= 0 ? portalId : -1, exportRolename); return roleId == _noRole ? null : (int?)roleId; } public static int? GeModuleDefIdByFriendltName(string friendlyName) { - if (string.IsNullOrEmpty(friendlyName)) - { - return null; - } - + if (string.IsNullOrEmpty(friendlyName)) + { + return null; + } + var moduleDefInfo = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(friendlyName); return moduleDefInfo?.ModuleDefID; } @@ -146,11 +146,11 @@ public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId { if (string.IsNullOrEmpty(permissionCode) || string.IsNullOrEmpty(permissionKey) || - string.IsNullOrEmpty(permissionName)) - { - return null; - } - + string.IsNullOrEmpty(permissionName)) + { + return null; + } + var permission = EntitiesController.Instance.GetPermissionInfo(permissionCode, permissionKey, permissionName); return permission?.PermissionID; } @@ -158,11 +158,11 @@ public static int GetUserIdByName(ExportImportJob importJob, int? exportedUserId public static int? GetProfilePropertyId(int portalId, int? exportedProfilePropertyId, string exportProfilePropertyname) { - if (!exportedProfilePropertyId.HasValue || exportedProfilePropertyId <= 0) - { - return -1; - } - + if (!exportedProfilePropertyId.HasValue || exportedProfilePropertyId <= 0) + { + return -1; + } + var property = ProfileController.GetPropertyDefinitionByName(portalId, exportProfilePropertyname); return property?.PropertyDefinitionId; } @@ -183,7 +183,7 @@ public static void ReadJson(string filePath, ref T item) if (File.Exists(filePath)) { var content = File.ReadAllText(filePath); - + // TODO: This might throw error if file is corrupt. Should we handle error here? item = JsonConvert.DeserializeObject(content); } @@ -212,17 +212,17 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) dateTime.Millisecond, DateTimeKind.Utc); return userInfo.LocalTime(dateTime); } - + return dateTime; } public static DateTime? ToLocalDateTime(DateTime? dateTime, UserInfo userInfo) { - if (dateTime != null && dateTime.Value.Kind != DateTimeKind.Local) - { - return userInfo.LocalTime(dateTime.Value); - } - + if (dateTime != null && dateTime.Value.Kind != DateTimeKind.Local) + { + return userInfo.LocalTime(dateTime.Value); + } + return dateTime; } @@ -233,16 +233,16 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) /// public static DateTime? ConvertToDbLocalTime(DateTime? dateTime) { - if (dateTime == null) - { - return null; - } - - if (dateTime.Value.Kind != DateTimeKind.Utc) - { - return dateTime; - } - + if (dateTime == null) + { + return null; + } + + if (dateTime.Value.Kind != DateTimeKind.Utc) + { + return dateTime; + } + var differenceInUtcTimes = TimeZone.CurrentTimeZone.GetUtcOffset(DateUtils.GetDatabaseUtcTime()).TotalMilliseconds; var d = dateTime.Value.ToLocalTime().AddMilliseconds(differenceInUtcTimes); @@ -256,16 +256,16 @@ public static DateTime ToLocalDateTime(DateTime dateTime, UserInfo userInfo) /// public static DateTime? ConvertToDbUtcTime(DateTime? dateTime) { - if (dateTime == null) - { - return null; - } - - if (dateTime.Value.Kind == DateTimeKind.Utc) - { - return dateTime; - } - + if (dateTime == null) + { + return null; + } + + if (dateTime.Value.Kind == DateTimeKind.Utc) + { + return dateTime; + } + var differenceInUtcTimes = TimeZone.CurrentTimeZone.GetUtcOffset(DateUtils.GetDatabaseUtcTime()).TotalMilliseconds; var d = dateTime.Value.ToUniversalTime().AddMilliseconds(differenceInUtcTimes); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs index ac48ae0c359..85d9e3c2dae 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BaseController.cs @@ -27,7 +27,7 @@ namespace Dnn.ExportImport.Components.Controllers public class BaseController { public static readonly string ExportFolder; - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(BaseController)); static BaseController() @@ -43,11 +43,11 @@ public bool CancelJob(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (job == null || (job.PortalId != portalId && portalId != -1)) - { - return false; - } - + if (job == null || (job.PortalId != portalId && portalId != -1)) + { + return false; + } + controller.SetJobCancelled(job); CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); return true; @@ -57,61 +57,39 @@ public bool RemoveJob(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (job == null || (job.PortalId != portalId && portalId != -1)) - { - return false; - } - + if (job == null || (job.PortalId != portalId && portalId != -1)) + { + return false; + } + CachingProvider.Instance().Remove(Util.GetExpImpJobCacheKey(job)); - + // if the job is running; then it will create few exceptions in the log file controller.RemoveJob(job); DeleteJobData(job); 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. - /// + ///
    /// public AllJobsResult GetAllJobs(int portalId, int currentPortalId, int? pageSize, int? pageIndex, int? jobType, string keywords) { - if (pageIndex < 0) - { - pageIndex = 0; - } - - if (pageSize < 1) - { - pageSize = 1; - } - else if (pageSize > 100) - { - pageSize = 100; - } - + if (pageIndex < 0) + { + pageIndex = 0; + } + + if (pageSize < 1) + { + pageSize = 1; + } + else if (pageSize > 100) + { + pageSize = 100; + } + var count = EntitiesController.Instance.GetAllJobsCount(portalId, jobType, keywords); var jobs = count <= 0 ? null @@ -133,11 +111,11 @@ public JobItem GetJobDetails(int portalId, int jobId) { var controller = EntitiesController.Instance; var job = controller.GetJobById(jobId); - if (portalId != -1 && job?.PortalId != portalId) - { - return null; - } - + if (portalId != -1 && job?.PortalId != portalId) + { + return null; + } + var jobItem = ToJobItem(job); jobItem.Summary = BuildJobSummary(jobId); return jobItem; @@ -208,11 +186,11 @@ protected static ImportExportSummary BuildJobSummary(int jobId) }; var checkpoints = EntitiesController.Instance.GetJobChekpoints(jobId); - if (!checkpoints.Any()) - { - return importExportSummary; - } - + if (!checkpoints.Any()) + { + return importExportSummary; + } + var implementors = Util.GetPortableImplementors(); summaryItems.AddRange(checkpoints.Select(checkpoint => new SummaryItem @@ -242,6 +220,28 @@ protected static ImportPackageInfo GetPackageInfo(string manifestPath) return packageInfo; } + 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); + } + private static JobItem ToJobItem(ExportImportJob job) { var user = UserController.Instance.GetUserById(job.PortalId, job.CreatedByUserId); @@ -266,11 +266,11 @@ private static JobItem ToJobItem(ExportImportJob job) private static void DeleteJobData(ExportImportJob job) { - if (job.JobType != JobType.Export) - { - return; - } - + if (job.JobType != JobType.Export) + { + return; + } + var jobFolder = Path.Combine(ExportFolder, job.Directory); try { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs index de8004efa54..5ef42b0c7b4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/BusinessController.cs @@ -28,7 +28,7 @@ public string UpgradeModule(string version) // AddNewLogTypes(); // moved to SQL migration script break; } - + return "Success"; } catch (Exception) diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs index b3e2846fbe5..737c3dee021 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/EntitiesController.cs @@ -32,16 +32,11 @@ public ExportImportJob GetFirstActiveJob() public ExportImportJob GetJobById(int jobId) { var job = CBO.Instance.FillObject(this._dataProvider.GetJobById(jobId)); - + // System.Diagnostics.Trace.WriteLine($"xxxxxxxxx job id={job?.JobId} IsCancelled={job?.IsCancelled} xxxxxxxxx"); return job; } - protected override Func GetFactory() - { - return () => new EntitiesController(); - } - public IList GetJobSummaryLog(int jobId) { return CBO.Instance.FillCollection(this._dataProvider.GetJobSummaryLog(jobId)); @@ -194,6 +189,11 @@ public void RunSchedule() } } + protected override Func GetFactory() + { + return () => new EntitiesController(); + } + private string GetSchedulerTypeFullName() { var type = typeof(ExportImportScheduler); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs index 0273c3b14af..bb2e0ba89b4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ExportController.cs @@ -29,18 +29,18 @@ public int QueueOperation(int userId, ExportDto exportDto) { exportDto.FromDateUtc = this.GetLastJobTime(exportDto.PortalId, JobType.Export); } - + var dataObject = JsonConvert.SerializeObject(exportDto); exportDto.IsDirty = false; // This should be set to false for new job. var jobId = DataProvider.Instance().AddNewJob(exportDto.PortalId, userId, JobType.Export, exportDto.ExportName, exportDto.ExportDescription, directory, dataObject); - + // Run the scheduler if required. if (exportDto.RunNow) { EntitiesController.Instance.RunSchedule(); } - + this.AddEventLog(exportDto.PortalId, userId, jobId, Constants.LogTypeSiteExport); return jobId; } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs index ea55a61ec7c..8e77bc86b73 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/ImportController.cs @@ -30,13 +30,13 @@ public int QueueOperation(int userId, ImportDto importDto) var dataObject = JsonConvert.SerializeObject(importDto); var jobId = DataProvider.Instance().AddNewJob( importDto.PortalId, userId, JobType.Import, null, null, importDto.PackageId, dataObject); - + // Run the scheduler if required. if (importDto.RunNow) { EntitiesController.Instance.RunSchedule(); } - + this.AddEventLog(importDto.PortalId, userId, jobId, Constants.LogTypeSiteImport); return jobId; } @@ -78,21 +78,21 @@ public bool VerifyImportPackage(string packageId, ImportExportSummary summary, o bool isValid; errorMessage = string.Empty; var importFolder = Path.Combine(ExportFolder, packageId); - if (!IsValidImportFolder(importFolder)) - { - return false; - } - + if (!IsValidImportFolder(importFolder)) + { + return false; + } + var dbPath = UnPackDatabase(importFolder); try { using (var ctx = new ExportImportRepository(dbPath)) { - if (summary != null) - { - BuildJobSummary(packageId, ctx, summary); - } - + if (summary != null) + { + BuildJobSummary(packageId, ctx, summary); + } + isValid = true; } } @@ -101,18 +101,18 @@ public bool VerifyImportPackage(string packageId, ImportExportSummary summary, o isValid = false; errorMessage = "Package is not valid. Technical Details:" + ex.Message; } - + return isValid; } private static string GetPackageDbPath(string packageId) { var importFolder = Path.Combine(ExportFolder, packageId); - if (!IsValidImportFolder(importFolder)) - { - return null; - } - + if (!IsValidImportFolder(importFolder)) + { + return null; + } + var dbPath = UnPackDatabase(importFolder); return dbPath; } @@ -120,11 +120,11 @@ private static string GetPackageDbPath(string packageId) private static string UnPackDatabase(string folderPath) { var dbName = Path.Combine(folderPath, Constants.ExportDbName); - if (File.Exists(dbName)) - { - return dbName; - } - + if (File.Exists(dbName)) + { + return dbName; + } + var zipDbName = Path.Combine(folderPath, Constants.ExportZipDbName); CompressionUtil.UnZipFileFromArchive(Constants.ExportDbName, zipDbName, folderPath, false); return dbName; @@ -159,7 +159,7 @@ private Func GetImportPackageOrderByFunc(string order sortFunc = packageInfo => packageInfo.ExporTime; break; } - + return sortFunc; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs index c0448f04057..8c6bdf1f465 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Controllers/SettingsController.cs @@ -22,7 +22,7 @@ public class SettingsController : ServiceLocator GetAllSettings() { - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( new CacheItemArgs(CacheKey, CacheDuration, CacheItemPriority.Normal), c => CBO.FillQueryable(DataProvider.Instance().GetExportImportSettings()).ToList()); } @@ -31,16 +31,16 @@ 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) { DataProvider.Instance().AddExportImportSetting(exportImportSetting); DataCache.RemoveCache(CacheKey); } + + protected override Func GetFactory() + { + return () => new SettingsController(); + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs index 861167d2608..e839387669b 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportDto.cs @@ -27,8 +27,14 @@ public enum TriCheckedState [JsonObject] public class ExportDto { + [JsonIgnore] + public DateTime? FromDate => this.FromDateUtc; + + [JsonIgnore] + public DateTime ToDate => this.ToDateUtc; + public int Id { get; set; } - + /// /// Gets or sets specifies the version of the exportes schema. /// @@ -143,12 +149,6 @@ public class ExportDto [JsonProperty("ToDate")] public DateTime ToDateUtc { get; set; } - [JsonIgnore] - public DateTime? FromDate => this.FromDateUtc; - - [JsonIgnore] - public DateTime ToDate => this.ToDateUtc; - /// /// Gets or sets the pages to be exported. These are the ID's (plus other information) /// of all checked items but not their children when a parent is checked. @@ -174,9 +174,9 @@ public class ExportDto public class PageToExport { public int TabId { get; set; } - + public int ParentTabId { get; set; } - + public TriCheckedState CheckedState { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs index 7c96bce3ac2..7deca1b4820 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ExportFileInfo.cs @@ -18,7 +18,7 @@ public class ExportFileInfo : IDateTimeConverter /// Gets or sets path for exported files. /// public string ExportPath { get; set; } - + /// /// Gets or sets formatted size of export file. /// diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs index e053fa8ab66..bf3fb8faf97 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportExportSummary.cs @@ -22,22 +22,32 @@ public ImportExportSummary() { this.SummaryItems = new SummaryList(); } - + + /// + /// Gets formatted Date from which data was taken to perform export. + /// + public string FromDateString => Util.GetDateTimeString(this.FromDate); + + /// + /// Gets formatted Date till which data was taken to perform export. + /// + public string ToDateString => Util.GetDateTimeString(this.ToDate); + /// /// Gets or sets a value indicating whether does this import/export includes the properties definitions or not. /// public bool IncludeProfileProperties { get; set; } - + /// /// Gets or sets a value indicating whether does this import/export includes the permission or not. /// public bool IncludePermissions { get; set; } - + /// /// Gets or sets a value indicating whether does this import/export includes the modules or not. /// public bool IncludeExtensions { get; set; } - + /// /// Gets or sets a value indicating whether does this import/export includes the deleted items or not. /// @@ -58,26 +68,16 @@ public ImportExportSummary() ///
    public DateTime? FromDate { get; set; } - /// - /// Gets formatted Date from which data was taken to perform export. - /// - public string FromDateString => Util.GetDateTimeString(this.FromDate); - /// /// Gets or sets date till which data was taken to perform export. /// public DateTime ToDate { get; set; } - /// - /// Gets formatted Date till which data was taken to perform export. - /// - public string ToDateString => Util.GetDateTimeString(this.ToDate); - /// /// Gets or sets summary of each item export. /// public IEnumerable SummaryItems { get; set; } - + /// /// Gets or sets exported file information. /// @@ -85,31 +85,31 @@ public ImportExportSummary() public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) - { - return; - } - + if (userInfo == null) + { + return; + } + this.ToDate = Util.ToLocalDateTime(this.ToDate, userInfo); - if (this.FromDate != null) - { - this.FromDate = Util.ToLocalDateTime(this.FromDate.Value, userInfo); - } - + if (this.FromDate != null) + { + this.FromDate = Util.ToLocalDateTime(this.FromDate.Value, userInfo); + } + this.ExportFileInfo?.ConvertToLocal(userInfo); - if (this.SummaryItems == null) - { - return; - } - + if (this.SummaryItems == null) + { + return; + } + var tempSummaryItems = new SummaryList(); foreach (var summaryItem in this.SummaryItems) { summaryItem.ConvertToLocal(userInfo); tempSummaryItems.Add(summaryItem); } - + this.SummaryItems = tempSummaryItems; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs index 2a5fc049718..e04a3db95cd 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/ImportPackageInfo.cs @@ -15,29 +15,34 @@ namespace Dnn.ExportImport.Components.Dto public class ImportPackageInfo : IDateTimeConverter { /// - /// Gets or sets package Id. Used to identify the package and path. + /// Gets package file name. It is just fake name for UI representation. /// - public string PackageId { get; set; } + public string FileName => this.PackageId; /// - /// Gets or sets name of the package. + /// Gets formatted DateTime when the package was exported. /// - public string Name { get; set; } + public string ExporTimeString => Util.GetDateTimeString(this.ExporTime); /// - /// Gets package file name. It is just fake name for UI representation. + /// Gets path to the thumbnail image for the package. /// - public string FileName => this.PackageId; + public string Thumb => this.PackageId + ".jpg"; /// - /// Gets or sets dateTime when the package was exported. + /// Gets or sets package Id. Used to identify the package and path. /// - public DateTime ExporTime { get; set; } + public string PackageId { get; set; } /// - /// Gets formatted DateTime when the package was exported. + /// Gets or sets name of the package. /// - public string ExporTimeString => Util.GetDateTimeString(this.ExporTime); + public string Name { get; set; } + + /// + /// Gets or sets dateTime when the package was exported. + /// + public DateTime ExporTime { get; set; } /// /// Gets or sets the portal from which the exported package was created. @@ -49,11 +54,6 @@ public class ImportPackageInfo : IDateTimeConverter /// public string Description { get; set; } - /// - /// Gets path to the thumbnail image for the package. - /// - public string Thumb => this.PackageId + ".jpg"; - /// /// Gets or sets complete summary of import package. /// @@ -61,11 +61,11 @@ public class ImportPackageInfo : IDateTimeConverter public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) - { - return; - } - + if (userInfo == null) + { + return; + } + this.ExporTime = Util.ToLocalDateTime(this.ExporTime, userInfo); this.Summary?.ConvertToLocal(userInfo); } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs index fee0c919928..5f541bde64d 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/AllJobsResult.cs @@ -15,21 +15,20 @@ namespace Dnn.ExportImport.Components.Dto.Jobs [JsonObject] public class AllJobsResult : IDateTimeConverter { + public string TotalJobsString => Util.FormatNumber(this.TotalJobs); + + public string LastExportTimeString => Util.GetDateTimeString(this.LastExportTime); + + public string LastImportTimeString => Util.GetDateTimeString(this.LastImportTime); public int PortalId { get; set; } - + public string PortalName { get; set; } - + public int TotalJobs { get; set; } - - public string TotalJobsString => Util.FormatNumber(this.TotalJobs); public DateTime? LastExportTime { get; set; } - - public DateTime? LastImportTime { get; set; } - public string LastExportTimeString => Util.GetDateTimeString(this.LastExportTime); - - public string LastImportTimeString => Util.GetDateTimeString(this.LastImportTime); + public DateTime? LastImportTime { get; set; } public IEnumerable Jobs { get; set; } @@ -38,16 +37,16 @@ public void ConvertToLocal(UserInfo userInfo) this.LastExportTime = Util.ToLocalDateTime(this.LastExportTime, userInfo); this.LastImportTime = Util.ToLocalDateTime(this.LastImportTime, userInfo); - if (userInfo == null) - { - return; - } - - if (this.Jobs == null) - { - return; - } - + if (userInfo == null) + { + return; + } + + if (this.Jobs == null) + { + return; + } + var tempJobs = new List(); foreach (var job in this.Jobs) @@ -55,7 +54,7 @@ public void ConvertToLocal(UserInfo userInfo) job.ConvertToLocal(userInfo); tempJobs.Add(job); } - + this.Jobs = tempJobs; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs index a5a51786174..51739ece1ac 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/JobItem.cs @@ -14,50 +14,49 @@ namespace Dnn.ExportImport.Components.Dto.Jobs [JsonObject] public class JobItem : IDateTimeConverter { + public string CreatedOnString => Util.GetDateTimeString(this.CreatedOn); + + public string CompletedOnString => Util.GetDateTimeString(this.CompletedOn); public int JobId { get; set; } - + public int PortalId { get; set; } - + public string User { get; set; } - + public string JobType { get; set; } - + public int Status { get; set; } - + public bool Cancelled { get; set; } - + public string JobStatus { get; set; } - + public string Name { get; set; } - + public string Description { get; set; } - + public DateTime CreatedOn { get; set; } - - public string CreatedOnString => Util.GetDateTimeString(this.CreatedOn); - + public DateTime? CompletedOn { get; set; } - - public string CompletedOnString => Util.GetDateTimeString(this.CompletedOn); public string ExportFile { get; set; } - + // public IEnumerable Summary { get; set; } public ImportExportSummary Summary { get; set; } public void ConvertToLocal(UserInfo userInfo) { - if (userInfo == null) - { - return; - } - + if (userInfo == null) + { + return; + } + this.Summary?.ConvertToLocal(userInfo); this.CreatedOn = Util.ToLocalDateTime(this.CreatedOn, userInfo); - if (this.CompletedOn != null) - { - this.CompletedOn = Util.ToLocalDateTime(this.CompletedOn.Value, userInfo); - } + if (this.CompletedOn != null) + { + this.CompletedOn = Util.ToLocalDateTime(this.CompletedOn.Value, userInfo); + } } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs index 571144071c8..232df87a0ce 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/Jobs/LogItem.cs @@ -13,11 +13,11 @@ namespace Dnn.ExportImport.Components.Dto.Jobs public class LogItem { public DateTime CreatedOnDate { get; set; } - + public string Name { get; set; } - + public string Value { get; set; } - + public ReportLevel ReportLevel { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs b/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs index 936b1a221eb..af01ed968c4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Dto/SummaryItem.cs @@ -16,6 +16,16 @@ namespace Dnn.ExportImport.Components.Dto [JsonObject] public class SummaryItem : IDateTimeConverter { + /// + /// Gets formatted total items. + /// + public string TotalItemsString => Util.FormatNumber(this.TotalItems); + + /// + /// Gets formatted processed items. + /// + public string ProcessedItemsString => Util.FormatNumber(this.ProcessedItems); + /// /// Gets or sets category of the import/export. Also identifier for localization. /// @@ -26,11 +36,6 @@ public class SummaryItem : IDateTimeConverter ///
    public int TotalItems { get; set; } - /// - /// Gets formatted total items. - /// - public string TotalItemsString => Util.FormatNumber(this.TotalItems); - /// /// Gets or sets items processed. /// @@ -41,11 +46,6 @@ public class SummaryItem : IDateTimeConverter ///
    public bool Completed { get; set; } - /// - /// Gets formatted processed items. - /// - public string ProcessedItemsString => Util.FormatNumber(this.ProcessedItems); - /// /// Gets or sets progress in percentage. /// diff --git a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs index a1f348427f2..6d4c27706ae 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Engines/ExportImportEngine.cs @@ -39,7 +39,7 @@ namespace Dnn.ExportImport.Components.Engines public class ExportImportEngine { private const StringComparison IgnoreCaseComp = StringComparison.InvariantCultureIgnoreCase; - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportEngine)); private static readonly string ExportFolder; @@ -117,7 +117,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul var dbName = Path.Combine(ExportFolder, exportJob.Directory, Constants.ExportDbName); var finfo = new FileInfo(dbName); dbName = finfo.FullName; - + var checkpoints = EntitiesController.Instance.GetJobChekpoints(exportJob.JobId); // Delete so we start a fresh export database; only if there is no previous checkpoint exists @@ -127,7 +127,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul { finfo.Directory.Delete(true); } - + // Clear all the files in finfo.Directory. Create if doesn't exists. finfo.Directory?.Create(); result.AddSummary("Starting Exporting Repository", finfo.Name); @@ -164,7 +164,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul exportJob.JobStatus = JobStatus.Failed; return; } - + scheduleHistoryItem.AddLogNote($"
    SITE EXPORT Preparing Check Points. JOB #{exportJob.JobId}: {exportJob.Name}"); this.PrepareCheckPoints(exportJob.JobId, parentServices, implementors, includedItems, checkpoints); @@ -218,11 +218,11 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul // persist the record in db this.CheckpointCallback(service); } - else if (service.CheckPoint.StartDate == Null.NullDate) - { - service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); - } - + else if (service.CheckPoint.StartDate == Null.NullDate) + { + service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); + } + try { service.ExportData(exportJob, exportDto); @@ -231,7 +231,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul { this.AddLogsToDatabase(exportJob.JobId, result.CompleteLog); } - + scheduleHistoryItem.AddLogNote("
    Exported: " + service.Category); } } @@ -248,7 +248,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul scheduleHistoryItem.AddLogNote( "
    Orphaned services: " + string.Join(",", parentServices.Select(x => x.Category))); } - } + } while (parentServices.Count > 0 && !this.TimeIsUp); RemoveTokenFromCache(exportJob); @@ -256,7 +256,7 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul if (this.TimeIsUp) { - result.AddSummary( + result.AddSummary( $"Job time slot ({this._timeoutSeconds} sec) expired", "Job will resume in the next scheduler iteration"); } @@ -268,9 +268,9 @@ public void Export(ExportImportJob exportJob, ExportImportResult result, Schedul { BaseController.BuildJobSummary(exportJob.Directory, ctx, summary); } - + DoPacking(exportJob, dbName); - + // Complete the job. exportJob.JobStatus = JobStatus.Successful; SetLastJobStartTime(scheduleHistoryItem.ScheduleID, exportJob.CreatedOnDate); @@ -399,11 +399,11 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul Progress = 0, StartDate = DateUtils.GetDatabaseUtcTime(), }; - if (service.CheckPoint.StartDate == Null.NullDate) - { - service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); - } - + if (service.CheckPoint.StartDate == Null.NullDate) + { + service.CheckPoint.StartDate = DateUtils.GetDatabaseUtcTime(); + } + this.CheckpointCallback(service); try @@ -414,7 +414,7 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul { this.AddLogsToDatabase(importJob.JobId, result.CompleteLog); } - + scheduleHistoryItem.AddLogNote("
    Imported: " + service.Category); } } @@ -431,13 +431,13 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul scheduleHistoryItem.AddLogNote( "
    Orphaned services: " + string.Join(",", parentServices.Select(x => x.Category))); } - } + } while (parentServices.Count > 0 && !this.TimeIsUp); RemoveTokenFromCache(importJob); if (this.TimeIsUp) { - result.AddSummary( + result.AddSummary( $"Job time slot ({this._timeoutSeconds} sec) expired", "Job will resume in the next scheduler iteration"); } @@ -454,11 +454,11 @@ public void Import(ExportImportJob importJob, ExportImportResult result, Schedul public void AddLogsToDatabase(int jobId, ICollection completeLog) { - if (completeLog == null || completeLog.Count == 0) - { - return; - } - + if (completeLog == null || completeLog.Count == 0) + { + return; + } + using (var table = new DataTable("ExportImportJobLogs")) { // must create the columns from scratch with each iteration @@ -486,7 +486,7 @@ public void AddLogsToDatabase(int jobId, ICollection completeLog) table.Rows.Clear(); } } - + completeLog.Clear(); } @@ -513,74 +513,7 @@ 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) - { - // there must be one parent implementor at least for this to work - var nextLevelServices = new List(); - var firstIteration = true; - if (checkpoints.Any()) - { - return; - } - - do - { - foreach (var service in parentServices.OrderBy(x => x.Priority)) - { - if (implementors.Count > 0) - { - // collect children for next iteration - var children = - implementors.Where(imp => service.Category.Equals(imp.ParentCategory, IgnoreCaseComp)); - nextLevelServices.AddRange(children); - implementors = implementors.Except(nextLevelServices).ToList(); - } - - if ((firstIteration && includedItems.Any(x => x.Equals(service.Category, IgnoreCaseComp))) || - (!firstIteration && includedItems.Any(x => x.Equals(service.ParentCategory, IgnoreCaseComp)))) - { - var serviceAssembly = service.GetType().Assembly.GetName().Name; - - service.CheckPoint = checkpoints.FirstOrDefault(cp => cp.Category == service.Category && cp.AssemblyName == serviceAssembly); - - if (service.CheckPoint != null) - { - continue; - } - - service.CheckPoint = new ExportImportChekpoint - { - JobId = jobId, - AssemblyName = serviceAssembly, - Category = service.Category, - Progress = 0, - }; - - // persist the record in db - this.CheckpointCallback(service); - } - } - - firstIteration = false; - parentServices = new List(nextLevelServices); - nextLevelServices.Clear(); - } - while (parentServices.Count > 0); - } - - /// - /// Callback function to provide a checkpoint mechanism for an implementation. - /// - /// The implementation. - /// Treu to stop further processing; false otherwise. - private bool CheckpointCallback(BasePortableService service) - { - EntitiesController.Instance.UpdateJobChekpoint(service.CheckPoint); - return this.TimeIsUp; - } - - private static HashSet GetAllCategoriesToInclude( + private static HashSet GetAllCategoriesToInclude( ExportDto exportDto, List implementors) { @@ -605,47 +538,47 @@ var name in includedItems.Add(Constants.Category_Workflows); } - if (exportDto.IncludeContent) - { - includedItems.Add(Constants.Category_Content); - } - - if (exportDto.IncludeFiles) - { - includedItems.Add(Constants.Category_Assets); - } - - if (exportDto.IncludeUsers) - { - includedItems.Add(Constants.Category_Users); - } - - if (exportDto.IncludeRoles) - { - includedItems.Add(Constants.Category_Roles); - } - - if (exportDto.IncludeVocabularies) - { - includedItems.Add(Constants.Category_Vocabularies); - } - + if (exportDto.IncludeContent) + { + includedItems.Add(Constants.Category_Content); + } + + if (exportDto.IncludeFiles) + { + includedItems.Add(Constants.Category_Assets); + } + + if (exportDto.IncludeUsers) + { + includedItems.Add(Constants.Category_Users); + } + + if (exportDto.IncludeRoles) + { + includedItems.Add(Constants.Category_Roles); + } + + if (exportDto.IncludeVocabularies) + { + includedItems.Add(Constants.Category_Vocabularies); + } + if (exportDto.IncludeTemplates) { includedItems.Add(Constants.Category_Templates); } - if (exportDto.IncludeProperfileProperties) - { - includedItems.Add(Constants.Category_ProfileProps); - } - - // This might be added always. - if (exportDto.IncludeExtensions) - { - includedItems.Add(Constants.Category_Packages); - } - + if (exportDto.IncludeProperfileProperties) + { + includedItems.Add(Constants.Category_ProfileProps); + } + + // This might be added always. + if (exportDto.IncludeExtensions) + { + includedItems.Add(Constants.Category_Packages); + } + var additionalItems = new List(); foreach (var includedItem in includedItems) { @@ -657,15 +590,15 @@ var name in additionalItems.Add(basePortableService.Category); } } - + additionalItems.ForEach(i => includedItems.Add(i)); // must be included always when there is at least one other object to process - if (includedItems.Any()) - { - includedItems.Add(Constants.Category_Portal); - } - + if (includedItems.Any()) + { + includedItems.Add(Constants.Category_Portal); + } + return includedItems; } @@ -688,7 +621,7 @@ private static int GetTimeoutPerSlot() { value = 12 * 60 * 60; } - + return value; } @@ -712,11 +645,11 @@ private static void DoUnPacking(ExportImportJob importJob) { var extractFolder = Path.Combine(ExportFolder, importJob.Directory); var dbName = Path.Combine(extractFolder, Constants.ExportDbName); - if (File.Exists(dbName)) - { - return; - } - + if (File.Exists(dbName)) + { + return; + } + var zipDbName = Path.Combine(extractFolder, Constants.ExportZipDbName); CompressionUtil.UnZipFileFromArchive(Constants.ExportDbName, zipDbName, extractFolder, false); } @@ -733,11 +666,11 @@ private static void CleanupDatabaseIfDirty(IExportImportRepository repository) var isDirty = exportDto.IsDirty; exportDto.IsDirty = true; repository.UpdateSingleItem(exportDto); - if (!isDirty) - { - return; - } - + if (!isDirty) + { + return; + } + var typeLocator = new TypeLocator(); var types = typeLocator.GetAllMatchingTypes( t => t != null && t.IsClass && !t.IsAbstract && t.IsVisible && @@ -754,12 +687,79 @@ private static void CleanupDatabaseIfDirty(IExportImportRepository repository) } catch (Exception e) { - Logger.ErrorFormat( + Logger.ErrorFormat( "Unable to clear {0} while calling CleanupDatabaseIfDirty. Error: {1}", type.Name, e.Message); } } } + + private void PrepareCheckPoints(int jobId, List parentServices, List implementors, + HashSet includedItems, IList checkpoints) + { + // there must be one parent implementor at least for this to work + var nextLevelServices = new List(); + var firstIteration = true; + if (checkpoints.Any()) + { + return; + } + + do + { + foreach (var service in parentServices.OrderBy(x => x.Priority)) + { + if (implementors.Count > 0) + { + // collect children for next iteration + var children = + implementors.Where(imp => service.Category.Equals(imp.ParentCategory, IgnoreCaseComp)); + nextLevelServices.AddRange(children); + implementors = implementors.Except(nextLevelServices).ToList(); + } + + if ((firstIteration && includedItems.Any(x => x.Equals(service.Category, IgnoreCaseComp))) || + (!firstIteration && includedItems.Any(x => x.Equals(service.ParentCategory, IgnoreCaseComp)))) + { + var serviceAssembly = service.GetType().Assembly.GetName().Name; + + service.CheckPoint = checkpoints.FirstOrDefault(cp => cp.Category == service.Category && cp.AssemblyName == serviceAssembly); + + if (service.CheckPoint != null) + { + continue; + } + + service.CheckPoint = new ExportImportChekpoint + { + JobId = jobId, + AssemblyName = serviceAssembly, + Category = service.Category, + Progress = 0, + }; + + // persist the record in db + this.CheckpointCallback(service); + } + } + + firstIteration = false; + parentServices = new List(nextLevelServices); + nextLevelServices.Clear(); + } + while (parentServices.Count > 0); + } + + /// + /// Callback function to provide a checkpoint mechanism for an implementation. + /// + /// The implementation. + /// Treu to stop further processing; false otherwise. + private bool CheckpointCallback(BasePortableService service) + { + EntitiesController.Instance.UpdateJobChekpoint(service.CheckPoint); + return this.TimeIsUp; + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs index 48d5698ffc8..023e2cb41a4 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportChekpoint.cs @@ -19,19 +19,19 @@ public class ExportImportChekpoint : IHydratable private double _progress; public int CheckpointId { get; set; } - + public int JobId { get; set; } - + public string AssemblyName { get; set; } - + public string Category { get; set; } - + public int Stage { get; set; } // all stages start from 0 and increase - + public string StageData { get; set; } // discretionary data - + public DateTime StartDate { get; set; } - + public DateTime LastUpdateDate { get; set; } public bool Completed { get; set; } @@ -39,24 +39,24 @@ public class ExportImportChekpoint : IHydratable public double Progress { get { return this._progress; } - + set { - if (value < 0) - { - value = 0; - } - else if (value > 100) - { - value = 100; - } - + if (value < 0) + { + value = 0; + } + else if (value > 100) + { + value = 100; + } + this._progress = value; } } public int TotalItems { get; set; } - + public int ProcessedItems { get; set; } public int KeyID diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs index 0a0e101e1f1..18bdaa84dfa 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJob.cs @@ -18,29 +18,29 @@ namespace Dnn.ExportImport.Components.Entities public class ExportImportJob : IHydratable { public int JobId { get; set; } - + public int PortalId { get; set; } - + public JobType JobType { get; set; } - + public JobStatus JobStatus { get; set; } - + public bool IsCancelled { get; set; } - + public string Name { get; set; } - + public string Description { get; set; } - + public int CreatedByUserId { get; set; } - + public DateTime CreatedOnDate { get; set; } - + public DateTime LastModifiedOnDate { get; set; } - + public DateTime? CompletedOnDate { get; set; } - + public string Directory { get; set; } - + public string JobObject { get; set; } public int KeyID @@ -72,7 +72,7 @@ public void Fill(IDataReader dr) this.CreatedOnDate.Hour, this.CreatedOnDate.Minute, this.CreatedOnDate.Second, this.CreatedOnDate.Millisecond, DateTimeKind.Utc); } - + if (this.LastModifiedOnDate.Kind != DateTimeKind.Utc) { this.LastModifiedOnDate = new DateTime( diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs index 49901ac98c2..038f53bfaac 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportJobLog.cs @@ -17,15 +17,15 @@ namespace Dnn.ExportImport.Components.Entities public class ExportImportJobLog : IHydratable { public int JobLogId { get; set; } - + public int JobId { get; set; } - + public string Name { get; set; } - + public string Value { get; set; } - + public int Level { get; set; } - + public DateTime CreatedOnDate { get; set; } public int KeyID diff --git a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs index 9ed69584145..232d88d310e 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Entities/ExportImportSetting.cs @@ -10,11 +10,11 @@ namespace Dnn.ExportImport.Components.Entities public class ExportImportSetting { public string SettingName { get; set; } - + public string SettingValue { get; set; } - + public bool SettingIsSecure { get; set; } - + public int CreatedByUserId { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs index d1a2c9e558b..5a6d031fb0c 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/IEntitiesController.cs @@ -15,59 +15,59 @@ namespace Dnn.ExportImport.Components.Interfaces public interface IEntitiesController { ExportImportJob GetFirstActiveJob(); - + ExportImportJob GetJobById(int jobId); - + IList GetJobSummaryLog(int jobId); - + IList GetJobFullLog(int jobId); - + int GetAllJobsCount(int? portalId, int? jobType, string keywords); - + IList GetAllJobs(int? portalId, int? pageSize, int? pageIndex, int? jobType, string keywords); - + DateTime? GetLastJobTime(int portalId, JobType jobType); - + void UpdateJobInfo(ExportImportJob job); - + void UpdateJobStatus(ExportImportJob job); - + void SetJobCancelled(ExportImportJob job); - + void RemoveJob(ExportImportJob job); - + IList GetJobChekpoints(int jobId); - + void UpdateJobChekpoint(ExportImportChekpoint checkpoint); IList GetPortalTabs(int portalId, bool includeDeleted, bool includeSystem, DateTime toDate, DateTime? fromDate); - + IList GetTabSettings(int tabId, DateTime toDate, DateTime? fromDate); - + IList GetTabPermissions(int tabId, DateTime toDate, DateTime? fromDate); - + IList GetTabUrls(int tabId, DateTime toDate, DateTime? fromDate); IList GetModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); - + IList GetModuleSettings(int moduleId, DateTime toDate, DateTime? fromDate); - + IList GetModulePermissions(int moduleId, DateTime toDate, DateTime? fromDate); IList GetTabModules(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); - + IList GetTabModuleSettings(int tabId, DateTime toDate, DateTime? fromDate); - + IList GetTabModuleSettings(int tabId, bool includeDeleted, DateTime toDate, DateTime? fromDate); PermissionInfo GetPermissionInfo(string permissionCode, string permissionKey, string permissionName); void SetTabSpecificData(int tabId, bool isDeleted, bool isVisible); - + void SetTabModuleDeleted(int tabModuleId, bool isDeleted); - + void SetUserDeleted(int portalId, int userId, bool isDeleted); - + void RunSchedule(); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs index 17185f9ad8d..ddda63c6771 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Interfaces/ISettingsController.cs @@ -11,9 +11,9 @@ namespace Dnn.ExportImport.Components.Interfaces public interface ISettingsController { IEnumerable GetAllSettings(); - + ExportImportSetting GetSetting(string settingName); - + void AddSetting(ExportImportSetting exportImportSetting); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs index 40b2024adad..e6f770075f3 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Models/ExportImportResult.cs @@ -17,16 +17,16 @@ public ExportImportResult() { this.CompleteLog = this.CompleteLog = new List(); } - - public int JobId { get; set; } - - public IList CompleteLog { get; private set; } public IList Summary { get { return this.CompleteLog.Where(item => item.ReportLevel >= ReportLevel.Info).ToList(); } } + public int JobId { get; set; } + + public IList CompleteLog { get; private set; } + 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 b6c56dde2a0..0cd64dc3c2d 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Providers/DataProvider.cs @@ -15,7 +15,7 @@ namespace Dnn.ExportImport.Components.Providers using DotNetNuke.Security.Permissions; internal class DataProvider - { + { private static readonly DataProvider Provider; private readonly DotNetNuke.Data.DataProvider _dataProvider = DotNetNuke.Data.DataProvider.Instance(); @@ -28,13 +28,13 @@ static DataProvider() 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) { this._dataProvider.ExecuteNonQuery( @@ -67,11 +67,11 @@ public void UpdateJobInfo(int jobId, string name, string description) public void UpdateJobStatus(int jobId, JobStatus jobStatus) { DateTime? completeDate = null; - if (jobStatus == JobStatus.Failed || jobStatus == JobStatus.Successful) - { - completeDate = DateUtils.GetDatabaseUtcTime(); - } - + if (jobStatus == JobStatus.Failed || jobStatus == JobStatus.Successful) + { + completeDate = DateUtils.GetDatabaseUtcTime(); + } + this._dataProvider.ExecuteNonQuery( "ExportImportJobs_UpdateStatus", jobId, jobStatus, completeDate); } @@ -91,7 +91,7 @@ public IDataReader GetExportImportSettings() { return this._dataProvider.ExecuteReader("ExportImport_Settings"); } - + public void AddExportImportSetting(ExportImportSetting exportImportSetting) { this._dataProvider.ExecuteNonQuery("ExportImport_AddSetting", exportImportSetting.SettingName, @@ -143,13 +143,13 @@ public IDataReader GetJobChekpoints(int jobId) var d = datim.Value; datim = new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond, DateTimeKind.Utc); } - + return datim; } public void UpsertJobChekpoint(ExportImportChekpoint checkpoint) { - this._dataProvider.ExecuteNonQuery( + this._dataProvider.ExecuteNonQuery( "ExportImportCheckpoints_Upsert", checkpoint.JobId, checkpoint.AssemblyName, checkpoint.Category, checkpoint.Stage, checkpoint.StageData, Null.SetNullInteger(Math.Floor(checkpoint.Progress)), checkpoint.TotalItems, checkpoint.ProcessedItems, this._dataProvider.GetNull(checkpoint.StartDate), checkpoint.Completed); @@ -194,7 +194,7 @@ public int GetRoleIdByName(int portalId, string roleName) { return this._dataProvider.ExecuteScalar("Export_RoleIdByName", this._dataProvider.GetNull(portalId), roleName); } - + public void SetRoleAutoAssign(int roleId) { this._dataProvider.ExecuteNonQuery("Export_RoleSetAutoAssign", roleId); @@ -264,8 +264,8 @@ public IDataReader GetFiles(int portalId, int? folderId, DateTime toDate, DateTi public int? GetPermissionId(string permissionCode, string permissionKey, string permissionName) { return - CBO.GetCachedObject>( - new CacheItemArgs( + CBO.GetCachedObject>( + new CacheItemArgs( DataCache.PermissionsCacheKey, DataCache.PermissionsCacheTimeout, DataCache.PermissionsCachePriority), diff --git a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs index 1e9c2386db3..7edc4028972 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Scheduler/ExportImportScheduler.cs @@ -24,8 +24,6 @@ public class ExportImportScheduler : SchedulerClient { 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"; @@ -36,7 +34,9 @@ public class ExportImportScheduler : SchedulerClient private const int EmergencyHistoryNumber = 1; private const int DefaultHistoryNumber = 60; - + + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ExportImportScheduler)); + public ExportImportScheduler(ScheduleHistoryItem objScheduleHistoryItem) { this.ScheduleHistoryItem = objScheduleHistoryItem; @@ -84,7 +84,7 @@ public override void DoWork() engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } - + EntitiesController.Instance.UpdateJobStatus(job); break; case JobType.Import: @@ -113,14 +113,14 @@ public override void DoWork() engine.AddLogsToDatabase(job.JobId, result.CompleteLog); throw; } - + EntitiesController.Instance.UpdateJobStatus(job); if (job.JobStatus == JobStatus.Successful || job.JobStatus == JobStatus.Cancelled) { // clear everything to be sure imported items take effect DataCache.ClearCache(); } - + break; default: throw new Exception("Unknown job type: " + job.JobType); @@ -154,7 +154,7 @@ public override void DoWork() { sb.Append($"
  • {entry.Name}: {entry.Value}
  • "); } - + sb.Append(""); } @@ -163,7 +163,7 @@ public override void DoWork() Logger.Trace("Site Export/Import: Job Finished"); } - + // SetLastSuccessfulIndexingDateTime(ScheduleHistoryItem.ScheduleID, ScheduleHistoryItem.StartDate); } catch (Exception ex) @@ -171,7 +171,7 @@ public override void DoWork() this.ScheduleHistoryItem.Succeeded = false; this.ScheduleHistoryItem.AddLogNote("
    Export/Import EXCEPTION: " + ex.Message); this.Errored(ref ex); - + // this duplicates the logging // if (ScheduleHistoryItem.ScheduleSource != ScheduleSource.STARTED_FROM_BEGIN_REQUEST) // { diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs index e6aada00f44..b0de22bafe3 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/AssetsExportService.cs @@ -27,10 +27,10 @@ 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( + private static readonly Regex UserFolderEx = new Regex( @"users/\d+/\d+/(\d+)/", RegexOptions.Compiled | RegexOptions.IgnoreCase); @@ -45,18 +45,18 @@ public class AssetsExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - // Skip the export if all the folders have been processed already. - if (this.CheckPoint.Stage >= 1) - { - return; - } - - // Create Zip File to hold files + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalFolderExported = 0; @@ -78,25 +78,25 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) .GetFolders(portalId, toDate, fromDate)).ToList(); var totalFolders = folders.Any() ? folders.Count : 0; folders = folders.Skip(skip).ToList(); - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalFolders : this.CheckPoint.TotalItems; this.CheckPoint.ProcessedItems = skip; this.CheckPoint.Progress = this.CheckPoint.TotalItems > 0 ? skip * 100.0 / this.CheckPoint.TotalItems : 0; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + using (var zipArchive = CompressionUtil.OpenCreate(assetsFile)) { foreach (var folder in folders) { - if (this.CheckCancelled(exportJob)) - { - break; - } - + if (this.CheckCancelled(exportJob)) + { + break; + } + var isUserFolder = false; var files = @@ -111,7 +111,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) folder.Username = UserController.GetUserById(portalId, Convert.ToInt32(userId))?.Username; } - + if (folder.ParentId != null && folder.ParentId > 0) { // If parent id exists then change the parent folder id to parent id. @@ -122,7 +122,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItem(folder, null); totalFolderExported++; - + // Include permissions only if IncludePermissions=true if (exportDto.IncludePermissions) { @@ -132,7 +132,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItems(permissions, folder.Id); totalFolderPermissionsExported += permissions.Count; } - + this.Repository.CreateItems(files, folder.Id); totalFilesExported += files.Count; var folderOffset = portal.HomeDirectoryMapPath.Length + @@ -143,24 +143,24 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) CompressionUtil.AddFilesToArchive(zipArchive, files.Select(file => portal.HomeDirectoryMapPath + folder.FolderPath + this.GetActualFileName(file)), folderOffset, isUserFolder ? "TempUsers" : null); } - + this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalFolders; this.CheckPoint.StageData = null; currentIndex++; - + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) - { - return; - } - + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } + this.Repository.RebuildIndex(x => x.Id, true); this.Repository.RebuildIndex(x => x.UserId); this.Repository.RebuildIndex(x => x.ReferenceId); } } - + this.CheckPoint.Completed = true; this.CheckPoint.Stage++; currentIndex = 0; @@ -179,20 +179,20 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - - // Stage 1: Portals files unzipped. - // Stage 2: All folders and files imported. - // Stage 3: Synchronization completed. - // Skip the export if all the folders have been processed already. - if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Stage 1: Portals files unzipped. + // Stage 2: All folders and files imported. + // Stage 3: Synchronization completed. + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) + { + return; + } + var totalFolderImported = 0; var totalFolderPermissionsImported = 0; var totalFilesImported = 0; @@ -215,15 +215,15 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { CompressionUtil.UnZipArchive(assetsFile, portal.HomeDirectoryMapPath, importDto.CollisionResolution == CollisionResolution.Overwrite); - + // Stage 1: Once unzipping of portal files is completed. this.CheckPoint.Stage++; this.CheckPoint.StageData = null; this.CheckPoint.Progress = 10; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } } @@ -235,23 +235,23 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var sourceFolders = this.Repository.GetAllItems(x => x.CreatedOnDate, true, skip).ToList(); var totalFolders = sourceFolders.Any() ? sourceFolders.Count : 0; - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalFolders : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var sourceFolder in sourceFolders) { - if (this.CheckCancelled(importJob)) - { - break; - } - - // PROCESS FOLDERS - // Create new or update existing folder + if (this.CheckCancelled(importJob)) + { + break; + } + + // PROCESS FOLDERS + // Create new or update existing folder if (this.ProcessFolder(importJob, importDto, sourceFolder)) { totalFolderImported++; @@ -262,7 +262,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) // PROCESS FOLDER PERMISSIONS var sourceFolderPermissions = this.Repository.GetRelatedItems(sourceFolder.Id).ToList(); - + // Replace folderId for each permission with new one. sourceFolderPermissions.ForEach(x => { @@ -282,14 +282,14 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.ProcessFolderPermission(importJob, importDto, folderPermission, localPermissions); } - + totalFolderPermissionsImported += sourceFolderPermissions.Count; } // PROCESS FILES var sourceFiles = this.Repository.GetRelatedItems(sourceFolder.Id).ToList(); - + // Replace folderId for each file with new one. sourceFiles.ForEach(x => { @@ -307,21 +307,21 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { this.ProcessFiles(importJob, importDto, file, localFiles); } - + totalFilesImported += sourceFiles.Count; } currentIndex++; this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = 10 + (this.CheckPoint.ProcessedItems * 90.0 / totalFolders); - + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) - { - return; - } + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } - + currentIndex = 0; this.CheckPoint.Completed = true; this.CheckPoint.Stage++; @@ -338,10 +338,10 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.Result.AddSummary("Imported Folder Permissions", totalFolderPermissionsImported.ToString()); this.Result.AddSummary("Imported Files", totalFilesImported.ToString()); - if (Directory.Exists(userFolderPath) && currentIndex == 0) - { - Directory.Delete(userFolderPath, true); - } + if (Directory.Exists(userFolderPath) && currentIndex == 0) + { + Directory.Delete(userFolderPath, true); + } } } } @@ -355,22 +355,22 @@ 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); - } - + 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; - if (folder == null) - { - return false; - } - + if (folder == null) + { + return false; + } + var existingFolder = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.FolderPath ?? string.Empty)); var isUpdate = false; var modifiedBy = Util.GetUserIdByName(importJob, folder.LastModifiedByUserId, folder.LastModifiedByUserName); @@ -387,14 +387,14 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - + folder.FolderPath = string.IsNullOrEmpty(folder.FolderPath) ? string.Empty : folder.FolderPath; var folderMapping = FolderMappingController.Instance.GetFolderMapping(portalId, folder.FolderMappingName); - if (folderMapping == null) - { - return false; - } - + if (folderMapping == null) + { + return false; + } + var workFlowId = this.GetLocalWorkFlowId(folder.WorkflowId); if (isUpdate) { @@ -421,7 +421,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor // Find the previously created parent folder id. folder.ParentId = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance().GetFolder(portalId, folder.ParentFolderPath ?? string.Empty))?.FolderId; } - + // ignore folders which start with Users but are not user folders. if (!folder.FolderPath.StartsWith(DefaultUsersFoldersPath)) { @@ -432,7 +432,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor createdBy, folderMapping.FolderMappingID, folder.IsVersioned, workFlowId, folder.ParentId ?? Null.NullInteger); } - + // Case when the folder is a user folder. else if (folder.UserId != null && folder.UserId > 0 && !string.IsNullOrEmpty(folder.Username)) { @@ -442,7 +442,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor folder.FolderId = 0; return false; } - + userInfo.IsSuperUser = false; var newFolder = FolderManager.Instance.GetUserFolder(userInfo); folder.FolderId = newFolder.FolderID; @@ -456,7 +456,7 @@ private bool ProcessFolder(ExportImportJob importJob, ImportDto importDto, Expor return false; } } - + return true; } @@ -465,11 +465,11 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import { var portalId = importJob.PortalId; var noRole = Convert.ToInt32(Globals.glbRoleNothing); - if (folderPermission == null) - { - return; - } - + if (folderPermission == null) + { + return; + } + var roleId = Util.GetRoleIdByName(portalId, folderPermission.RoleId ?? noRole, folderPermission.RoleName); var userId = UserController.GetUserByName(portalId, folderPermission.Username)?.UserID; @@ -495,7 +495,7 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, folderPermission.LastModifiedByUserId, @@ -520,21 +520,21 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import if (folderPermission.UserId != null && folderPermission.UserId > 0 && !string.IsNullOrEmpty(folderPermission.Username)) { folderPermission.UserId = userId; - if (folderPermission.UserId == null) - { - return; - } + if (folderPermission.UserId == null) + { + return; + } } - + if (folderPermission.RoleId != null && folderPermission.RoleId > noRole && !string.IsNullOrEmpty(folderPermission.RoleName)) { folderPermission.RoleId = roleId; - if (folderPermission.RoleId == null) - { - return; - } + if (folderPermission.RoleId == null) + { + return; + } } - + var createdBy = Util.GetUserIdByName(importJob, folderPermission.CreatedByUserId, folderPermission.CreatedByUserName); @@ -544,17 +544,17 @@ private void ProcessFolderPermission(ExportImportJob importJob, ImportDto import folderPermission.UserId ?? Null.NullInteger, createdBy); } } - + folderPermission.LocalId = folderPermission.FolderPermissionId; } private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, ExportFile file, IEnumerable localFiles) { - if (file == null) - { - return; - } - + if (file == null) + { + return; + } + var existingFile = localFiles.FirstOrDefault(x => x.FileName == file.FileName); var isUpdate = false; if (existingFile != null) @@ -570,7 +570,7 @@ private void ProcessFiles(ExportImportJob importJob, ImportDto importDto, Export throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, file.LastModifiedByUserId, file.LastModifiedByUserName); @@ -599,15 +599,15 @@ 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.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. + file.StartDate, file.EndDate ?? Null.NullDate, file.EnablePublishPeriod, + + // file.ContentItemId ?? Null.NullInteger);--If we keep it we will see FK_PK relationship errors. Null.NullInteger); - - if (file.Content != null) - { - DotNetNuke.Data.DataProvider.Instance().UpdateFileContent(file.FileId, file.Content); - } + + if (file.Content != null) + { + DotNetNuke.Data.DataProvider.Instance().UpdateFileContent(file.FileId, file.Content); + } } } @@ -617,27 +617,27 @@ private void SyncUserFolder(int portalId, ExportFolder folder) var tempUsersFolderPath = $"{string.Format(UsersAssetsTempFolder, portal.HomeDirectoryMapPath.TrimEnd('\\'))}{folder.FolderPath}"; var newUsersFolderPath = $"{portal.HomeDirectoryMapPath}{folder.FolderPath}"; - if (!Directory.Exists(tempUsersFolderPath)) - { - return; - } - - if (!Directory.Exists(newUsersFolderPath)) - { - Directory.CreateDirectory(newUsersFolderPath); - } - + if (!Directory.Exists(tempUsersFolderPath)) + { + return; + } + + if (!Directory.Exists(newUsersFolderPath)) + { + Directory.CreateDirectory(newUsersFolderPath); + } + var files = Directory.GetFiles(tempUsersFolderPath, "*.*", SearchOption.AllDirectories); var dirInfo = new DirectoryInfo(newUsersFolderPath); foreach ( var mFile in files.Select(file => new System.IO.FileInfo(file))) { - if (File.Exists(dirInfo + "\\" + mFile.Name)) - { - File.Delete(dirInfo + "\\" + mFile.Name); - } - + if (File.Exists(dirInfo + "\\" + mFile.Name)) + { + File.Delete(dirInfo + "\\" + mFile.Name); + } + mFile.MoveTo(dirInfo + "\\" + mFile.Name); } } @@ -656,7 +656,7 @@ private int GetCurrentSkip() dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } - + return 0; } @@ -667,7 +667,7 @@ private int GetLocalWorkFlowId(int? exportedWorkFlowId) var state = this.Repository.GetItem(item => item.WorkflowID == exportedWorkFlowId); return state?.LocalId ?? -1; } - + return -1; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs index b7c92b530f0..6cb89334761 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/BasePortableService.cs @@ -16,6 +16,26 @@ namespace Dnn.ExportImport.Components.Services ///
    public abstract class BasePortableService { + // The following properties and methods must be overriden in descendant classes + + /// + /// Gets category name for the exportable module. For example: "ASSETS". + /// + public abstract string Category { get; } + + /// + /// Gets category name for the parent exportable module. For example: "USERS". + /// If this is null, then the category is a top parent. If this is not null, + /// then this category will be included automatically when the parent is included. + /// + public abstract string ParentCategory { get; } + + /// + /// Gets a priority for exporting/importing the object. Objects with higher + /// priority are exported/imported first. Highest priority is 0. + /// + public abstract uint Priority { get; } + /// /// Gets or sets an object to record the export/import progress information. /// This is set by the export/import engine. @@ -52,30 +72,10 @@ public abstract class BasePortableService /// True if the implementation to abort progress; false to continue. public Func CheckPointStageCallback { get; set; } - // The following properties and methods must be overriden in descendant classes - - /// - /// Gets category name for the exportable module. For example: "ASSETS". - /// - public abstract string Category { get; } - - /// - /// Gets category name for the parent exportable module. For example: "USERS". - /// If this is null, then the category is a top parent. If this is not null, - /// then this category will be included automatically when the parent is included. - /// - public abstract string ParentCategory { get; } - - /// - /// Gets a priority for exporting/importing the object. Objects with higher - /// priority are exported/imported first. Highest priority is 0. - /// - public abstract uint Priority { get; } - public abstract void ExportData(ExportImportJob exportJob, ExportDto exportDto); - + public abstract void ImportData(ExportImportJob importJob, ImportDto importDto); - + public abstract int GetImportTotal(); } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs index 9b25b06eed4..5238d900f27 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PackagesExportService.cs @@ -36,18 +36,18 @@ public class PackagesExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - // Skip the export if all the folders have been processed already. - if (this.CheckPoint.Stage >= 1) - { - return; - } - - // Create Zip File to hold files + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalPackagesExported = 0; @@ -68,11 +68,11 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalPackages : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var file in skinPackageFiles) { var exportPackage = this.GenerateExportPackage(file); @@ -88,12 +88,12 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalPackages; currentIndex++; - + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) - { - return; - } + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } this.CheckPoint.Stage++; @@ -112,17 +112,17 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - - // Skip the export if all the templates have been processed already. - if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) + { + return; + } + this._exportImportJob = importJob; this.ProcessImportModulePackages(importDto); @@ -187,7 +187,7 @@ private int GetCurrentSkip() dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } - + return 0; } @@ -237,7 +237,7 @@ private void ProcessImportModulePackage(ExportPackage exportPackage, string temp var packageName = exportPackage.PackageName; var version = exportPackage.Version; - var existPackage = PackageController.Instance.GetExtensionPackage( + var existPackage = PackageController.Instance.GetExtensionPackage( Null.NullInteger, p => p.PackageType == packageType && p.Name == packageName); if (existPackage != null && @@ -245,7 +245,7 @@ private void ProcessImportModulePackage(ExportPackage exportPackage, string temp (existPackage.Version == version && collisionResolution == CollisionResolution.Ignore))) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Import Package ignores", $"{packageName} has higher version {existPackage.Version} installed, ignore import it"); return; @@ -256,7 +256,7 @@ private void ProcessImportModulePackage(ExportPackage exportPackage, string temp } catch (Exception ex) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Import Package error", $"{exportPackage.PackageName} : {exportPackage.Version} - {ex.Message}"); Logger.Error(ex); @@ -273,11 +273,11 @@ private void ProcessImportModulePackages(ImportDto importDto) var exportPackages = this.Repository.GetAllItems().ToList(); this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exportPackages.Count : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + if (this.CheckPoint.Stage == 0) { try @@ -288,12 +288,12 @@ private void ProcessImportModulePackages(ImportDto importDto) this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / exportPackages.Count; - if (this.CheckPointStageCallback(this)) - { - break; + if (this.CheckPointStageCallback(this)) + { + break; } } - + this.CheckPoint.Stage++; this.CheckPoint.Completed = true; } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs index b80e8f53b1b..8a44cae0f8d 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PageTemplatesExportService.cs @@ -34,18 +34,18 @@ public class PageTemplatesExportService : AssetsExportService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - // Skip the export if all the folders have been processed already. - if (this.CheckPoint.Stage >= 1) - { - return; - } - - // Create Zip File to hold files + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + + // Create Zip File to hold files var skip = this.GetCurrentSkip(); var currentIndex = skip; var totalTemplatesExported = 0; @@ -70,11 +70,11 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalTemplates : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + foreach (var template in templates) { this.Repository.CreateItem(template, null); @@ -90,14 +90,14 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalTemplates; currentIndex++; - + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) - { - return; - } + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } - + this.CheckPoint.Stage++; currentIndex = 0; this.CheckPoint.Completed = true; @@ -114,27 +114,27 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - - // Skip the export if all the templates have been processed already. - if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 2 || this.CheckPoint.Completed) + { + return; + } + var portalId = importJob.PortalId; var templatesFile = string.Format(this._templatesFolder, importJob.Directory.TrimEnd('\\').TrimEnd('/')); var totalTemplates = this.GetImportTotal(); this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalTemplates : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + if (this.CheckPoint.Stage == 0) { if (!File.Exists(templatesFile)) @@ -157,13 +157,13 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.Progress = 90; this.CheckPoint.TotalItems = totalTemplates; this.CheckPoint.ProcessedItems = totalTemplates; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } } - + if (this.CheckPoint.Stage == 1) { Func predicate = x => x.Folder; @@ -195,7 +195,7 @@ private int GetCurrentSkip() dynamic stageData = JsonConvert.DeserializeObject(this.CheckPoint.StageData); return Convert.ToInt32(stageData.skip) ?? 0; } - + return 0; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs index a17c55df943..d75a662e154 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PagesExportService.cs @@ -46,11 +46,20 @@ 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; - + private IModuleController _moduleController; + private ExportImportJob _exportImportJob; + private ImportDto _importDto; + private ExportDto _exportDto; + + private IList _exportedModuleDefinitions = new List(); + private Dictionary _partialImportedTabs = new Dictionary(); + private Dictionary _searchedParentTabs = new Dictionary(); + private IList _importContentList = new List(); // map the exported module and local module. + public override string Category => Constants.Category_Pages; public override string ParentCategory => null; @@ -62,15 +71,6 @@ public class PagesExportService : BasePortableService public virtual bool IgnoreParentMatch { get; set; } = false; protected ImportDto ImportDto => this._importDto; - private IModuleController _moduleController; - private ExportImportJob _exportImportJob; - private ImportDto _importDto; - private ExportDto _exportDto; - - private IList _exportedModuleDefinitions = new List(); - 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) { @@ -87,7 +87,7 @@ public static void ResetContentsFlag(ExportImportRepository repository) items.ForEach(item => item.IsRestored = false); repository.UpdateItems(items); } - + toSkip += batchSize; totalCount -= batchSize; } @@ -95,16 +95,16 @@ public static void ResetContentsFlag(ExportImportRepository repository) public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var checkedPages = exportDto.Pages.Where(p => p.CheckedState == TriCheckedState.Checked || p.CheckedState == TriCheckedState.CheckedWithAllChildren); if (checkedPages.Any()) { @@ -124,16 +124,16 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + this._exportImportJob = importJob; this._importDto = importDto; this._exportDto = importDto.ExportDto; @@ -152,7 +152,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) public override int GetImportTotal() { return this.Repository.GetCount(x => x.IsSystem == this.IncludeSystem); - } + } public void RestoreTab(TabInfo tab, PortalSettings portalSettings) { @@ -193,11 +193,11 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex this.Result.AddLogEntry("Ignored Tab", $"{otherTab.TabName} ({otherTab.TabPath})"); break; case CollisionResolution.Overwrite: - if (!this.IsTabPublished(localTab)) - { - return; - } - + if (!this.IsTabPublished(localTab)) + { + return; + } + SetTabData(localTab, otherTab); localTab.StateID = this.GetLocalStateId(otherTab.StateID); var parentId = this.IgnoreParentMatch ? otherTab.ParentId.GetValueOrDefault(Null.NullInteger) : TryFindLocalParentTabId(otherTab, exportedTabs, localTabs); @@ -208,10 +208,10 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex this.Result.AddLogEntry("Importing existing tab skipped as its parent was not found", $"{otherTab.TabName} ({otherTab.TabPath})", ReportLevel.Warn); return; } - + this.CheckForPartialImportedTabs(otherTab); } - + var tabType = Globals.GetURLType(otherTab.Url); if (tabType == TabType.Tab && !referenceTabs.Contains(localTab.TabID)) { @@ -221,14 +221,14 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex // this is not saved when adding the tab; so set it explicitly localTab.IsVisible = otherTab.IsVisible; EntitiesController.Instance.SetTabSpecificData(localTab.TabID, false, localTab.IsVisible); - + // Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. if (localTab.UniqueId != otherTab.UniqueId && !DataProvider.Instance().CheckTabUniqueIdExists(otherTab.UniqueId)) { localTab.UniqueId = otherTab.UniqueId; this.UpdateTabUniqueId(localTab.TabID, localTab.UniqueId); } - + try { localTab.TabPermissions.Clear(); // without this the UpdateTab() could fail @@ -237,7 +237,7 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex { localTab.Url = otherTab.Url; } - + this.SetPartialImportSettings(otherTab, localTab); this._tabController.UpdateTab(localTab); @@ -286,7 +286,7 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex { localTab.Url = otherTab.Url; } - + localTab.UniqueId = Guid.NewGuid(); this.SetPartialImportSettings(otherTab, localTab); otherTab.LocalId = localTab.TabID = this._tabController.AddTab(localTab, false); @@ -314,7 +314,7 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex // this is not saved upon updating the tab localTab.IsVisible = otherTab.IsVisible; EntitiesController.Instance.SetTabSpecificData(localTab.TabID, false, localTab.IsVisible); - + // _tabController.UpdateTab(localTab); // to clear cache // Try to set the unique id of existing page same as source page unique id, if possible. This will help for future updates etc. if (!DataProvider.Instance().CheckTabUniqueIdExists(otherTab.UniqueId)) @@ -329,7 +329,7 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex this.AddTabRelatedItems(localTab, otherTab, true); this.TriggerImportEvent(localTab); } - + var portalSettings = new PortalSettings(portalId); if (otherTab.IsDeleted) @@ -344,7 +344,7 @@ protected virtual void ProcessImportPage(ExportTab otherTab, IList ex this.RestoreTab(tab, portalSettings); } } - + this.UpdateParentInPartialImportTabs(localTab, otherTab, portalId, exportedTabs, localTabs); } @@ -363,10 +363,10 @@ private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable t.TabID == otherParent.LocalId); - if (localTab != null) - { - return localTab.TabID; - } + if (localTab != null) + { + return localTab.TabID; + } } } else if (exportedTab.TabPath.HasValue()) @@ -378,17 +378,89 @@ private static int TryFindLocalTabId(ExportTab exportedTab, IEnumerable path.Equals(t.TabPath, StringComparison.InvariantCultureIgnoreCase) && IsSameCulture(t.CultureCode, exportedTab.CultureCode)); - if (localTab != null) - { - return localTab.TabID; - } + if (localTab != null) + { + return localTab.TabID; + } } } } return -1; } - + + private static bool IsSameCulture(string sourceCultureCode, string targetCultureCode) + { + sourceCultureCode = !string.IsNullOrWhiteSpace(sourceCultureCode) ? sourceCultureCode : Localization.SystemLocale; + targetCultureCode = !string.IsNullOrWhiteSpace(targetCultureCode) ? targetCultureCode : Localization.SystemLocale; + + return sourceCultureCode == targetCultureCode; + } + + private static void SetTabData(TabInfo localTab, ExportTab otherTab) + { + localTab.TabOrder = otherTab.TabOrder; + localTab.TabName = otherTab.TabName; + localTab.IsVisible = otherTab.IsVisible; + localTab.IconFile = otherTab.IconFile; + localTab.DisableLink = otherTab.DisableLink; + localTab.Title = otherTab.Title; + localTab.Description = otherTab.Description; + localTab.KeyWords = otherTab.KeyWords; + + // localTab.IsDeleted = otherTab.IsDeleted; // DO NOT enable this; leave this to other logic + localTab.Url = otherTab.Url; + localTab.SkinSrc = otherTab.SkinSrc; + localTab.ContainerSrc = otherTab.ContainerSrc; + localTab.StartDate = otherTab.StartDate ?? DateTime.MinValue; + localTab.EndDate = otherTab.EndDate ?? DateTime.MinValue; + localTab.RefreshInterval = otherTab.RefreshInterval ?? -1; + localTab.PageHeadText = otherTab.PageHeadText; + localTab.IsSecure = otherTab.IsSecure; + localTab.PermanentRedirect = otherTab.PermanentRedirect; + localTab.SiteMapPriority = otherTab.SiteMapPriority; + localTab.IconFileLarge = otherTab.IconFileLarge; + localTab.CultureCode = otherTab.CultureCode; + + // localTab.UniqueId = otherTab.UniqueId; + localTab.VersionGuid = otherTab.VersionGuid; + localTab.LocalizedVersionGuid = otherTab.LocalizedVersionGuid; + localTab.Level = otherTab.Level; + localTab.TabPath = otherTab.TabPath; + localTab.HasBeenPublished = otherTab.HasBeenPublished; + localTab.IsSystem = otherTab.IsSystem; + 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 ProcessImportPages() { this._dataProvider = DataProvider.Instance(); @@ -405,11 +477,11 @@ private void ProcessImportPages() // 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; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + var progressStep = 100.0 / exportedTabs.OrderByDescending(x => x.Id).Count(x => x.Id < this._totals.LastProcessedId); var index = 0; @@ -417,25 +489,25 @@ private void ProcessImportPages() this._importContentList.Clear(); foreach (var otherTab in exportedTabs) { - if (this.CheckCancelled(this._exportImportJob)) - { - break; - } - - if (this._totals.LastProcessedId > index) - { - continue; // this is the exported DB row ID; not the TabID - } - + 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; - } - + if (this.CheckPointStageCallback(this)) + { + break; + } + this._totals.LastProcessedId = index++; this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); } @@ -489,7 +561,7 @@ private void UpdateDefaultLanguageGuid(int portalId, TabInfo localTab, ExportTab return; } } - + localTab.DefaultLanguageGuid = exportedTab.DefaultLanguageGuid ?? Null.NullGuid; } @@ -506,7 +578,7 @@ private void TriggerImportEvent(TabInfo localTab) { localTab.TabSettings.Add("TabImported", "Y"); } - + this._tabController.UpdateTab(localTab); TabController.Instance.DeleteTabSetting(localTab.TabID, "TabImported"); } @@ -558,7 +630,7 @@ private int ImportTabSettings(TabInfo localTab, ExportTab otherTab, bool isNew) { goto case CollisionResolution.Ignore; } - + break; case CollisionResolution.Ignore: this.Result.AddLogEntry("Ignored tab setting", other.SettingName); @@ -574,11 +646,11 @@ private int ImportTabSettings(TabInfo localTab, ExportTab otherTab, bool isNew) private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNew) { - if (!this._exportDto.IncludePermissions) - { - return 0; - } - + if (!this._exportDto.IncludePermissions) + { + return 0; + } + var noRole = Convert.ToInt32(Globals.glbRoleNothing); var count = 0; var tabPermissions = this.Repository.GetRelatedItems(otherTab.Id).ToList(); @@ -635,30 +707,30 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe { if (userId == null) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Couldn't add tab permission; User is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); continue; } - + local.UserID = userId.Value; } - + if (other.RoleID != null && other.RoleID > noRole && !string.IsNullOrEmpty(other.RoleName)) { if (roleId == null) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Couldn't add tab permission; Role is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); continue; } - + local.RoleID = roleId.Value; } - + localTab.TabPermissions.Add(local, true); - + // UNDONE: none set; not possible until after saving all tab permissions as donbefore exiting this method // var createdBy = Util.GetUserIdByName(_exportImportJob, other.CreatedByUserID, other.CreatedByUserName); // var modifiedBy = Util.GetUserIdByName(_exportImportJob, other.LastModifiedByUserID, other.LastModifiedByUserName); @@ -668,7 +740,7 @@ private int ImportTabPermissions(TabInfo localTab, ExportTab otherTab, bool isNe } else { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Couldn't add tab permission; Permission is undefined!", $"{other.PermissionKey} - {other.PermissionID}", ReportLevel.Warn); } @@ -707,7 +779,7 @@ private int ImportTabUrls(TabInfo localTab, ExportTab otherTab, bool isNew) { this.Result.AddLogEntry("EXCEPTION updating tab, Tab ID=" + local.TabId, ex.Message, ReportLevel.Error); } - + break; case CollisionResolution.Ignore: this.Result.AddLogEntry("Ignored tab url", other.Url); @@ -779,15 +851,15 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab } var otherModule = exportedModules.FirstOrDefault(m => m.ModuleID == other.ModuleID); - if (otherModule == null) - { - continue; // must not happen - } - + if (otherModule == null) + { + continue; // must not happen + } + var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByFriendlyName(other.FriendlyName); if (moduleDefinition == null) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Error adding tab module, ModuleDef=" + other.FriendlyName, "The modue definition is not present in the system", ReportLevel.Error); continue; // the module is not installed, therefore ignore it @@ -825,7 +897,7 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab Header = other.Header, Footer = other.Footer, CultureCode = other.CultureCode, - + // UniqueId = other.UniqueId, UniqueId = DataProvider.Instance().CheckTabModuleUniqueIdExists(other.UniqueId) ? Guid.NewGuid() : other.UniqueId, VersionGuid = other.VersionGuid, @@ -925,7 +997,7 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab Header = other.Header, Footer = other.Footer, CultureCode = other.CultureCode, - + // UniqueId = other.UniqueId, UniqueId = DataProvider.Instance().CheckTabModuleUniqueIdExists(other.UniqueId) ? Guid.NewGuid() : other.UniqueId, VersionGuid = other.VersionGuid, @@ -947,14 +1019,14 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab if (isDeleted != other.IsDeleted && !otherTab.IsDeleted) { local.IsDeleted = other.IsDeleted; - if (other.IsDeleted) - { - this._moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); - } - else - { - this._moduleController.RestoreModule(local); - } + if (other.IsDeleted) + { + this._moduleController.DeleteTabModule(local.TabID, local.ModuleID, true); + } + else + { + this._moduleController.RestoreModule(local); + } } } else @@ -1080,7 +1152,7 @@ private int ImportTabModulesAndRelatedItems(TabInfo localTab, ExportTab otherTab { Logger.Error(new Exception($"Delete TabModule Failed: {moduleId}", ex)); } - + this.Result.AddLogEntry("Removed existing tab module", "Module ID=" + moduleId); } } @@ -1212,7 +1284,7 @@ private int ImportModuleSettings(ModuleInfo localModule, ExportModule otherModul { goto case CollisionResolution.Ignore; } - + break; case CollisionResolution.Ignore: this.Result.AddLogEntry("Ignored module setting", other.SettingName); @@ -1256,21 +1328,21 @@ private int ImportModulePermissions(ModuleInfo localModule, ExportModule otherMo }; if (other.UserID != null && other.UserID > 0 && !string.IsNullOrEmpty(other.Username)) { - if (userId == null) - { - continue; - } - + if (userId == null) + { + continue; + } + local.UserID = userId.Value; } - + if (other.RoleID != null && other.RoleID > noRole && !string.IsNullOrEmpty(other.RoleName)) { - if (roleId == null) - { - continue; - } - + if (roleId == null) + { + continue; + } + local.RoleID = roleId.Value; } @@ -1338,7 +1410,7 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul catch (Exception ex) { this.Result.AddLogEntry("Error importing module data, Module ID=" + localModule.ModuleID, ex.Message, ReportLevel.Error); - Logger.ErrorFormat( + Logger.ErrorFormat( "ModuleContent: (Module ID={0}). Error: {1}{2}{3}", localModule.ModuleID, ex, Environment.NewLine, moduleContent.XmlContent); } @@ -1362,7 +1434,7 @@ private int ImportPortableContent(int tabId, ModuleInfo localModule, ExportModul } } } - + return 0; } @@ -1381,7 +1453,7 @@ private void ActionInWorkflowlessContext(int tabId, Action action) } } - private void DisableVersioning( + private void DisableVersioning( int tabId, out bool versionEnabledPortalLevel, out bool versionEnabledTabLevel, @@ -1400,7 +1472,7 @@ private void DisableVersioning( workflowSettings.SetWorkflowEnabled(portalId, tabId, false); } - private void RestoreVersioning( + private void RestoreVersioning( int tabId, bool versionEnabledPortalLevel, bool versionEnabledTabLevel, @@ -1452,7 +1524,7 @@ private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule o { goto case CollisionResolution.Ignore; } - + break; case CollisionResolution.Ignore: this.Result.AddLogEntry("Ignored module setting", other.SettingName); @@ -1466,78 +1538,6 @@ private int ImportTabModuleSettings(ModuleInfo localTabModule, ExportTabModule o return count; } - private static bool IsSameCulture(string sourceCultureCode, string targetCultureCode) - { - sourceCultureCode = !string.IsNullOrWhiteSpace(sourceCultureCode) ? sourceCultureCode : Localization.SystemLocale; - targetCultureCode = !string.IsNullOrWhiteSpace(targetCultureCode) ? targetCultureCode : Localization.SystemLocale; - - return sourceCultureCode == targetCultureCode; - } - - private static void SetTabData(TabInfo localTab, ExportTab otherTab) - { - localTab.TabOrder = otherTab.TabOrder; - localTab.TabName = otherTab.TabName; - localTab.IsVisible = otherTab.IsVisible; - localTab.IconFile = otherTab.IconFile; - localTab.DisableLink = otherTab.DisableLink; - localTab.Title = otherTab.Title; - localTab.Description = otherTab.Description; - localTab.KeyWords = otherTab.KeyWords; - - // localTab.IsDeleted = otherTab.IsDeleted; // DO NOT enable this; leave this to other logic - localTab.Url = otherTab.Url; - localTab.SkinSrc = otherTab.SkinSrc; - localTab.ContainerSrc = otherTab.ContainerSrc; - localTab.StartDate = otherTab.StartDate ?? DateTime.MinValue; - localTab.EndDate = otherTab.EndDate ?? DateTime.MinValue; - localTab.RefreshInterval = otherTab.RefreshInterval ?? -1; - localTab.PageHeadText = otherTab.PageHeadText; - localTab.IsSecure = otherTab.IsSecure; - localTab.PermanentRedirect = otherTab.PermanentRedirect; - localTab.SiteMapPriority = otherTab.SiteMapPriority; - localTab.IconFileLarge = otherTab.IconFileLarge; - localTab.CultureCode = otherTab.CultureCode; - - // localTab.UniqueId = otherTab.UniqueId; - localTab.VersionGuid = otherTab.VersionGuid; - localTab.LocalizedVersionGuid = otherTab.LocalizedVersionGuid; - localTab.Level = otherTab.Level; - localTab.TabPath = otherTab.TabPath; - localTab.HasBeenPublished = otherTab.HasBeenPublished; - localTab.IsSystem = otherTab.IsSystem; - 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) { foreach (var tabId in referenceTabs) @@ -1553,14 +1553,12 @@ private void RepairReferenceTabs(IList referenceTabs, IList localT } } } - } - + } + private void UpdateTabChangers(int tabId, int createdBy, int modifiedBy) { this._dataProvider.UpdateRecordChangers("Tabs", "TabID", tabId, createdBy, modifiedBy); - } - - // ReSharper disable UnusedMember.Local + } // ReSharper disable UnusedMember.Local private void UpdateTabPermissionChangers(int tabPermissionId, int createdBy, int modifiedBy) { this._dataProvider.UpdateRecordChangers("TabPermission", "TabPermissionID", tabPermissionId, createdBy, modifiedBy); @@ -1609,8 +1607,8 @@ private void UpdateTabUniqueId(int tabId, Guid uniqueId) private void UpdateModuleUniqueId(int tabModuleId, Guid uniqueId) { this._dataProvider.UpdateUniqueId("TabModules", "TabModuleID", tabModuleId, uniqueId); - } - + } + private void ProcessExportPages() { var selectedPages = this._exportDto.Pages; @@ -1625,18 +1623,18 @@ private void ProcessExportPages() var isAllIncluded = selectedPages.Any(p => p.TabId == -1 && p.CheckedState == TriCheckedState.CheckedWithAllChildren); - var allTabs = EntitiesController.Instance.GetPortalTabs( + var allTabs = EntitiesController.Instance.GetPortalTabs( portalId, this._exportDto.IncludeDeletions, this.IncludeSystem, toDate, fromDate) // ordered by TabID .OrderBy(tab => tab.TabPath).ToArray(); // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? allTabs.Length : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + var progressStep = 100.0 / allTabs.Length; this.CheckPoint.TotalItems = this.IncludeSystem || isAllIncluded @@ -1646,21 +1644,21 @@ private void ProcessExportPages() // Note: We assume no new tabs were added while running; otherwise, some tabs might get skipped. for (var index = 0; index < allTabs.Length; index++) { - if (this.CheckCancelled(this._exportImportJob)) - { - break; - } - + if (this.CheckCancelled(this._exportImportJob)) + { + break; + } + var otherPg = allTabs.ElementAt(index); - if (this._totals.LastProcessedId > index) - { - continue; - } - + if (this._totals.LastProcessedId > index) + { + continue; + } + if (this.IncludeSystem || isAllIncluded || IsTabIncluded(otherPg, allTabs, selectedPages)) { var tab = this._tabController.GetTab(otherPg.TabID, portalId); - + // Do not export tab which has never been published. if (tab.HasBeenPublished) { @@ -1685,17 +1683,17 @@ private void ProcessExportPages() this.ExportTabModuleSettings(exportPage, this._exportDto.IncludeDeletions, toDate, fromDate); this._totals.TotalTabs++; } - + this._totals.LastProcessedId = index; } this.CheckPoint.Progress += progressStep; this.CheckPoint.ProcessedItems++; this.CheckPoint.StageData = JsonConvert.SerializeObject(this._totals); - if (this.CheckPointStageCallback(this)) - { - break; - } + if (this.CheckPointStageCallback(this)) + { + break; + } } this.ReportExportTotals(); @@ -1705,60 +1703,60 @@ private void ProcessExportPages() private int ExportTabSettings(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { var tabSettings = EntitiesController.Instance.GetTabSettings(exportPage.TabId, toDate, fromDate); - if (tabSettings.Count > 0) - { - this.Repository.CreateItems(tabSettings, exportPage.Id); - } - + if (tabSettings.Count > 0) + { + this.Repository.CreateItems(tabSettings, exportPage.Id); + } + return tabSettings.Count; } private int ExportTabPermissions(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { - if (!this._exportDto.IncludePermissions) - { - return 0; - } - + if (!this._exportDto.IncludePermissions) + { + return 0; + } + var tabPermissions = EntitiesController.Instance.GetTabPermissions(exportPage.TabId, toDate, fromDate); - if (tabPermissions.Count > 0) - { - this.Repository.CreateItems(tabPermissions, exportPage.Id); - } - + if (tabPermissions.Count > 0) + { + this.Repository.CreateItems(tabPermissions, exportPage.Id); + } + return tabPermissions.Count; } private int ExportTabUrls(ExportTab exportPage, DateTime toDate, DateTime? fromDate) { var tabUrls = EntitiesController.Instance.GetTabUrls(exportPage.TabId, toDate, fromDate); - if (tabUrls.Count > 0) - { - this.Repository.CreateItems(tabUrls, exportPage.Id); - } - + if (tabUrls.Count > 0) + { + this.Repository.CreateItems(tabUrls, exportPage.Id); + } + return tabUrls.Count; } private int ExportTabModules(ExportTab exportPage, bool includeDeleted, DateTime toDate, DateTime? fromDate) { var tabModules = EntitiesController.Instance.GetTabModules(exportPage.TabId, includeDeleted, toDate, fromDate); - if (tabModules.Count > 0) - { - this.Repository.CreateItems(tabModules, exportPage.Id); - } - + if (tabModules.Count > 0) + { + this.Repository.CreateItems(tabModules, exportPage.Id); + } + return tabModules.Count; } private int ExportTabModuleSettings(ExportTab exportPage, bool includeDeleted, DateTime toDate, DateTime? fromDate) { var tabModuleSettings = EntitiesController.Instance.GetTabModuleSettings(exportPage.TabId, includeDeleted, toDate, fromDate); - if (tabModuleSettings.Count > 0) - { - this.Repository.CreateItems(tabModuleSettings, exportPage.Id); - } - + if (tabModuleSettings.Count > 0) + { + this.Repository.CreateItems(tabModuleSettings, exportPage.Id); + } + return tabModuleSettings.Count; } @@ -1808,13 +1806,13 @@ private int ExportModulePackage(ExportModule exportModule) var offset = Path.GetDirectoryName(filePath)?.Length + 1; 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), + this.Repository.CreateItem( + new ExportPackage + { + PackageName = package.Name, + Version = package.Version, + PackageType = package.PackageType, + PackageFileName = InstallerUtil.GetPackageBackupName(package), }, null); this._exportedModuleDefinitions.Add(exportModule.ModuleDefID); @@ -1827,36 +1825,36 @@ private int ExportModulePackage(ExportModule exportModule) } } } - + return 0; } private int ExportModuleSettings(ExportModule exportModule, DateTime toDate, DateTime? fromDate) { var moduleSettings = EntitiesController.Instance.GetModuleSettings(exportModule.ModuleID, toDate, fromDate); - if (moduleSettings.Count > 0) - { - this.Repository.CreateItems(moduleSettings, exportModule.Id); - } - + if (moduleSettings.Count > 0) + { + this.Repository.CreateItems(moduleSettings, exportModule.Id); + } + return moduleSettings.Count; } private int ExportModulePermissions(ExportModule exportModule, DateTime toDate, DateTime? fromDate) { var modulePermission = EntitiesController.Instance.GetModulePermissions(exportModule.ModuleID, toDate, fromDate); - if (modulePermission.Count > 0) - { - this.Repository.CreateItems(modulePermission, exportModule.Id); - } - + if (modulePermission.Count > 0) + { + this.Repository.CreateItems(modulePermission, exportModule.Id); + } + return modulePermission.Count; } // Note: until now there is no use of time range for content // ReSharper disable UnusedParameter.Local private int ExportPortableContent(ExportTab exportPage, ExportModule exportModule, DateTime toDate, DateTime? fromDat) - + // ReSharper enable UnusedParameter.Local { // check if module's contnt was exported before @@ -1874,7 +1872,7 @@ private int ExportPortableContent(ExportTab exportPage, ExportModule exportModul { try { - var businessController = Reflection.CreateObject( + var businessController = Reflection.CreateObject( module.DesktopModule.BusinessControllerClass, module.DesktopModule.BusinessControllerClass); var controller = businessController as IPortable; @@ -1905,7 +1903,7 @@ private int ExportPortableContent(ExportTab exportPage, ExportModule exportModul } } } - + return 0; } @@ -1955,7 +1953,7 @@ private ExportTab SaveExportPage(TabInfo tab) this.Repository.CreateItem(exportPage, null); this.Result.AddLogEntry("Exported page", tab.TabName + " (" + tab.TabPath + ")"); return exportPage; - } + } private void ReportExportTotals() { @@ -1999,46 +1997,46 @@ private int GetLocalStateId(int exportedStateId) { var exportWorkflowState = this.Repository.GetItem(item => item.StateID == exportedStateId); var stateId = exportWorkflowState?.LocalId ?? Null.NullInteger; - if (stateId <= 0) - { - return stateId; - } - + if (stateId <= 0) + { + return stateId; + } + var state = WorkflowStateManager.Instance.GetWorkflowState(stateId); - if (state == null) - { - return -1; - } - + if (state == null) + { + return -1; + } + var workflow = WorkflowManager.Instance.GetWorkflow(state.WorkflowID); - if (workflow == null) - { - return -1; - } - + if (workflow == null) + { + return -1; + } + return workflow.FirstState.StateID; } private bool IsTabPublished(TabInfo tab) { var stateId = tab.StateID; - if (stateId <= 0) - { - return true; - } - + if (stateId <= 0) + { + return true; + } + var state = WorkflowStateManager.Instance.GetWorkflowState(stateId); - if (state == null) - { - return true; - } - + if (state == null) + { + return true; + } + var workflow = WorkflowManager.Instance.GetWorkflow(state.WorkflowID); - if (workflow == null) - { - return true; - } - + if (workflow == null) + { + return true; + } + return workflow.LastState.StateID == stateId; } @@ -2104,7 +2102,7 @@ private bool IsParentTabPresentInExport(ExportTab exportedTab, IList } } } - + return isParentPresent; } @@ -2196,8 +2194,8 @@ private void AddToPartialImportedTabs(int localTabId, int exportTabParentId) { this._partialImportedTabs.Add(localTabId, exportTabParentId); } - } - + } + [JsonObject] private class ProgressTotals { @@ -2206,25 +2204,25 @@ private class ProgressTotals public int LastProcessedId { get; set; } public int TotalTabs { get; set; } - + public int TotalTabSettings { get; set; } - + public int TotalTabPermissions { get; set; } - + public int TotalTabUrls { get; set; } public int TotalModules { get; set; } - + public int TotalModulePermissions { get; set; } - + public int TotalModuleSettings { get; set; } - + public int TotalContents { get; set; } - + public int TotalPackages { get; set; } public int TotalTabModules { get; set; } - + public int TotalTabModuleSettings { get; set; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs index ee0701dbacb..3125e73eeb3 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/PortalExportService.cs @@ -34,16 +34,16 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (this.CheckPoint.Stage > 1) - { - return; - } - - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckPoint.Stage > 1) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + List portalLanguages = null; if (this.CheckPoint.Stage == 0) { @@ -68,36 +68,36 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) DataProvider.Instance().GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); this.CheckPoint.TotalItems += portalLanguages.Count; } - + this.CheckPointStageCallback(this); this.Repository.CreateItems(portalSettings); } - + this.Result.AddSummary("Exported Portal Settings", portalSettings.Count.ToString()); this.CheckPoint.Progress = 50; this.CheckPoint.ProcessedItems = portalSettings.Count; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } if (this.CheckPoint.Stage == 1) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - if (portalLanguages == null) - { + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (portalLanguages == null) + { portalLanguages = CBO.FillCollection(DataProvider.Instance() - .GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); - } - + .GetPortalLanguages(exportJob.PortalId, toDate, fromDate)); + } + this.Repository.CreateItems(portalLanguages); this.Result.AddSummary("Exported Portal Languages", portalLanguages.Count.ToString()); this.CheckPoint.Progress = 100; @@ -112,16 +112,16 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - - if (this.CheckPoint.Stage > 1) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (this.CheckPoint.Stage > 1) + { + return; + } + if (this.CheckPoint.Stage == 0) { var portalSettings = this.Repository.GetAllItems().ToList(); @@ -131,12 +131,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.Progress += 50; this.CheckPoint.Stage++; this.CheckPoint.ProcessedItems = portalSettings.Count; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } - + if (this.CheckPoint.Stage == 1) { var portalLanguages = this.Repository.GetAllItems().ToList(); @@ -148,7 +148,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.ProcessedItems += portalLanguages.Count; this.CheckPointStageCallback(this); } - + /* ProgressPercentage = 0; var portalLocalizations = Repository.GetAllItems().ToList(); @@ -171,11 +171,11 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt CBO.FillCollection(DataProvider.Instance().GetPortalSettings(portalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null)); foreach (var exportPortalSetting in portalSettings) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var existingPortalSetting = localPortalSettings.FirstOrDefault( t => @@ -198,7 +198,7 @@ private void ProcessPortalSettings(ExportImportJob importJob, ImportDto importDt throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - + if (isUpdate) { var modifiedBy = Util.GetUserIdByName(importJob, exportPortalSetting.LastModifiedByUserId, @@ -232,11 +232,11 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD var localLanguages = CBO.FillCollection(DotNetNuke.Data.DataProvider.Instance().GetLanguages()); foreach (var exportPortalLanguage in portalLanguages) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, exportPortalLanguage.CreatedByUserId, exportPortalLanguage.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, exportPortalLanguage.LastModifiedByUserId, exportPortalLanguage.LastModifiedByUserName); @@ -253,7 +253,7 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD Localization.SaveLanguage(locale); localLanguageId = locale.LanguageId; } - + var existingPortalLanguage = localPortalLanguages.FirstOrDefault( t => @@ -273,7 +273,7 @@ private void ProcessPortalLanguages(ExportImportJob importJob, ImportDto importD throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - + if (isUpdate) { DotNetNuke.Data.DataProvider.Instance() diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs index 24ee145f4a9..9a2cb62cbc8 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ProfilePropertiesService.cs @@ -27,37 +27,37 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (this.CheckCancelled(exportJob)) - { - return; - } - - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var profileProperties = CBO.FillCollection( DataProvider.Instance() .GetPropertyDefinitionsByPortal(exportJob.PortalId, exportDto.IncludeDeletions, toDate, fromDate)).ToList(); this.CheckPoint.Progress = 50; - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? profileProperties.Count : this.CheckPoint.TotalItems; this.CheckPointStageCallback(this); - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + this.Repository.CreateItems(profileProperties); this.Result.AddSummary("Exported Profile Properties", profileProperties.Count.ToString()); this.CheckPoint.Progress = 100; @@ -69,24 +69,24 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - + if (this.CheckPoint.Stage > 0) + { + return; + } + var profileProperties = this.Repository.GetAllItems().ToList(); - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? profileProperties.Count : this.CheckPoint.TotalItems; this.CheckPointStageCallback(this); foreach (var profileProperty in profileProperties) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var existingProfileProperty = CBO.FillObject(DotNetNuke.Data.DataProvider.Instance() .GetPropertyDefinitionByName(importJob.PortalId, profileProperty.PropertyName)); @@ -126,7 +126,7 @@ public override int GetImportTotal() return this.Repository.GetCount(); } - private static void ProcessCreateProfileProperty( + private static void ProcessCreateProfileProperty( ExportImportJob importJob, ExportProfileProperty profileProperty, int createdById) { @@ -143,7 +143,7 @@ private static void ProcessUpdateProfileProperty(ExportProfileProperty profilePr int modifiedById) { DotNetNuke.Data.DataProvider.Instance() - .UpdatePropertyDefinition( + .UpdatePropertyDefinition( existingProfileProperty.PropertyDefinitionId, profileProperty.DataType ?? Null.NullInteger, profileProperty.DefaultValue, profileProperty.PropertyCategory, profileProperty.PropertyName, diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs index 23687b9cdd9..d073a80e030 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/RolesExportService.cs @@ -28,20 +28,20 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); - if (this.CheckPoint.Stage > 2) - { - return; - } - + if (this.CheckPoint.Stage > 2) + { + return; + } + List roles = null; List roleSettings = null; if (this.CheckPoint.Stage == 0) { - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + var roleGroups = CBO.FillCollection( DataProvider.Instance().GetAllRoleGroups(exportJob.PortalId, toDate, fromDate)); @@ -55,7 +55,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); this.CheckPoint.TotalItems += roles.Count + roleSettings.Count; } - + this.CheckPointStageCallback(this); this.Repository.CreateItems(roleGroups); @@ -63,49 +63,49 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.ProcessedItems = roleGroups.Count; this.CheckPoint.Progress = 30; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } if (this.CheckPoint.Stage == 1) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - if (roles == null) - { + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (roles == null) + { roles = CBO.FillCollection( - DataProvider.Instance().GetAllRoles(exportJob.PortalId, toDate, fromDate)); - } - + DataProvider.Instance().GetAllRoles(exportJob.PortalId, toDate, fromDate)); + } + this.Repository.CreateItems(roles); this.Result.AddSummary("Exported Roles", roles.Count.ToString()); this.CheckPoint.Progress = 80; this.CheckPoint.ProcessedItems += roles.Count; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } if (this.CheckPoint.Stage == 2) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - if (roleSettings == null) - { + if (this.CheckCancelled(exportJob)) + { + return; + } + + if (roleSettings == null) + { roleSettings = CBO.FillCollection( - DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); - } - + DataProvider.Instance().GetAllRoleSettings(exportJob.PortalId, toDate, fromDate)); + } + this.Repository.CreateItems(roleSettings); this.Result.AddSummary("Exported Role Settings", roleSettings.Count.ToString()); this.CheckPoint.Progress = 100; @@ -118,17 +118,17 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckPoint.Stage > 2) - { - return; - } - - if (this.CheckCancelled(importJob)) - { - return; - } - - // Update the total items count in the check points. This should be updated only once. + if (this.CheckPoint.Stage > 2) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; this.CheckPointStageCallback(this); @@ -141,17 +141,17 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.Progress = 40; this.CheckPoint.ProcessedItems = otherRoleGroups.Count; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } + } + + if (this.CheckCancelled(importJob)) + { + return; } - if (this.CheckCancelled(importJob)) - { - return; - } - var otherRoles = this.Repository.GetAllItems().ToList(); if (this.CheckPoint.Stage == 1) { @@ -161,19 +161,19 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.Progress = 50; this.CheckPoint.ProcessedItems += otherRoles.Count; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } if (this.CheckPoint.Stage == 2) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var otherRoleSettings = this.Repository.GetAllItems().ToList(); this.ProcessRoleSettings(importJob, importDto, otherRoles, otherRoleSettings); this.Repository.UpdateItems(otherRoleSettings); @@ -212,6 +212,16 @@ private static void RefreshRecordsUserIds(IEnumerable roleItems) } } + private static void RefreshRecordsUserIds(IEnumerable settingItems) + { + var provider = DataProvider.Instance(); + foreach (var item in settingItems) + { + provider.UpdateSettingRecordChangers("RoleSettings", "RoleID", + item.RoleId, item.Name, item.CreatedBy, item.ModifiedBy); + } + } + private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, IEnumerable otherRoleGroups) { @@ -220,11 +230,11 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, var localRoleGroups = CBO.FillCollection(DataProvider.Instance().GetAllRoleGroups(portalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null)); foreach (var other in otherRoleGroups) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var local = localRoleGroups.FirstOrDefault(t => t.RoleGroupName == other.RoleGroupName); @@ -265,11 +275,11 @@ private void ProcessRoleGroups(ExportImportJob importJob, ImportDto importDto, this.Result.AddLogEntry("Added role group", other.RoleGroupName); } } - - if (changedGroups.Count > 0) - { - RefreshRecordsUserIds(changedGroups); - } + + if (changedGroups.Count > 0) + { + RefreshRecordsUserIds(changedGroups); + } } private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, @@ -279,11 +289,11 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, var portalId = importJob.PortalId; foreach (var other in otherRoles) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var localRoleInfo = RoleController.Instance.GetRoleByName(portalId, other.RoleName); @@ -321,11 +331,11 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, roleItems.Add(new RoleItem(localRoleInfo.RoleID, createdBy, modifiedBy)); // do not assign existing users to the roles automatically - if (other.AutoAssignment) - { - DataProvider.Instance().SetRoleAutoAssign(localRoleInfo.RoleID); - } - + if (other.AutoAssignment) + { + DataProvider.Instance().SetRoleAutoAssign(localRoleInfo.RoleID); + } + RoleController.Instance.ClearRoleCache(localRoleInfo.RoleID); this.Result.AddLogEntry("Updated role", other.RoleName); break; @@ -369,10 +379,10 @@ private void ProcessRoles(ExportImportJob importJob, ImportDto importDto, } // set created/updated for any added/modified item - if (roleItems.Count > 0) - { - RefreshRecordsUserIds(roleItems); - } + if (roleItems.Count > 0) + { + RefreshRecordsUserIds(roleItems); + } } private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, @@ -382,25 +392,25 @@ private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, var portalId = importJob.PortalId; foreach (var other in otherRoleSettings) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var createdBy = Util.GetUserIdByName(importJob, other.CreatedByUserID, other.CreatedByUserName); var modifiedBy = Util.GetUserIdByName(importJob, other.LastModifiedByUserID, other.LastModifiedByUserName); var otherRole = otherRoles.FirstOrDefault(r => r.RoleID == other.RoleID); - if (otherRole == null || !otherRole.LocalId.HasValue) - { - continue; - } - + if (otherRole == null || !otherRole.LocalId.HasValue) + { + continue; + } + var localRoleInfo = RoleController.Instance.GetRoleById(portalId, otherRole.LocalId.Value); - if (localRoleInfo == null) - { - continue; - } - + if (localRoleInfo == null) + { + continue; + } + switch (importDto.CollisionResolution) { case CollisionResolution.Ignore: @@ -415,36 +425,26 @@ private void ProcessRoleSettings(ExportImportJob importJob, ImportDto importDto, localRoleInfo.Settings[other.SettingName] = other.SettingValue; RoleController.Instance.UpdateRoleSettings(localRoleInfo, false); this.Result.AddLogEntry("Updated role setting", other.SettingName); - + // No need to clear cache as the caller will do it one time at end } else { this.Result.AddLogEntry("Ignored role setting", other.SettingName); } - + break; default: throw new ArgumentOutOfRangeException(importDto.CollisionResolution.ToString()); } } - if (changedSettings.Count > 0) - { - RefreshRecordsUserIds(changedSettings); - } - - RoleController.Instance.ClearRoleCache(importJob.PortalId); - } - - private static void RefreshRecordsUserIds(IEnumerable settingItems) - { - var provider = DataProvider.Instance(); - foreach (var item in settingItems) + if (changedSettings.Count > 0) { - provider.UpdateSettingRecordChangers("RoleSettings", "RoleID", - item.RoleId, item.Name, item.CreatedBy, item.ModifiedBy); + RefreshRecordsUserIds(changedSettings); } + + RoleController.Instance.ClearRoleCache(importJob.PortalId); } private struct RoleGroupItem @@ -455,11 +455,11 @@ public RoleGroupItem(int roleGroupId, int createdBy, int modifiedBy) this.CreatedBy = createdBy; this.ModifiedBy = modifiedBy; } - + public int RoleGroupId { get; } - + public int CreatedBy { get; } - + public int ModifiedBy { get; } } @@ -471,11 +471,11 @@ public RoleItem(int roleId, int createdBy, int modifiedBy) this.CreatedBy = createdBy; this.ModifiedBy = modifiedBy; } - + public int RoleId { get; } - + public int CreatedBy { get; } - + public int ModifiedBy { get; } } @@ -488,13 +488,13 @@ 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/ThemesExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs index a80fbda0fec..d1d352f9735 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/ThemesExportService.cs @@ -35,17 +35,17 @@ public class ThemesExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckCancelled(exportJob)) - { - return; - } - - // Skip the export if all the folders have been processed already. - if (this.CheckPoint.Stage >= 1) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + + // Skip the export if all the folders have been processed already. + if (this.CheckPoint.Stage >= 1) + { + return; + } + this._exportImportJob = exportJob; this._portalSettings = new PortalSettings(exportJob.PortalId); @@ -65,11 +65,11 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalThemes : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + using (var archive = CompressionUtil.OpenCreate(packagesZipFile)) { foreach (var theme in exportThemes) @@ -83,19 +83,19 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) var folderOffset = Path.Combine(Globals.ApplicationMapPath, "Portals").Length + 1; CompressionUtil.AddFileToArchive(archive, file, folderOffset); } - + totalThemesExported += 1; } this.CheckPoint.ProcessedItems++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalThemes; currentIndex++; - + // After every 10 items, call the checkpoint stage. This is to avoid too many frequent updates to DB. - if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) - { - return; - } + if (currentIndex % 10 == 0 && this.CheckPointStageCallback(this)) + { + return; + } } } @@ -113,17 +113,17 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - - // Skip the export if all the templates have been processed already. - if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + + // Skip the export if all the templates have been processed already. + if (this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed) + { + return; + } + this._exportImportJob = importJob; var packageZipFile = $"{Globals.ApplicationMapPath}{Constants.ExportFolder}{this._exportImportJob.Directory.TrimEnd('\\', '/')}\\{Constants.ExportZipThemes}"; @@ -136,11 +136,11 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this._importCount = exporeFiles.Length; this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? exporeFiles.Length : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + if (this.CheckPoint.Stage == 0) { try @@ -152,7 +152,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var checkFolder = file.Replace(tempFolder + "\\", string.Empty).Split('\\')[0]; var relativePath = file.Substring((tempFolder + "\\" + checkFolder + "\\").Length); string targetPath; - + if (checkFolder == "_default") { targetPath = Path.Combine(Globals.HostMapPath, relativePath); @@ -189,7 +189,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) Logger.Error(ex); } } - + this.CheckPoint.Stage++; this.CheckPoint.Completed = true; } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs index b7bd39f93a6..643aca9f9b6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersDataExportService.cs @@ -50,7 +50,7 @@ public class UsersDataExportService : BasePortableService new Tuple("ExtendedVisibility", typeof(string)), new Tuple("IsSuperUser", typeof(bool)), }; - + public override string Category => Constants.Category_UsersData; public override string ParentCategory => Constants.Category_Users; @@ -64,17 +64,17 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.TotalItems = 0; this.CheckPoint.ProcessedItems = 0; this.CheckPointStageCallback(this); - + // No implementation required in export users child as everything is exported in parent service. } public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var pageIndex = 0; const int pageSize = Constants.DefaultPageSize; var totalUserRolesImported = 0; @@ -87,35 +87,35 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPointStageCallback(this); return; } - + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); - + // Skip the import if all the users has been processed already. - if (this.CheckPoint.Stage >= totalPages) - { - return; - } - + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + pageIndex = this.CheckPoint.Stage; var totalUsersToBeProcessed = totalUsers - (pageIndex * pageSize); // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + var includeProfile = importDto.ExportDto.IncludeProperfileProperties; try { this.Repository.RebuildIndex(x => x.ReferenceId); - if (includeProfile) - { - this.Repository.RebuildIndex(x => x.ReferenceId); - } - + if (includeProfile) + { + this.Repository.RebuildIndex(x => x.ReferenceId); + } + var portalId = importJob.PortalId; using (var tableUserProfile = new DataTable("UserProfile")) using (var tableUserRoles = new DataTable("UserRoles")) @@ -126,11 +126,11 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var dataProvider = DotNetNuke.Data.DataProvider.Instance(); while (totalProcessed < totalUsersToBeProcessed) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var users = this.Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); var tempUserRolesCount = 0; var tempUserProfileCount = 0; @@ -138,12 +138,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { foreach (var user in users) { - if (this.CheckCancelled(importJob)) - { - return; - } - - // Find the correct userId from the system which was added/updated by UserExportService. + if (this.CheckCancelled(importJob)) + { + return; + } + + // Find the correct userId from the system which was added/updated by UserExportService. var userId = UserController.GetUserByName(user.Username)?.UserID; if (userId != null) { @@ -151,16 +151,16 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) foreach (var userRole in userRoles) { var roleId = Util.GetRoleIdByName(importJob.PortalId, userRole.RoleId, userRole.RoleName); - if (roleId == null) - { - continue; - } - - if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) - { - continue; - } - + if (roleId == null) + { + continue; + } + + if (!(roleId > Convert.ToInt32(Globals.glbRoleNothing))) + { + continue; + } + var userRoleRow = tableUserRoles.NewRow(); userRoleRow["PortalId"] = portalId; userRoleRow["UserId"] = userId; @@ -176,21 +176,21 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) tableUserRoles.Rows.Add(userRoleRow); tempUserRolesCount++; } - + if (includeProfile) { var userProfiles = this.Repository.GetRelatedItems(user.Id).ToList(); foreach (var userProfile in userProfiles) { - var profileDefinitionId = Util.GetProfilePropertyId( + var profileDefinitionId = Util.GetProfilePropertyId( importJob.PortalId, userProfile.PropertyDefinitionId, userProfile.PropertyName); - if (profileDefinitionId == null || profileDefinitionId == -1) - { - continue; - } - + if (profileDefinitionId == null || profileDefinitionId == -1) + { + continue; + } + var value = userProfile.PropertyValue; if (userProfile.PropertyName.Equals("photo", StringComparison.InvariantCultureIgnoreCase) && (value = this.GetUserPhotoId(portalId, value, user)) == null) { @@ -212,9 +212,9 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } } - + var overwrite = importDto.CollisionResolution == CollisionResolution.Overwrite; - + // Bulk insert the data in DB DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUserRolesBulk", "@DataTable", tableUserRoles, new Dictionary { { "Overwrite", overwrite } }); @@ -237,20 +237,20 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { this.Result.AddLogEntry($"Importing Users Data from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } - + tableUserRoles.Rows.Clear(); tableUserProfile.Rows.Clear(); pageIndex++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; this.CheckPoint.Stage++; this.CheckPoint.StageData = null; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } } - + this.CheckPoint.Completed = true; this.CheckPoint.Progress = 100; } @@ -274,28 +274,28 @@ private string GetUserPhotoId(int portalId, string importFileId, ExportUser user { int profilePictureId; if (string.IsNullOrEmpty(importFileId) || - !int.TryParse(importFileId, out profilePictureId)) - { - return null; - } - + !int.TryParse(importFileId, out profilePictureId)) + { + return null; + } + var files = FolderManager.Instance.GetFiles( FolderManager.Instance.GetUserFolder( UserController.GetUserByName(portalId, user.Username))) .ToList(); - if (!files.Any()) - { - return null; - } - + if (!files.Any()) + { + return null; + } + var importUserFolder = this.Repository.GetItem(x => x.UserId == user.UserId); - if (importUserFolder == null) - { - return null; - } - + if (importUserFolder == null) + { + return null; + } + { var profilePicture = this.Repository.GetRelatedItems(importUserFolder.Id) @@ -309,7 +309,7 @@ private string GetUserPhotoId(int portalId, string importFileId, ExportUser user .FileId); } } - + return null; } } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs index 0c04c532b5a..80708f0921a 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/UsersExportService.cs @@ -61,7 +61,7 @@ public class UsersExportService : BasePortableService new Tuple("AuthenticationType", typeof(string)), new Tuple("AuthenticationToken", typeof(string)), }; - + public override string Category => Constants.Category_Users; public override string ParentCategory => null; @@ -70,11 +70,11 @@ public class UsersExportService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDateUtc = exportDto.FromDateUtc; var toDateUtc = exportDto.ToDateUtc; @@ -95,39 +95,39 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPointStageCallback(this); return; } - + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); // Skip the export if all the users has been processed already. - if (this.CheckPoint.Stage >= totalPages) - { - return; - } - - // Check if there is any pending stage or partially processed data. + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + + // Check if there is any pending stage or partially processed data. if (this.CheckPoint.Stage > 0) { pageIndex = this.CheckPoint.Stage; } - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; this.CheckPoint.ProcessedItems = this.CheckPoint.Stage * pageSize; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + var includeProfile = exportDto.IncludeProperfileProperties; try { while (pageIndex < totalPages) { - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckCancelled(exportJob)) + { + return; + } + var exportUsersList = new List(); var exportAspnetUserList = new List(); var exportAspnetMembershipList = new List(); @@ -153,7 +153,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { CBO.FillCollection(reader, exportUserProfileList, false); } - + reader.NextResult(); CBO.FillCollection(reader, exportUserPortalList, false); @@ -193,7 +193,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.Repository.CreateItems(exportUserProfileList, null); totalProfilesExported += exportUserProfileList.Count; } - + exportUserPortalList.ForEach( x => { @@ -224,29 +224,29 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { this.Result.AddLogEntry($"Exporting Users from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } - + this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } - - // Rebuild the indexes in the exported database. + if (this.CheckPointStageCallback(this)) + { + return; + } + + // Rebuild the indexes in the exported database. this.Repository.RebuildIndex(x => x.Id, true); this.Repository.RebuildIndex(x => x.ReferenceId); this.Repository.RebuildIndex(x => x.ReferenceId); this.Repository.RebuildIndex(x => x.ReferenceId); this.Repository.RebuildIndex(x => x.ReferenceId); this.Repository.RebuildIndex(x => x.ReferenceId); - if (includeProfile) - { - this.Repository.RebuildIndex(x => x.ReferenceId); - } - + if (includeProfile) + { + this.Repository.RebuildIndex(x => x.ReferenceId); + } + pageIndex++; } - + this.CheckPoint.Completed = true; this.CheckPoint.Progress = 100; } @@ -260,7 +260,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { this.Result.AddSummary("Exported User Profiles", totalProfilesExported.ToString()); } - + this.Result.AddSummary("Exported User Authentication", totalAuthenticationExported.ToString()); this.Result.AddSummary("Exported Aspnet User", totalAspnetUserExported.ToString()); this.Result.AddSummary("Exported Aspnet Membership", totalAspnetMembershipExported.ToString()); @@ -269,11 +269,11 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + const int pageSize = Constants.DefaultPageSize; var totalUsersImported = 0; var totalPortalsImported = 0; @@ -287,26 +287,26 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPointStageCallback(this); return; } - + var totalPages = Util.CalculateTotalPages(totalUsers, pageSize); - + // Skip the import if all the users has been processed already. - if (this.CheckPoint.Stage >= totalPages) - { - return; - } - + if (this.CheckPoint.Stage >= totalPages) + { + return; + } + var pageIndex = this.CheckPoint.Stage; var totalUsersToBeProcessed = totalUsers - (pageIndex * pageSize); - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? totalUsers : this.CheckPoint.TotalItems; - if (this.CheckPointStageCallback(this)) - { - return; - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + try { this.Repository.RebuildIndex(x => x.Id, true); @@ -323,11 +323,11 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) UsersDatasetColumns.Select(column => new DataColumn(column.Item1, column.Item2)).ToArray()); while (totalUsersImported < totalUsersToBeProcessed) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var users = this.Repository.GetAllItems(null, true, pageIndex * pageSize, pageSize).ToList(); var tempAspUserCount = 0; @@ -338,16 +338,16 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { foreach (var user in users) { - if (this.CheckCancelled(importJob)) - { - return; - } - + if (this.CheckCancelled(importJob)) + { + return; + } + var row = table.NewRow(); var userPortal = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); var userAuthentication = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); - + // Aspnet Users and Membership var aspNetUser = this.Repository.GetRelatedItems(user.Id).FirstOrDefault(); var aspnetMembership = aspNetUser != null @@ -384,7 +384,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) row["RefreshRoles"] = DBNull.Value; row["IsDeleted"] = DBNull.Value; } - + if (userAuthentication != null) { tempUserAuthenticationCount += 1; @@ -441,9 +441,9 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) table.Rows.Add(row); } - + var overwrite = importDto.CollisionResolution == CollisionResolution.Overwrite; - + // Bulk insert the data in DB DotNetNuke.Data.DataProvider.Instance() .BulkInsert("ExportImport_AddUpdateUsersBulk", "@DataTable", table, new Dictionary { { "Overwrite", overwrite } }); @@ -458,19 +458,19 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { this.Result.AddLogEntry($"Importing Users from {pageIndex * pageSize} to {(pageIndex * pageSize) + pageSize} exception", ex.Message, ReportLevel.Error); } - + table.Rows.Clear(); pageIndex++; this.CheckPoint.Progress = this.CheckPoint.ProcessedItems * 100.0 / totalUsers; this.CheckPoint.Stage++; this.CheckPoint.StageData = null; - if (this.CheckPointStageCallback(this)) - { - return; - } + if (this.CheckPointStageCallback(this)) + { + return; + } } } - + this.CheckPoint.Completed = true; this.CheckPoint.Progress = 100; } @@ -493,11 +493,11 @@ public override int GetImportTotal() private Guid GetApplicationId() { using (var db = - new PetaPocoDataContext( + new PetaPocoDataContext( DotNetNuke.Data.DataProvider.Instance().Settings["connectionStringName"], "aspnet_")) { - return db.ExecuteScalar( + return db.ExecuteScalar( CommandType.Text, "SELECT TOP 1 ApplicationId FROM aspnet_Applications"); } diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs index 44f9cb0c2f6..9e38d54f3b6 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/VocabularyService.cs @@ -28,16 +28,16 @@ public class VocabularyService : BasePortableService public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); List vocabularyTypes = null; @@ -49,7 +49,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) if (taxonomyTerms.Count > 0 || taxonomyVocabularies.Count > 0) { var scopeTypes = CBO.FillCollection(DataProvider.Instance().GetAllScopeTypes()); - + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? scopeTypes.Count : this.CheckPoint.TotalItems; if (this.CheckPoint.TotalItems == scopeTypes.Count) @@ -59,31 +59,31 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); this.CheckPoint.TotalItems += taxonomyTerms.Count + taxonomyVocabularies.Count; } - + this.CheckPointStageCallback(this); this.Repository.CreateItems(scopeTypes); - + // Result.AddSummary("Exported Taxonomy Scopes", scopeTypes.Count.ToString()); -- not imported so don't show // CheckPoint.ProcessedItems += scopeTypes.Count; } - + this.CheckPoint.Progress = 25; - if (taxonomyVocabularies == null) - { - taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); - } - + if (taxonomyVocabularies == null) + { + taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); + } + if (taxonomyTerms.Count > 0 || taxonomyVocabularies.Count > 0) { - if (vocabularyTypes == null) - { - vocabularyTypes = CBO.FillCollection(DataProvider.Instance().GetAllVocabularyTypes()); - } - + if (vocabularyTypes == null) + { + vocabularyTypes = CBO.FillCollection(DataProvider.Instance().GetAllVocabularyTypes()); + } + this.Repository.CreateItems(vocabularyTypes); - + // Result.AddSummary("Exported Vocabulary Types", vocabularyTypes.Count.ToString()); -- not imported so don't show // CheckPoint.ProcessedItems += vocabularyTypes.Count; } @@ -93,16 +93,16 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.Progress = 75; this.CheckPoint.ProcessedItems += taxonomyTerms.Count; this.CheckPoint.Stage++; - if (this.CheckPointStageCallback(this)) - { - return; - } - - if (taxonomyVocabularies == null) - { - taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); - } - + if (this.CheckPointStageCallback(this)) + { + return; + } + + if (taxonomyVocabularies == null) + { + taxonomyVocabularies = GetTaxonomyVocabularies(exportDto.PortalId, toDate, fromDate); + } + this.Repository.CreateItems(taxonomyVocabularies); this.Result.AddSummary("Exported Terms", taxonomyVocabularies.Count.ToString()); this.CheckPoint.Progress = 100; @@ -115,22 +115,22 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) public override void ImportData(ExportImportJob importJob, ImportDto importDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(importJob)) - { - return; - } - - // Update the total items count in the check points. This should be updated only once. + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(importJob)) + { + return; + } + + // Update the total items count in the check points. This should be updated only once. this.CheckPoint.TotalItems = this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? this.GetImportTotal() : this.CheckPoint.TotalItems; if (this.CheckPoint.Stage == 0) { var otherScopeTypes = this.Repository.GetAllItems().ToList(); - + // the table Taxonomy_ScopeTypes is used for lookup only and never changed/updated in the database // CheckPoint.Progress = 10; @@ -233,18 +233,18 @@ private void ProcessVocabularies(ExportImportJob importJob, ImportDto importDto, changed = true; } } - - if (changed) - { - DataCache.ClearCache(DataCache.VocabularyCacheKey); - } + + if (changed) + { + DataCache.ClearCache(DataCache.VocabularyCacheKey); + } } private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto, IList otherVocabularies, IList otherTaxonomyTerms) { var dataService = Util.GetDataService(); - + // var vocabularyController = new VocabularyController(); var localTaxonomyTerms = GetTaxonomyTerms(importDto.PortalId, DateUtils.GetDatabaseUtcTime().AddYears(1), null); foreach (var other in otherTaxonomyTerms) @@ -284,7 +284,7 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto { dataService.UpdateSimpleTerm(term, modifiedBy); } - + DataCache.ClearCache(string.Format(DataCache.TermCacheKey, term.TermId)); this.Result.AddLogEntry("Updated taxonomy", other.Name); break; @@ -302,7 +302,7 @@ private void ProcessTaxonomyTerms(ExportImportJob importJob, ImportDto importDto ParentTermId = parent?.LocalId, Weight = other.Weight, }; - + other.LocalId = isHierarchical ? dataService.AddHeirarchicalTerm(term, createdBy) : dataService.AddSimpleTerm(term, createdBy); diff --git a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs index b50003b4b17..2f5dab2a003 100644 --- a/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs +++ b/DNN Platform/Modules/DnnExportImport/Components/Services/WorkflowsExportService.cs @@ -32,20 +32,20 @@ public class WorkflowsExportService : BasePortableService public override int GetImportTotal() { return this.Repository.GetCount() + this.Repository.GetCount(); - } - + } + public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) { - if (this.CheckPoint.Stage > 0) - { - return; - } - - if (this.CheckCancelled(exportJob)) - { - return; - } - + if (this.CheckPoint.Stage > 0) + { + return; + } + + if (this.CheckCancelled(exportJob)) + { + return; + } + var fromDate = (exportDto.FromDateUtc ?? Constants.MinDbTime).ToLocalTime(); var toDate = exportDto.ToDateUtc.ToLocalTime(); @@ -82,7 +82,7 @@ public override void ExportData(ExportImportJob exportJob, ExportDto exportDto) this.CheckPoint.StageData = null; this.CheckPointStageCallback(this); } - + public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (this.CheckCancelled(importJob) || this.CheckPoint.Stage >= 1 || this.CheckPoint.Completed || this.CheckPointStageCallback(this)) @@ -96,7 +96,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) var importWorkflows = this.Repository.GetAllItems().ToList(); var existWorkflows = workflowManager.GetWorkflows(portalId).ToList(); var defaultTabWorkflowId = importWorkflows.FirstOrDefault(w => w.IsDefault)?.WorkflowID ?? 1; - this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? importWorkflows.Count : this.CheckPoint.TotalItems; + this.CheckPoint.TotalItems = this.CheckPoint.TotalItems <= 0 ? importWorkflows.Count : this.CheckPoint.TotalItems; foreach (var importWorkflow in importWorkflows) { var workflow = existWorkflows.FirstOrDefault(w => w.WorkflowName == importWorkflow.WorkflowName); @@ -133,7 +133,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } - importWorkflow.LocalId = workflow.WorkflowID; + importWorkflow.LocalId = workflow.WorkflowID; var importStates = this.Repository.GetRelatedItems(importWorkflow.Id).ToList(); foreach (var importState in importStates) { @@ -164,8 +164,8 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) WorkflowStateManager.Instance.AddWorkflowState(workflowState); this.Result.AddLogEntry("Added workflow state", workflowState.StateID.ToString()); } - - importState.LocalId = workflowState.StateID; + + importState.LocalId = workflowState.StateID; if (!workflowState.IsSystem) { var importPermissions = this.Repository.GetRelatedItems(importState.Id).ToList(); @@ -193,12 +193,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (userId == null) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Couldn't add tab permission; User is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } - + permission.UserID = userId.Value; } @@ -206,12 +206,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) { if (roleId == null) { - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Couldn't add tab permission; Role is undefined!", $"{importPermission.PermissionKey} - {importPermission.PermissionID}", ReportLevel.Warn); continue; } - + permission.RoleID = roleId.Value; } @@ -222,12 +222,12 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) x => x.PermissionCode == importPermission.PermissionCode && x.PermissionKey == importPermission.PermissionKey && x.PermissionName.Equals(importPermission.PermissionName, StringComparison.InvariantCultureIgnoreCase) && x.RoleID == roleId && x.UserID == userId); - + if (local == null) { workflowStateManager.AddWorkflowStatePermission(permission, -1); importPermission.LocalId = permission.WorkflowStatePermissionID; - this.Result.AddLogEntry( + this.Result.AddLogEntry( "Added workflow state permission", permission.WorkflowStatePermissionID.ToString()); } @@ -242,15 +242,15 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) } } } - } - } - + } + } + this.Repository.UpdateItems(importStates); this.Result.AddSummary("Imported Workflow", importWorkflows.Count.ToString()); this.CheckPoint.ProcessedItems++; this.CheckPointStageCallback(this); // no need to return; very small amount of data processed - } - + } + this.Repository.UpdateItems(importWorkflows); this.CheckPoint.Stage++; @@ -259,7 +259,7 @@ public override void ImportData(ExportImportJob importJob, ImportDto importDto) this.CheckPoint.TotalItems = importWorkflows.Count; this.CheckPoint.ProcessedItems = importWorkflows.Count; this.CheckPointStageCallback(this); - } + } private static List GetWorkflows(int portalId, bool includeDeletions) { @@ -278,6 +278,6 @@ private static List GetWorkflowStatePermissions( { return CBO.FillCollection( DataProvider.Instance().GetAllWorkflowStatePermissions(stateId, toDate, fromDate)); - } + } } } diff --git a/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs b/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs index 5aa56b4ba78..20ace3e12c9 100644 --- a/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs +++ b/DNN Platform/Modules/DnnExportImport/Services/ExportImportController.cs @@ -39,7 +39,7 @@ public HttpResponseMessage Import(ImportDto importDto) var jobId = controller.QueueOperation(this.PortalSettings.UserId, importDto); return this.Request.CreateResponse(HttpStatusCode.OK, new { jobId }); } - + return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, message); } @@ -106,16 +106,16 @@ public HttpResponseMessage LastJobTime(int portal, JobType jobType) return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } - if (portal < 0) - { - return this.Request.CreateErrorResponse( + if (portal < 0) + { + return this.Request.CreateErrorResponse( HttpStatusCode.BadRequest, - Localization.GetString("InvalidPortal", Constants.SharedResources)); - } - + Localization.GetString("InvalidPortal", Constants.SharedResources)); + } + var controller = new BaseController(); var lastTime = controller.GetLastJobTime(portal, jobType); - return this.Request.CreateResponse( + return this.Request.CreateResponse( HttpStatusCode.OK, new { lastTime = Util.GetDateTimeString(lastTime) }); } @@ -129,7 +129,7 @@ public HttpResponseMessage AllJobs(int portal, int? pageSize = 10, int? pageInde var error = Localization.GetString("NotPortalAdmin", Constants.SharedResources); return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, error); } - + var controller = new BaseController(); var jobs = controller.GetAllJobs(portal, this.PortalSettings.PortalId, pageSize, pageIndex, jobType, keywords); jobs?.ConvertToLocal(this.UserInfo); @@ -144,7 +144,7 @@ public HttpResponseMessage JobDetails(int jobId) job?.ConvertToLocal(this.UserInfo); return job != null ? this.Request.CreateResponse(HttpStatusCode.OK, job) - : this.Request.CreateResponse( + : this.Request.CreateResponse( HttpStatusCode.BadRequest, new { message = Localization.GetString("JobNotExist", Constants.SharedResources) }); } diff --git a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs index 4dfb62f5e4b..9c58951cfbe 100644 --- a/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs +++ b/DNN Platform/Modules/DnnExportImport/Services/ServiceRouteMapper.cs @@ -10,7 +10,7 @@ public class ServiceRouteMapper : IServiceRouteMapper { public void RegisterRoutes(IMapRoute routeManager) { - routeManager.MapHttpRoute( + routeManager.MapHttpRoute( "SiteExportImport", "default", "{controller}/{action}", diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs index 2be58dbf294..d5568ccf4d0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFile.cs @@ -9,17 +9,17 @@ namespace Dnn.ExportImport.Dto.Assets public class ExportFile : BasicExportImportDto { public int FileId { get; set; } - + public string FileName { get; set; } - + public string Extension { get; set; } - + public int Size { get; set; } - + public int? Width { get; set; } - + public int? Height { get; set; } - + public string ContentType { get; set; } public int FolderId { get; set; } @@ -31,17 +31,17 @@ public class ExportFile : BasicExportImportDto public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } - + public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } public Guid UniqueId { get; set; } - + public Guid VersionGuid { get; set; } public string Sha1Hash { get; set; } @@ -49,21 +49,21 @@ public class ExportFile : BasicExportImportDto public DateTime LastModificationTime { get; set; } public string Title { get; set; } - + public DateTime StartDate { get; set; } - + public bool EnablePublishPeriod { get; set; } - + public DateTime? EndDate { get; set; } - + public int PublishedVersion { get; set; } public int? ContentItemId { get; set; } public bool HasBeenPublished { get; set; } - + public string Description { get; set; } - + public int StorageLocation { get; set; } public bool IsCached { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs index c5051e53eae..a286e2730a8 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolder.cs @@ -11,31 +11,31 @@ public class ExportFolder : BasicExportImportDto public int FolderId { get; set; } public string FolderPath { get; set; } - + public int StorageLocation { get; set; } - + public bool IsProtected { get; set; } - + public bool IsCached { get; set; } - + public DateTime? LastUpdated { get; set; } public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public Guid UniqueId { get; set; } - + public Guid VersionGuid { get; set; } - + public int FolderMappingId { get; set; } public string FolderMappingName { get; set; } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs index 6647498e5b0..019496e0bcc 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderMapping.cs @@ -11,21 +11,21 @@ public class ExportFolderMapping : BasicExportImportDto public int FolderMappingId { get; set; } public string MappingName { get; set; } - + public string FolderProviderType { get; set; } - + public int? Priority { get; set; } public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs index ea8e48ea577..ec7cceda3a6 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Assets/ExportFolderPermission.cs @@ -39,13 +39,13 @@ public class ExportFolderPermission : BasicExportImportDto public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs index d3b285c7201..f6d138d9c1a 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/PageTemplates/ExportPageTemplate.cs @@ -7,6 +7,5 @@ namespace Dnn.ExportImport.Dto.PageTemplates using Dnn.ExportImport.Dto.Assets; public class ExportPageTemplate : ExportFile - { - } + {} } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs index 1c3489239fc..ac4d6974392 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModule.cs @@ -10,39 +10,39 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportModule : BasicExportImportDto { public int ModuleID { get; set; } - + public int ModuleDefID { get; set; } - + public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName - + public bool AllTabs { get; set; } - + public bool IsDeleted { get; set; } - + public bool? InheritViewPermissions { get; set; } - + public DateTime? StartDate { get; set; } - + public DateTime? EndDate { get; set; } - + public DateTime? LastContentModifiedOnDate { get; set; } - + public int? ContentItemID { get; set; } - + public bool IsShareable { get; set; } - + public bool IsShareableViewOnly { get; set; } public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs index 4bbaab24a7c..becee3951f3 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleContent.cs @@ -7,11 +7,11 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportModuleContent : BasicExportImportDto { public int ModuleID { get; set; } - + public int ModuleDefID { get; set; } - + public bool IsRestored { get; set; } - + public string XmlContent { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs index 9499e866cb7..f5f8b8fecdc 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModulePermission.cs @@ -10,37 +10,37 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportModulePermission : BasicExportImportDto { public int ModulePermissionID { get; set; } - + public int ModuleID { get; set; } - + public int PermissionID { get; set; } - + public string PermissionCode { get; set; } - + public string PermissionKey { get; set; } - + public string PermissionName { get; set; } - + public bool AllowAccess { get; set; } - + public int? RoleID { get; set; } - + public string RoleName { get; set; } - + public int? UserID { get; set; } - + public string Username { get; set; } public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs index 73b8e990fc7..d4f69252a09 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportModuleSetting.cs @@ -10,21 +10,21 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportModuleSetting : BasicExportImportDto { public int ModuleID { get; set; } - + public string SettingName { get; set; } - + public string SettingValue { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs index 5474133b3b5..8f745f98af3 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTab.cs @@ -10,83 +10,83 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTab : BasicExportImportDto { public int TabId { get; set; } - + public int TabOrder { get; set; } - + public string TabName { get; set; } - + public bool IsVisible { get; set; } - + public int? ParentId { get; set; } - + public string IconFile { get; set; } - + public bool DisableLink { get; set; } - + public string Title { get; set; } - + public string Description { get; set; } - + public string KeyWords { get; set; } - + public bool IsDeleted { get; set; } - + public string Url { get; set; } - + public string SkinSrc { get; set; } - + public string ContainerSrc { get; set; } - + public DateTime? StartDate { get; set; } - + public DateTime? EndDate { get; set; } - + public int? RefreshInterval { get; set; } - + public string PageHeadText { get; set; } - + public bool IsSecure { get; set; } - + public bool PermanentRedirect { get; set; } - + public float SiteMapPriority { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } - + public string IconFileLarge { get; set; } - + public string CultureCode { get; set; } - + public int? ContentItemID { get; set; } // FK - + public Guid UniqueId { get; set; } - + public Guid VersionGuid { get; set; } - + public Guid? DefaultLanguageGuid { get; set; } - + public Guid LocalizedVersionGuid { get; set; } - + public int Level { get; set; } - + public string TabPath { get; set; } - + public bool HasBeenPublished { get; set; } - + public bool IsSystem { get; set; } - + public int StateID { get; set; } - + public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } - + public string Tags { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs index 405ba3379d3..007b34c8d04 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabInfo.cs @@ -7,11 +7,11 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabInfo { public int TabID { get; set; } - + public int ParentID { get; set; } - + public string TabName { get; set; } - + public string TabPath { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs index 1db3dcb9764..72485c2f04f 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModule.cs @@ -10,81 +10,81 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabModule : BasicExportImportDto { public int TabModuleID { get; set; } - + public int TabID { get; set; } - + public int ModuleID { get; set; } - + public string PaneName { get; set; } - + public int ModuleOrder { get; set; } - + public int CacheTime { get; set; } - + public string Alignment { get; set; } - + public string Color { get; set; } - + public string Border { get; set; } - + public string IconFile { get; set; } - + public int Visibility { get; set; } - + public string ContainerSrc { get; set; } - + public bool DisplayTitle { get; set; } - + public bool DisplayPrint { get; set; } - + public bool DisplaySyndicate { get; set; } - + public bool IsWebSlice { get; set; } - + public string WebSliceTitle { get; set; } - + public DateTime? WebSliceExpiryDate { get; set; } - + public int? WebSliceTTL { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } - + public bool IsDeleted { get; set; } - + public string CacheMethod { get; set; } - + public string ModuleTitle { get; set; } - + public string Header { get; set; } - + public string Footer { get; set; } - + public string CultureCode { get; set; } - + public Guid UniqueId { get; set; } - + public Guid VersionGuid { get; set; } - + public Guid? DefaultLanguageGuid { get; set; } - + public Guid LocalizedVersionGuid { get; set; } - + public bool InheritViewPermissions { get; set; } - + public bool IsShareable { get; set; } - + public bool IsShareableViewOnly { get; set; } public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName - + public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs index 26d2385b909..a3380f4b9c4 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabModuleSetting.cs @@ -10,21 +10,21 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabModuleSetting : BasicExportImportDto { public int TabModuleID { get; set; } - + public string SettingName { get; set; } - + public string SettingValue { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs index 3136a0d226a..b22e753468e 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabPermission.cs @@ -10,41 +10,41 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabPermission : BasicExportImportDto { public int TabPermissionID { get; set; } - + public int TabID { get; set; } - + public int PermissionID { get; set; } - + public string PermissionCode { get; set; } - + public string PermissionKey { get; set; } - + public string PermissionName { get; set; } - + public bool AllowAccess { get; set; } - + public int? RoleID { get; set; } - + public string RoleName { get; set; } - + public int? UserID { get; set; } - + public string Username { get; set; } - + public int? ModuleDefID { get; set; } - + public string FriendlyName { get; set; } // this is ModuleDefinition.FriendlyName public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs index f1f47de6218..da92e12d9b9 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabSetting.cs @@ -10,21 +10,21 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabSetting : BasicExportImportDto { public int TabID { get; set; } - + public string SettingName { get; set; } - + public string SettingValue { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs index ec7098ed0a9..c5444c28d8d 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Pages/ExportTabUrl.cs @@ -10,35 +10,35 @@ namespace Dnn.ExportImport.Dto.Pages public class ExportTabUrl : BasicExportImportDto { public int TabID { get; set; } - + public int SeqNum { get; set; } - + public string Url { get; set; } - + public string QueryString { get; set; } - + public string HttpStatus { get; set; } - + public string CultureCode { get; set; } - + public bool IsSystem { get; set; } - + public int? PortalAliasId { get; set; } - + public int? PortalAliasUsage { get; set; } // PortalAliasUsageType - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string HTTPAlias { get; set; } - + public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs index e33e3894c79..acbc25671cb 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalLanguage.cs @@ -17,15 +17,15 @@ public class ExportPortalLanguage : BasicExportImportDto public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public bool IsPublished { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs index e36518555f1..8cd52cc8122 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Portal/ExportPortalSetting.cs @@ -11,23 +11,23 @@ public class ExportPortalSetting : BasicExportImportDto public int PortalSettingId { get; set; } public string SettingName { get; set; } - + public string SettingValue { get; set; } public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public string CultureCode { get; set; } - + public bool IsSecure { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs index c35ba0c8cf2..be5fd412923 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/ProfileProperties/ExportProfileProperty.cs @@ -13,39 +13,39 @@ public class ExportProfileProperty : BasicExportImportDto public int? ModuleDefId { get; set; } public bool Deleted { get; set; } - + public int? DataType { get; set; } - + public string DefaultValue { get; set; } - + public string PropertyCategory { get; set; } - + public string PropertyName { get; set; } - + public int Length { get; set; } - + public bool Required { get; set; } - + public string ValidationExpression { get; set; } - + public int ViewOrder { get; set; } - + public bool Visible { get; set; } public int? CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int? LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public int DefaultVisibility { get; set; } - + public bool ReadOnly { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs index b78f7ff05f0..6f1e9eab616 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRole.cs @@ -9,49 +9,49 @@ namespace Dnn.ExportImport.Dto.Roles public class ExportRole : BasicExportImportDto { public int RoleID { get; set; } - + public string RoleName { get; set; } - + public string Description { get; set; } - + public decimal? ServiceFee { get; set; } - + public string BillingFrequency { get; set; } - + public int? TrialPeriod { get; set; } - + public string TrialFrequency { get; set; } - + public int? BillingPeriod { get; set; } - + public decimal? TrialFee { get; set; } - + public bool IsPublic { get; set; } - + public bool AutoAssignment { get; set; } - + public int? RoleGroupID { get; set; } - + public string RSVPCode { get; set; } - + public string IconFile { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } - + public int Status { get; set; } - + public int SecurityMode { get; set; } - + public bool IsSystemRole { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs index 27d3cb88326..f59d22f382b 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleGroup.cs @@ -9,21 +9,21 @@ namespace Dnn.ExportImport.Dto.Roles public class ExportRoleGroup : BasicExportImportDto { public int RoleGroupID { get; set; } - + public string RoleGroupName { get; set; } - + public string Description { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs index edfea721833..d94741ea7fb 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Roles/ExportRoleSetting.cs @@ -9,23 +9,23 @@ namespace Dnn.ExportImport.Dto.Roles public class ExportRoleSetting : BasicExportImportDto { public int RoleSettingID { get; set; } - + public int RoleID { get; set; } - + public string SettingName { get; set; } - + public string SettingValue { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs index 814388f7437..842889a2bf7 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyScopeType.cs @@ -7,7 +7,7 @@ namespace Dnn.ExportImport.Dto.Taxonomy public class TaxonomyScopeType : BasicExportImportDto { public int ScopeTypeID { get; set; } - + public string ScopeType { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs index 5edd7e4218d..227e1f7ff78 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyTerm.cs @@ -10,29 +10,29 @@ namespace Dnn.ExportImport.Dto.Taxonomy public class TaxonomyTerm : BasicExportImportDto { public int TermID { get; set; } - + public int VocabularyID { get; set; } - + public int? ParentTermID { get; set; } - + public string Name { get; set; } - + public string Description { get; set; } - + public int Weight { get; set; } - + // public int TermLeft { get; set; } // public int TermRight { get; set; } public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs index abae42646df..39bef404280 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabulary.cs @@ -10,31 +10,31 @@ namespace Dnn.ExportImport.Dto.Taxonomy public class TaxonomyVocabulary : BasicExportImportDto { public int VocabularyID { get; set; } - + public int VocabularyTypeID { get; set; } - + public string Name { get; set; } - + public string Description { get; set; } - + public int Weight { get; set; } - + public int? ScopeID { get; set; } - + public int ScopeTypeID { get; set; } - + public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } - + public bool IsSystem { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs index cf60360ecd0..bd76f4bcae5 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Taxonomy/TaxonomyVocabularyType.cs @@ -7,7 +7,7 @@ namespace Dnn.ExportImport.Dto.Taxonomy public class TaxonomyVocabularyType : BasicExportImportDto { public int VocabularyTypeID { get; set; } // enum VocabularyType - + public string VocabularyType { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs index 3612a00534d..a93eb47c6fa 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetMembership.cs @@ -9,45 +9,45 @@ namespace Dnn.ExportImport.Dto.Users public class ExportAspnetMembership : BasicExportImportDto { public Guid ApplicationId { get; set; } - + public Guid UserId { get; set; } - + public string Password { get; set; } - + public int PasswordFormat { get; set; } - + public string PasswordSalt { get; set; } public virtual string MobilePin { get; set; } public string Email { get; set; } - + public string LoweredEmail { get; set; } - + public string PasswordQuestion { get; set; } - + public string PasswordAnswer { get; set; } - + public bool IsApproved { get; set; } - + public bool IsLockedOut { get; set; } - + public DateTime CreateDate { get; set; } - + public DateTime LastLoginDate { get; set; } - + public DateTime LastPasswordChangedDate { get; set; } - + public DateTime LastLockoutDate { get; set; } - + public int FailedPasswordAttemptCount { get; set; } - + public DateTime FailedPasswordAttemptWindowStart { get; set; } - + public int FailedPasswordAnswerAttemptCount { get; set; } - + public DateTime FailedPasswordAnswerAttemptWindowStart { get; set; } - + public string Comment { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs index 560ef0e4327..f46d736f6db 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportAspnetUser.cs @@ -9,17 +9,17 @@ namespace Dnn.ExportImport.Dto.Users public class ExportAspnetUser : BasicExportImportDto { public Guid ApplicationId { get; set; } - + public Guid UserId { get; set; } - + public string UserName { get; set; } - + public string LoweredUserName { get; set; } - + public string MobileAlias { get; set; } - + public bool IsAnonymous { get; set; } - + public DateTime? LastActivityDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs index 55d7bb8a1a2..0193d804f53 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs @@ -13,19 +13,19 @@ public class ExportUser : BasicExportImportDto public int UserId { get; set; } public string Username { get; set; } - + public string FirstName { get; set; } - + public string LastName { get; set; } - + public bool IsSuperUser { get; set; } - + public int? AffiliateId { get; set; } - + public string Email { get; set; } - + public string DisplayName { get; set; } - + public bool UpdatePassword { get; set; } public string LastIpAddress { get; set; } @@ -33,19 +33,19 @@ public class ExportUser : BasicExportImportDto public bool IsDeletedPortal { get; set; } public int CreatedByUserId { get; set; } // How do we insert this value? - + public string CreatedByUserName { get; set; }// This could be used to find "CreatedByUserId" - + public DateTime? CreatedOnDate { get; set; } public int LastModifiedByUserId { get; set; } // How do we insert this value? - + public string LastModifiedByUserName { get; set; }// This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public Guid? PasswordResetToken { get; set; } - + public DateTime? PasswordResetExpiration { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs index fbb18be7d1c..3554cd90772 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserAuthentication.cs @@ -13,19 +13,19 @@ public class ExportUserAuthentication : BasicExportImportDto public int UserId { get; set; } public string AuthenticationType { get; set; } - + public string AuthenticationToken { get; set; } - + public int CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" public DateTime CreatedOnDate { get; set; } - + public int LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime LastModifiedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs index b29e8955eb0..ee10f828e20 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserPortal.cs @@ -9,15 +9,15 @@ namespace Dnn.ExportImport.Dto.Users public class ExportUserPortal : BasicExportImportDto { public int UserId { get; set; } - + public DateTime CreatedDate { get; set; } - + public bool Authorised { get; set; } - + public bool IsDeleted { get; set; } - + public bool RefreshRoles { get; set; } - + public string VanityUrl { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs index c4ec1b9e5dd..a59bb99450d 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserProfile.cs @@ -17,13 +17,13 @@ public class ExportUserProfile : BasicExportImportDto public string PropertyName { get; set; } public string PropertyValue { get; set; } - + public string PropertyText { get; set; } - + public int Visibility { get; set; } - + public DateTime LastUpdatedDate { get; set; } - + public string ExtendedVisibility { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs index 96c71d17cc3..44fb17d1b66 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUserRole.cs @@ -17,25 +17,25 @@ public class ExportUserRole : BasicExportImportDto public string RoleName { get; set; } public DateTime? ExpiryDate { get; set; } - + public bool IsTrialUsed { get; set; } - + public DateTime? EffectiveDate { get; set; } public int CreatedByUserId { get; set; } public string CreatedByUserName { get; set; } // This could be used to find "CreatedByUserId" - + public DateTime CreatedOnDate { get; set; } public int LastModifiedByUserId { get; set; } public string LastModifiedByUserName { get; set; } // This could be used to find "LastModifiedByUserId" - + public DateTime? LastModifiedOnDate { get; set; } - + public int Status { get; set; } - + public bool IsOwner { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs index 103f8812262..3195fc9f673 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflow.cs @@ -7,23 +7,23 @@ namespace Dnn.ExportImport.Dto.Workflow public class ExportWorkflow : BasicExportImportDto { public int WorkflowID { get; set; } - + public string WorkflowName { get; set; } - + public string Description { get; set; } - + public bool IsDeleted { get; set; } - + public bool StartAfterCreating { get; set; } - + public bool StartAfterEditing { get; set; } - + public bool DispositionEnabled { get; set; } - + public bool IsSystem { get; set; } - + public string WorkflowKey { get; set; } - + public bool IsDefault { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs index f0e0896874e..3ce9bde4eb4 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowState.cs @@ -7,33 +7,33 @@ namespace Dnn.ExportImport.Dto.Workflow public class ExportWorkflowState : BasicExportImportDto { public int StateID { get; set; } - + public int WorkflowID { get; set; } - + public string StateName { get; set; } - + public int Order { get; set; } - + public bool IsActive { get; set; } - + public bool SendEmail { get; set; } - + public bool SendMessage { get; set; } - + public bool IsDisposalState { get; set; } - + public string OnCompleteMessageSubject { get; set; } - + public string OnCompleteMessageBody { get; set; } - + public string OnDiscardMessageSubject { get; set; } - + public string OnDiscardMessageBody { get; set; } - + public bool IsSystem { get; set; } - + public bool SendNotification { get; set; } - + public bool SendNotificationToAdministrators { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs index a34006026a0..f033541e84c 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Dto/Workflow/ExportWorkflowStatePermission.cs @@ -9,38 +9,38 @@ namespace Dnn.ExportImport.Dto.Workflow public class ExportWorkflowStatePermission : BasicExportImportDto { public int WorkflowStatePermissionID { get; set; } - + public int StateID { get; set; } - + public int PermissionID { get; set; } - + public string PermissionCode { get; set; } - + public string PermissionKey { get; set; } - + public string PermissionName { get; set; } - + public bool AllowAccess { get; set; } - + public int? RoleID { get; set; } - + public string RoleName { get; set; } - + public int? UserID { get; set; } - + public string Username { get; set; } - + // public int? ModuleDefID { get; set; } public int? CreatedByUserID { get; set; } - + public DateTime? CreatedOnDate { get; set; } - + public int? LastModifiedByUserID { get; set; } - + public DateTime? LastModifiedOnDate { get; set; } public string CreatedByUserName { get; set; } - + public string LastModifiedByUserName { get; set; } } } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs b/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs index 0278e907b9a..d0e7d52ed61 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Interfaces/IExportImportRepository.cs @@ -12,22 +12,22 @@ namespace Dnn.ExportImport.Interfaces public interface IExportImportRepository : IDisposable { - T AddSingleItem(T item) - where T : class; - - T UpdateSingleItem(T item) - where T : class; - - T GetSingleItem() - where T : class; + T AddSingleItem(T item) + where T : class; + + T UpdateSingleItem(T item) + where T : class; + + T GetSingleItem() + where T : class; - T CreateItem(T item, int? referenceId) - where T : BasicExportImportDto; + T CreateItem(T item, int? referenceId) + where T : BasicExportImportDto; void CreateItems(IEnumerable items, int? referenceId = null) where T : BasicExportImportDto; - IEnumerable GetItems( + IEnumerable GetItems( Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto; @@ -36,20 +36,20 @@ IEnumerable GetAllItems( Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto; - int GetCount() - where T : BasicExportImportDto; + int GetCount() + where T : BasicExportImportDto; - void RebuildIndex(Expression> predicate, bool unique = false) - where T : BasicExportImportDto; + void RebuildIndex(Expression> predicate, bool unique = false) + where T : BasicExportImportDto; + + int GetCount(Expression> predicate) + where T : BasicExportImportDto; - int GetCount(Expression> predicate) - where T : BasicExportImportDto; - T GetItem(Expression> predicate) where T : BasicExportImportDto; - T GetItem(int id) - where T : BasicExportImportDto; + T GetItem(int id) + where T : BasicExportImportDto; IEnumerable GetItems(IEnumerable idList) where T : BasicExportImportDto; @@ -57,20 +57,20 @@ IEnumerable GetItems(IEnumerable idList) IEnumerable GetRelatedItems(int referenceId) where T : BasicExportImportDto; - IEnumerable FindItems(Expression> predicate) - where T : BasicExportImportDto; + IEnumerable FindItems(Expression> predicate) + where T : BasicExportImportDto; - void UpdateItem(T item) - where T : BasicExportImportDto; + void UpdateItem(T item) + where T : BasicExportImportDto; - void UpdateItems(IEnumerable items) - where T : BasicExportImportDto; + void UpdateItems(IEnumerable items) + where T : BasicExportImportDto; - bool DeleteItem(int id) - where T : BasicExportImportDto; + bool DeleteItem(int id) + where T : BasicExportImportDto; - void DeleteItems(Expression> deleteExpression) - where T : BasicExportImportDto; + void DeleteItems(Expression> deleteExpression) + where T : BasicExportImportDto; void CleanUpLocal(string collectionName); } diff --git a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs index c9f8195b4f9..f2e8c1255d0 100644 --- a/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs +++ b/DNN Platform/Modules/DnnExportImportLibrary/Repository/ExportImportRepository.cs @@ -35,88 +35,78 @@ public void Dispose() this.Dispose(true); } - public T AddSingleItem(T item) - where T : class + public T AddSingleItem(T item) + where T : class { var collection = this.DbCollection(); collection.Insert(item); return item; } - public T UpdateSingleItem(T item) - where T : class + public T UpdateSingleItem(T item) + where T : class { var collection = this.DbCollection(); collection.Update(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 + public T GetSingleItem() + where T : class { var collection = this.DbCollection(); var first = collection.Min(); return collection.FindById(first); } - public T CreateItem(T item, int? referenceId) - where T : BasicExportImportDto + public T CreateItem(T item, int? referenceId) + where T : BasicExportImportDto { - if (item == null) - { - return null; - } - + if (item == null) + { + return null; + } + var collection = this.DbCollection(); if (referenceId != null) { item.ReferenceId = referenceId; } - + item.Id = collection.Insert(item); return item; } - public void CreateItems(IEnumerable items, int? referenceId = null) - where T : BasicExportImportDto + public void CreateItems(IEnumerable items, int? referenceId = null) + where T : BasicExportImportDto { - if (items == null) - { - return; - } - + if (items == null) + { + return; + } + var allItems = items as List ?? items.ToList(); - if (allItems.Count == 0) - { - return; - } - + if (allItems.Count == 0) + { + return; + } + var collection = this.DbCollection(); if (referenceId != null) { allItems.ForEach(x => { x.ReferenceId = referenceId; }); } - + collection.Insert(allItems); } - public T GetItem(Expression> predicate) - where T : BasicExportImportDto + public T GetItem(Expression> predicate) + where T : BasicExportImportDto { return this.InternalGetItems(predicate).FirstOrDefault(); } - public IEnumerable GetItems( + public IEnumerable GetItems( Expression> predicate, Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) where T : BasicExportImportDto @@ -124,22 +114,22 @@ public IEnumerable GetItems( return this.InternalGetItems(predicate, orderKeySelector, asc, skip, max); } - public int GetCount() - where T : BasicExportImportDto + public int GetCount() + where T : BasicExportImportDto { var collection = this.DbCollection(); return collection?.Count() ?? 0; } - - public int GetCount(Expression> predicate) - where T : BasicExportImportDto + + public int GetCount(Expression> predicate) + where T : BasicExportImportDto { var collection = this.DbCollection(); return collection?.Count(predicate) ?? 0; } - public void RebuildIndex(Expression> predicate, bool unique = false) - where T : BasicExportImportDto + public void RebuildIndex(Expression> predicate, bool unique = false) + where T : BasicExportImportDto { var collection = this.DbCollection(); collection.EnsureIndex(predicate, unique); @@ -152,8 +142,8 @@ public IEnumerable GetAllItems( return this.InternalGetItems(null, orderKeySelector, asc, skip, max); } - public T GetItem(int id) - where T : BasicExportImportDto + public T GetItem(int id) + where T : BasicExportImportDto { var collection = this.DbCollection(); return collection.FindById(id); @@ -166,25 +156,6 @@ public IEnumerable GetItems(IEnumerable idList) return this.InternalGetItems(predicate); } - private IEnumerable InternalGetItems( - Expression> predicate, - Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) - where T : BasicExportImportDto - { - var collection = this.DbCollection(); - - var result = predicate != null - ? collection.Find(predicate, skip ?? 0, max ?? int.MaxValue) - : collection.Find(Query.All(), skip ?? 0, max ?? int.MaxValue); - - if (orderKeySelector != null) - { - result = asc ? result.OrderBy(orderKeySelector) : result.OrderByDescending(orderKeySelector); - } - - return result.AsEnumerable(); - } - public IEnumerable GetRelatedItems(int referenceId) where T : BasicExportImportDto { @@ -192,73 +163,73 @@ public IEnumerable GetRelatedItems(int referenceId) return this.InternalGetItems(predicate); } - public IEnumerable FindItems(Expression> predicate) - where T : BasicExportImportDto + public IEnumerable FindItems(Expression> predicate) + where T : BasicExportImportDto { var collection = this.DbCollection(); return collection.Find(predicate); } - public void UpdateItem(T item) - where T : BasicExportImportDto + public void UpdateItem(T item) + where T : BasicExportImportDto { - if (item == null) - { - return; - } - + if (item == null) + { + return; + } + var collection = this.DbCollection(); - if (collection.FindById(item.Id) == null) - { - throw new KeyNotFoundException(); - } - + if (collection.FindById(item.Id) == null) + { + throw new KeyNotFoundException(); + } + collection.Update(item); } - public void UpdateItems(IEnumerable items) - where T : BasicExportImportDto + public void UpdateItems(IEnumerable items) + where T : BasicExportImportDto { var allItems = items as T[] ?? items.ToArray(); - if (allItems.Length == 0) - { - return; - } - + if (allItems.Length == 0) + { + return; + } + var collection = this.DbCollection(); collection.Update(allItems); } - public bool DeleteItem(int id) - where T : BasicExportImportDto + public bool DeleteItem(int id) + where T : BasicExportImportDto { var collection = this.DbCollection(); var item = collection.FindById(id); - if (item == null) - { - throw new KeyNotFoundException(); - } - + if (item == null) + { + throw new KeyNotFoundException(); + } + return collection.Delete(id); } - public void DeleteItems(Expression> deleteExpression) - where T : BasicExportImportDto + public void DeleteItems(Expression> deleteExpression) + where T : BasicExportImportDto { var collection = this.DbCollection(); - if (deleteExpression != null) - { - collection.Delete(deleteExpression); - } + if (deleteExpression != null) + { + collection.Delete(deleteExpression); + } } public void CleanUpLocal(string collectionName) { - if (!this._liteDb.CollectionExists(collectionName)) - { - return; - } - + if (!this._liteDb.CollectionExists(collectionName)) + { + return; + } + var collection = this._liteDb.GetCollection(collectionName); var documentsToUpdate = collection.Find(Query.All()).ToList(); documentsToUpdate.ForEach(x => @@ -268,6 +239,35 @@ public void CleanUpLocal(string collectionName) collection.Update(documentsToUpdate); } + private void Dispose(bool isDisposing) + { + var temp = Interlocked.Exchange(ref this._liteDb, null); + temp?.Dispose(); + if (isDisposing) + { + GC.SuppressFinalize(this); + } + } + + private IEnumerable InternalGetItems( + Expression> predicate, + Func orderKeySelector = null, bool asc = true, int? skip = null, int? max = null) + where T : BasicExportImportDto + { + var collection = this.DbCollection(); + + var result = predicate != null + ? collection.Find(predicate, skip ?? 0, max ?? int.MaxValue) + : collection.Find(Query.All(), skip ?? 0, max ?? int.MaxValue); + + if (orderKeySelector != null) + { + result = asc ? result.OrderBy(orderKeySelector) : result.OrderByDescending(orderKeySelector); + } + + return result.AsEnumerable(); + } + private LiteCollection DbCollection() { return this._liteDb.GetCollection(typeof(T).Name); diff --git a/DNN Platform/Modules/Groups/Components/Constants.cs b/DNN Platform/Modules/Groups/Components/Constants.cs index 0d0478e4519..3e307ed4689 100644 --- a/DNN Platform/Modules/Groups/Components/Constants.cs +++ b/DNN Platform/Modules/Groups/Components/Constants.cs @@ -36,7 +36,7 @@ public class Constants internal const string MemberApprovedNotification = "GroupMemberApprovedNotification"; // Sent to Member when membership is approved. internal const string MemberJoinedNotification = "MemberJoinedNotification"; // Sent to Group Owners when a new member has joined a public group. internal const string MemberRejectedNotification = "GroupMemberRejectedNotification"; // Sent to requesting member when membership is rejected. - + internal const string SharedResourcesPath = "~/DesktopModules/SocialGroups/App_LocalResources/SharedResources.resx"; internal const string ModulePath = "~/DesktopModules/SocialGroups/"; diff --git a/DNN Platform/Modules/Groups/Components/Content.cs b/DNN Platform/Modules/Groups/Components/Content.cs index 2581b5f1cad..5d0e4c275c7 100644 --- a/DNN Platform/Modules/Groups/Components/Content.cs +++ b/DNN Platform/Modules/Groups/Components/Content.cs @@ -20,53 +20,53 @@ 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) + 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) + if (colContentTypes.Count() > 0) { var contentType = colContentTypes.Single(); contentTypeId = contentType == null ? CreateContentType(ContentTypeName) : contentType.ContentTypeId; - } - else + } + else { contentTypeId = CreateContentType(ContentTypeName); } return contentTypeId; - } - + } + /// /// This should only run after the Post exists in the data store. /// /// The newly created ContentItemID from the data store. /// This is for the first question in the thread. Not for replies or items with ParentID > 0. - internal ContentItem CreateContentItem(RoleInfo objItem, int tabId) + internal ContentItem CreateContentItem(RoleInfo objItem, int tabId) { var typeController = new ContentTypeController(); string contentTypeName = "DNNCorp_SocialGroup"; - if (objItem.RoleID > 0) + if (objItem.RoleID > 0) { contentTypeName = "DNNCorp_SocialGroup"; } - + var colContentTypes = from t in typeController.GetContentTypes() where t.ContentType == contentTypeName select t; int contentTypeID; - if (colContentTypes.Count() > 0) + if (colContentTypes.Count() > 0) { var contentType = colContentTypes.Single(); contentTypeID = contentType == null ? CreateContentType(contentTypeName) : contentType.ContentTypeId; - } - else + } + else { contentTypeID = CreateContentType(contentTypeName); } - var objContent = new ContentItem + var objContent = new ContentItem { Content = objItem.RoleName, ContentTypeId = contentTypeID, @@ -87,15 +87,15 @@ internal ContentItem CreateContentItem(RoleInfo objItem, int tabId) /// /// This is used to update the content in the ContentItems table. Should be called when a question is updated. /// - internal void UpdateContentItem(RoleInfo objItem, int tabId) + internal void UpdateContentItem(RoleInfo objItem, int tabId) { ContentItem objContent = null; // Util.GetContentController().; - if (objContent == null) - { - return; - } - + if (objContent == null) + { + return; + } + objContent.Content = objItem.RoleName; objContent.TabID = tabId; objContent.ContentKey = "GroupId=" + objItem.RoleID; // we reset this just in case the page changed. @@ -111,35 +111,35 @@ internal void UpdateContentItem(RoleInfo objItem, int tabId) /// This removes a content item associated with a question/thread from the data store. Should run every time an entire thread is deleted. ///
    /// - internal void DeleteContentItem(int contentItemID) + internal void DeleteContentItem(int contentItemID) { - if (contentItemID <= Null.NullInteger) - { - return; - } - + if (contentItemID <= Null.NullInteger) + { + return; + } + var objContent = Util.GetContentController().GetContentItem(contentItemID); - if (objContent == null) - { - return; - } - - // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) - // var cntTerms = new Terms(); - // cntTerms.RemoveQuestionTerms(objContent); + if (objContent == null) + { + return; + } + + // remove any metadata/terms associated first (perhaps we should just rely on ContentItem cascade delete here?) + // var cntTerms = new Terms(); + // cntTerms.RemoveQuestionTerms(objContent); Util.GetContentController().DeleteContentItem(objContent); } - + /// /// Creates a Content Type (for taxonomy) in the data store. /// /// The primary key value of the new ContentType. - private static int CreateContentType(string ContentTypeName) + private static int CreateContentType(string ContentTypeName) { var typeController = new ContentTypeController(); var objContentType = new ContentType { ContentType = ContentTypeName }; return typeController.AddContentType(objContentType); - } + } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupInfo.cs b/DNN Platform/Modules/Groups/Components/GroupInfo.cs index acced559719..2345ef9afec 100644 --- a/DNN Platform/Modules/Groups/Components/GroupInfo.cs +++ b/DNN Platform/Modules/Groups/Components/GroupInfo.cs @@ -15,11 +15,11 @@ namespace DotNetNuke.Entities.Groups public class GroupInfo : RoleInfo, IPropertyAccess { // private RoleInfo roleInfo; - public GroupInfo() + public GroupInfo() { } - - public GroupInfo(RoleInfo roleInfo) + + public GroupInfo(RoleInfo roleInfo) { this.RoleID = roleInfo.RoleID; this.RoleName = roleInfo.RoleName; @@ -29,7 +29,7 @@ public GroupInfo(RoleInfo roleInfo) this.ServiceFee = roleInfo.ServiceFee; this.RSVPCode = roleInfo.RSVPCode; } - + // public RoleInfo Role { // get { // return roleInfo; @@ -45,121 +45,121 @@ public GroupInfo(RoleInfo roleInfo) // } // public int ModuleId { get; set; } - public string Street + public string Street { - get + get { return this.GetString("Street", string.Empty); } - - set + + set { this.SetString("Street", value); } } - - public string City + + public string City { - get + get { return this.GetString("City", string.Empty); } - - set + + set { this.SetString("City", value); } } - public string Region + public string Region { - get + get { return this.GetString("Region", string.Empty); } - - set + + set { this.SetString("Region", value); } } - public string Country + public string Country { - get + get { return this.GetString("Country", string.Empty); } - - set + + set { this.SetString("Country", value); } } - public string PostalCode + public string PostalCode { - get + get { return this.GetString("PostalCode", string.Empty); } - - set + + set { this.SetString("PostalCode", value); } } - public string Website + public string Website { - get + get { return this.GetString("Website", string.Empty); } - - set + + set { this.SetString("Website", value); } } - - public bool Featured + + public bool Featured { - get + get { return Convert.ToBoolean(this.GetString("Featured", "false")); } - - set + + set { this.SetString("Featured", value.ToString()); } } - - private string GetString(string keyName, string defaultValue) + + private string GetString(string keyName, string defaultValue) { - if (this.Settings == null) + if (this.Settings == null) { return defaultValue; } - - if (this.Settings.ContainsKey(keyName)) + + if (this.Settings.ContainsKey(keyName)) { return this.Settings[keyName]; - } - else + } + else { return defaultValue; } } - - private void SetString(string keyName, string value) + + private void SetString(string keyName, string value) { - if (this.Settings.ContainsKey(keyName)) + if (this.Settings.ContainsKey(keyName)) { this.Settings[keyName] = value; - } - else + } + else { this.Settings.Add(keyName, value); } diff --git a/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs b/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs index 294c08c2adb..6a96615fe0a 100644 --- a/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs +++ b/DNN Platform/Modules/Groups/Components/GroupItemPropertyAccess.cs @@ -21,8 +21,8 @@ public GroupItemTokenReplace(RoleInfo groupInfo) { this.PropertySource["groupitem"] = groupInfo; } - - public string ReplaceGroupItemTokens(string source) + + public string ReplaceGroupItemTokens(string source) { return this.ReplaceTokens(source); } diff --git a/DNN Platform/Modules/Groups/Components/GroupMemberType.cs b/DNN Platform/Modules/Groups/Components/GroupMemberType.cs index 1d8f717a27e..3cf5b57f342 100644 --- a/DNN Platform/Modules/Groups/Components/GroupMemberType.cs +++ b/DNN Platform/Modules/Groups/Components/GroupMemberType.cs @@ -7,7 +7,7 @@ namespace DotNetNuke.Modules.Groups.Components internal class GroupMemberType { public int GroupMemberTypeId { get; set; } - + public string GroupMemberTypeName { get; set; } } } diff --git a/DNN Platform/Modules/Groups/Components/GroupUtilities.cs b/DNN Platform/Modules/Groups/Components/GroupUtilities.cs index 747261aedba..6d99ebadb27 100644 --- a/DNN Platform/Modules/Groups/Components/GroupUtilities.cs +++ b/DNN Platform/Modules/Groups/Components/GroupUtilities.cs @@ -35,16 +35,16 @@ public static void CreateJournalEntry(RoleInfo roleInfo, UserInfo createdBy) journalItem.JournalTypeId = journalController.GetJournalType("groupcreate").JournalTypeId; journalItem.ObjectKey = string.Format("groupcreate:{0}:{1}", roleInfo.RoleID.ToString(CultureInfo.InvariantCulture), createdBy.UserID.ToString(CultureInfo.InvariantCulture)); - if (journalController.GetJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey) != null) - { - journalController.DeleteJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey); + if (journalController.GetJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey) != null) + { + journalController.DeleteJournalItemByKey(roleInfo.PortalID, journalItem.ObjectKey); } journalItem.SecuritySet = string.Empty; - if (roleInfo.IsPublic) - { - journalItem.SecuritySet += "E,"; + if (roleInfo.IsPublic) + { + journalItem.SecuritySet += "E,"; } journalController.SaveJournalItem(journalItem, null); diff --git a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs index 7cc312d6a42..a99b5c54902 100644 --- a/DNN Platform/Modules/Groups/Components/GroupViewParser.cs +++ b/DNN Platform/Modules/Groups/Components/GroupViewParser.cs @@ -28,20 +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; } - + + public string GroupEditUrl { 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() { @@ -60,7 +60,7 @@ public string ParseView() membershipPending = true; } } - + if (this.RoleInfo.CreatedByUserID == this.CurrentUser.UserID || this.CurrentUser.IsSuperUser) { isOwner = true; @@ -84,25 +84,25 @@ public string ParseView() this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotOwner", false); this.Template = Utilities.ParseTokenWrapper(this.Template, "IsOwner", false); - if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName) || !HttpContext.Current.Request.IsAuthenticated || membershipPending) - { - this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", false); - } - else - { - this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", true); - } - + if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName) || !HttpContext.Current.Request.IsAuthenticated || membershipPending) + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", false); + } + else + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsNotMember", true); + } + if (this.CurrentUser.IsInRole(this.RoleInfo.RoleName)) { this.Template = Utilities.ParseTokenWrapper(this.Template, "IsMember", true); this.Template = Utilities.ParseTokenWrapper(this.Template, "IsPendingMember", false); } - else - { - this.Template = Utilities.ParseTokenWrapper(this.Template, "IsMember", false); - } - + else + { + this.Template = Utilities.ParseTokenWrapper(this.Template, "IsMember", false); + } + this.Template = Utilities.ParseTokenWrapper(this.Template, "AllowJoin", this.RoleInfo.IsPublic); this.Template = this.Template.Replace("[GROUPEDITBUTTON]", string.Empty); diff --git a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs index 71384bd1b02..87193819655 100644 --- a/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs +++ b/DNN Platform/Modules/Groups/Components/GroupsBusinessController.cs @@ -66,7 +66,7 @@ private void RemoveRejectActionForCreatedNotification() { return; } - + NotificationsController.Instance.DeleteNotificationTypeAction(action.NotificationTypeActionId); } @@ -81,17 +81,17 @@ 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 = "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 = "RejectGroup", + DescriptionResourceKey = "RejectGroup", + APICall = "API/SocialGroups/ModerationService/RejectGroup", }); NotificationsController.Instance.CreateNotificationType(type); NotificationsController.Instance.SetNotificationTypeActions(actions, type.NotificationTypeId); @@ -109,12 +109,12 @@ 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,18 +132,18 @@ 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 = "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 = "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 ac4dd2be9a0..b7f4e8ca43d 100644 --- a/DNN Platform/Modules/Groups/Components/Notifications.cs +++ b/DNN Platform/Modules/Groups/Components/Notifications.cs @@ -19,13 +19,13 @@ internal virtual Notification AddGroupNotification(string notificationTypeName, { return this.AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, null as UserInfo); } - + internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, UserInfo recipient) { return this.AddGroupNotification(notificationTypeName, tabId, moduleId, group, initiatingUser, moderators, recipient == null ? null : new List { recipient }); } - - internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, IList recipients) + + internal virtual Notification AddGroupNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser, IList moderators, IList recipients) { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); var tokenReplace = new GroupItemTokenReplace(group); @@ -40,20 +40,20 @@ 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; } - + internal virtual Notification AddGroupOwnerNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo initiatingUser) { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); @@ -80,9 +80,9 @@ internal virtual Notification AddGroupOwnerNotification(string notificationTypeN roleOwners.Add(UserController.GetUserById(group.PortalID, userRoleInfo.UserID)); } } - + roleOwners.Add(roleCreator); - + // Need to add from sender details var notification = new Notification { @@ -97,8 +97,8 @@ internal virtual Notification AddGroupOwnerNotification(string notificationTypeN return notification; } - - internal virtual Notification AddMemberNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo sender, UserInfo recipient) + + internal virtual Notification AddMemberNotification(string notificationTypeName, int tabId, int moduleId, RoleInfo group, UserInfo sender, UserInfo recipient) { var notificationType = NotificationsController.Instance.GetNotificationType(notificationTypeName); diff --git a/DNN Platform/Modules/Groups/Components/Utilities.cs b/DNN Platform/Modules/Groups/Components/Utilities.cs index 12af3904236..115b5cca3fd 100644 --- a/DNN Platform/Modules/Groups/Components/Utilities.cs +++ b/DNN Platform/Modules/Groups/Components/Utilities.cs @@ -18,7 +18,7 @@ public static string NavigateUrl(int TabId, string[] @params) { return Globals.DependencyProvider.GetRequiredService()?.NavigateURL(TabId, string.Empty, @params); } - + public static string[] AddParams(string param, string[] currParams) { var tmpParams = new string[] { param }; @@ -28,8 +28,8 @@ public static string[] AddParams(string param, string[] currParams) currParams.CopyTo(tmpParams, intLength); return tmpParams; } - - internal static string ParseTokenWrapper(string Template, string Token, bool Condition) + + 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); @@ -38,7 +38,7 @@ internal static string ParseTokenWrapper(string Template, string Token, bool Con { 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 27877ac071d..c6543753d77 100644 --- a/DNN Platform/Modules/Groups/Create.ascx.cs +++ b/DNN Platform/Modules/Groups/Create.ascx.cs @@ -23,18 +23,18 @@ namespace DotNetNuke.Modules.Groups public partial class Create : GroupsModuleBase { private readonly INavigationManager _navigationManager; - + public Create() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - + protected override void OnInit(EventArgs e) { this.InitializeComponent(); base.OnInit(e); } - + protected void Page_Load(object sender, EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); @@ -51,7 +51,7 @@ private void Cancel_Click(object sender, EventArgs e) { this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, null)); } - + private void Create_Click(object sender, EventArgs e) { var ps = Security.PortalSecurity.Instance; @@ -65,7 +65,7 @@ private void Create_Click(object sender, EventArgs e) this.lblInvalidGroupName.Visible = true; return; } - + var modRoles = new List(); var modUsers = new List(); foreach (ModulePermissionInfo modulePermissionInfo in ModulePermissionController.GetModulePermissions(this.ModuleId, this.TabId)) @@ -115,7 +115,7 @@ private void Create_Click(object sender, EventArgs e) { roleGroupId = Null.NullInteger; } - + roleInfo.RoleGroupID = roleGroupId; roleInfo.RoleID = RoleController.Instance.AddRole(roleInfo); @@ -127,7 +127,7 @@ private void Create_Click(object sender, EventArgs e) const int startIndex = 8; // length of https:// groupUrl = groupUrl.Substring(groupUrl.IndexOf("/", startIndex, StringComparison.InvariantCultureIgnoreCase)); } - + roleInfo.Settings.Add("URL", groupUrl); roleInfo.Settings.Add("GroupCreatorName", this.UserInfo.DisplayName); @@ -145,7 +145,7 @@ private void Create_Click(object sender, EventArgs e) { groupFolder = _folderManager.AddFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); } - + if (groupFolder != null) { var fileName = Path.GetFileName(this.inpFile.PostedFile.FileName); @@ -156,7 +156,7 @@ private void Create_Click(object sender, EventArgs e) } var notifications = new Notifications(); - + RoleController.Instance.AddUserRole(this.PortalId, this.UserId, roleInfo.RoleID, userRoleStatus, true, Null.NullDate, Null.NullDate); if (roleInfo.Status == RoleStatus.Pending) { diff --git a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs index 57b28676f93..89d245088a9 100644 --- a/DNN Platform/Modules/Groups/GroupEdit.ascx.cs +++ b/DNN Platform/Modules/Groups/GroupEdit.ascx.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Modules.Groups public partial class GroupEdit : GroupsModuleBase { private readonly INavigationManager _navigationManager; - + public GroupEdit() { this._navigationManager = this.DependencyProvider.GetRequiredService(); @@ -29,7 +29,7 @@ protected override void OnInit(EventArgs e) this.InitializeComponent(); base.OnInit(e); } - + protected void Page_Load(object sender, EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); @@ -52,24 +52,24 @@ protected void Page_Load(object sender, EventArgs e) this.txtGroupName.Visible = !roleInfo.IsSystemRole; this.reqGroupName.Enabled = !roleInfo.IsSystemRole; - if (!roleInfo.IsSystemRole) - { - this.txtGroupName.Text = roleInfo.RoleName; - } - else - { - this.litGroupName.Text = roleInfo.RoleName; - } - + if (!roleInfo.IsSystemRole) + { + this.txtGroupName.Text = roleInfo.RoleName; + } + else + { + this.litGroupName.Text = roleInfo.RoleName; + } + this.txtDescription.Text = roleInfo.Description; this.rdAccessTypePrivate.Checked = !roleInfo.IsPublic; this.rdAccessTypePublic.Checked = roleInfo.IsPublic; - + if (roleInfo.Settings.ContainsKey("ReviewMembers")) { this.chkMemberApproved.Checked = Convert.ToBoolean(roleInfo.Settings["ReviewMembers"].ToString()); } - + this.imgGroup.Src = roleInfo.PhotoURL; } else @@ -85,7 +85,7 @@ private void InitializeComponent() this.btnSave.Click += this.Save_Click; this.btnCancel.Click += this.Cancel_Click; } - + private void Cancel_Click(object sender, EventArgs e) { this.Response.Redirect(this.ModuleContext.NavigateUrl(this.TabId, string.Empty, false, new string[] { "groupid=" + this.GroupId.ToString() })); @@ -125,15 +125,15 @@ private void Save_Click(object sender, EventArgs e) roleInfo.Description = this.txtDescription.Text; roleInfo.IsPublic = this.rdAccessTypePublic.Checked; - if (roleInfo.Settings.ContainsKey("ReviewMembers")) - { - roleInfo.Settings["ReviewMembers"] = this.chkMemberApproved.Checked.ToString(); - } - else - { - roleInfo.Settings.Add("ReviewMembers", this.chkMemberApproved.Checked.ToString()); - } - + if (roleInfo.Settings.ContainsKey("ReviewMembers")) + { + roleInfo.Settings["ReviewMembers"] = this.chkMemberApproved.Checked.ToString(); + } + else + { + roleInfo.Settings.Add("ReviewMembers", this.chkMemberApproved.Checked.ToString()); + } + RoleController.Instance.UpdateRoleSettings(roleInfo, true); RoleController.Instance.UpdateRole(roleInfo); @@ -148,7 +148,7 @@ private void Save_Click(object sender, EventArgs e) { groupFolder = _folderManager.AddFolder(this.PortalSettings.PortalId, "Groups/" + roleInfo.RoleID); } - + if (groupFolder != null) { var fileName = Path.GetFileName(this.inpFile.PostedFile.FileName); diff --git a/DNN Platform/Modules/Groups/GroupListControl.cs b/DNN Platform/Modules/Groups/GroupListControl.cs index 6fa218063e9..c95bc5b9e65 100644 --- a/DNN Platform/Modules/Groups/GroupListControl.cs +++ b/DNN Platform/Modules/Groups/GroupListControl.cs @@ -26,37 +26,37 @@ namespace DotNetNuke.Modules.Groups.Controls public class GroupListControl : WebControl { public UserInfo currentUser; - - [DefaultValue("")] + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public PortalSettings PortalSettings + { + get + { + return PortalController.Instance.GetCurrentPortalSettings(); + } + } + + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string ItemTemplate { get; set; } - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string HeaderTemplate { get; set; } - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string FooterTemplate { get; set; } - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string RowHeaderTemplate { get; set; } - [DefaultValue("")] + [DefaultValue("")] [PersistenceMode(PersistenceMode.InnerProperty)] public string RowFooterTemplate { get; set; } - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public PortalSettings PortalSettings - { - get - { - return PortalController.Instance.GetCurrentPortalSettings(); - } - } - [DefaultValue(1)] public int ItemsPerRow { get; set; } @@ -104,15 +104,15 @@ protected override void Render(HtmlTextWriter output) whereCls.Add(grp => grp.RoleGroupID == this.RoleGroupId); } - if (this.DisplayCurrentUserGroups) - { - whereCls.Add(grp => this.currentUser.IsInRole(grp.RoleName)); - } - else - { - whereCls.Add(grp => grp.IsPublic || this.currentUser.IsInRole(grp.RoleName) || this.currentUser.IsInRole(this.PortalSettings.AdministratorRoleName)); - } - + if (this.DisplayCurrentUserGroups) + { + whereCls.Add(grp => this.currentUser.IsInRole(grp.RoleName)); + } + else + { + whereCls.Add(grp => grp.IsPublic || this.currentUser.IsInRole(grp.RoleName) || this.currentUser.IsInRole(this.PortalSettings.AdministratorRoleName)); + } + if (!string.IsNullOrEmpty(this.SearchFilter)) { whereCls.Add(grp => grp.RoleName.ToLowerInvariant().Contains(this.SearchFilter.ToLowerInvariant()) || grp.Description.ToLowerInvariant().Contains(this.SearchFilter.ToLowerInvariant())); @@ -120,19 +120,19 @@ protected override void Render(HtmlTextWriter output) var roles = RoleController.Instance.GetRoles(this.PortalSettings.PortalId, grp => TestPredicateGroup(whereCls, grp)); - if (this.SortDirection.ToLowerInvariant() == "asc") - { - roles = roles.OrderBy(info => GetOrderByProperty(info, this.SortField)).ToList(); - } - else - { - roles = roles.OrderByDescending(info => GetOrderByProperty(info, this.SortField)).ToList(); - } - + if (this.SortDirection.ToLowerInvariant() == "asc") + { + roles = roles.OrderBy(info => GetOrderByProperty(info, this.SortField)).ToList(); + } + else + { + roles = roles.OrderByDescending(info => GetOrderByProperty(info, this.SortField)).ToList(); + } + decimal pages = (decimal)roles.Count / (decimal)this.PageSize; - + output.Write(this.HeaderTemplate); - + this.ItemTemplate = this.ItemTemplate.Replace("{resx:posts}", Localization.GetString("posts", Constants.SharedResourcesPath)); this.ItemTemplate = this.ItemTemplate.Replace("{resx:members}", Localization.GetString("members", Constants.SharedResourcesPath)); this.ItemTemplate = this.ItemTemplate.Replace("{resx:photos}", Localization.GetString("photos", Constants.SharedResourcesPath)); @@ -143,9 +143,9 @@ protected override void Render(HtmlTextWriter output) this.ItemTemplate = this.ItemTemplate.Replace("{resx:LeaveGroup}", Localization.GetString("LeaveGroup", Constants.SharedResourcesPath)); this.ItemTemplate = this.ItemTemplate.Replace("[GroupViewTabId]", this.GroupViewTabId.ToString()); - if (roles.Count == 0) - { - output.Write(string.Format("
    {0}
    ", Localization.GetString("NoGroupsFound", Constants.SharedResourcesPath))); + if (roles.Count == 0) + { + output.Write(string.Format("
    {0}
    ", Localization.GetString("NoGroupsFound", Constants.SharedResourcesPath))); } if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["page"])) @@ -157,27 +157,27 @@ protected override void Render(HtmlTextWriter output) int rowItem = 0; int recordStart = this.CurrentIndex * this.PageSize; - if (this.CurrentIndex == 0) - { - recordStart = 0; + if (this.CurrentIndex == 0) + { + recordStart = 0; } for (int x = recordStart; x < (recordStart + this.PageSize); x++) { - if (x > roles.Count - 1) - { - break; - } - + if (x > roles.Count - 1) + { + break; + } + var role = roles[x]; string rowTemplate = this.ItemTemplate; - if (rowItem == 0) - { - output.Write(this.RowHeaderTemplate); - } - + if (rowItem == 0) + { + output.Write(this.RowHeaderTemplate); + } + var groupParser = new GroupViewParser(this.PortalSettings, role, this.currentUser, rowTemplate, this.GroupViewTabId); output.Write(groupParser.ParseView()); @@ -190,20 +190,20 @@ protected override void Render(HtmlTextWriter output) } } - if (rowItem > 0) - { - output.Write(this.RowFooterTemplate); + if (rowItem > 0) + { + output.Write(this.RowFooterTemplate); } output.Write(this.FooterTemplate); int TotalPages = Convert.ToInt32(System.Math.Ceiling(pages)); - - if (TotalPages == 0) - { - TotalPages = 1; - } - + + if (TotalPages == 0) + { + TotalPages = 1; + } + string sUrlFormat = "{2}"; string[] currParams = new string[] { }; @@ -232,9 +232,9 @@ protected override void Render(HtmlTextWriter output) string cssClass = "pagerItem"; - if (x - 1 == this.CurrentIndex) - { - cssClass = "pagerItemSelected"; + if (x - 1 == this.CurrentIndex) + { + cssClass = "pagerItemSelected"; } sb.AppendFormat(sUrlFormat, sUrl, cssClass, x.ToString()); diff --git a/DNN Platform/Modules/Groups/GroupView.ascx.cs b/DNN Platform/Modules/Groups/GroupView.ascx.cs index a0ef0d538e1..9b69181ee18 100644 --- a/DNN Platform/Modules/Groups/GroupView.ascx.cs +++ b/DNN Platform/Modules/Groups/GroupView.ascx.cs @@ -39,10 +39,10 @@ protected void Page_Load(object sender, EventArgs e) role.Description = Localization.GetString("Sample_RoleDescription", this.LocalResourceFile); } - if (role == null) - { - this.litOutput.Text = string.Empty; - } + if (role == null) + { + this.litOutput.Text = string.Empty; + } else { var resxPath = Constants.SharedResourcesPath; @@ -59,7 +59,7 @@ protected void Page_Load(object sender, EventArgs e) template = template.Replace("{resx:LeaveGroup}", Localization.GetString("LeaveGroup", resxPath)); template = template.Replace("{resx:EditGroup}", Localization.GetString("EditGroup", resxPath)); template = template.Replace("[GroupViewTabId]", this.GroupViewTabId.ToString()); - + var groupParser = new GroupViewParser(this.PortalSettings, role, this.UserInfo, template, this.TabId); groupParser.GroupEditUrl = this.GetEditUrl(); diff --git a/DNN Platform/Modules/Groups/GroupsModuleBase.cs b/DNN Platform/Modules/Groups/GroupsModuleBase.cs index 3c0391ad8a7..37cb4a477ea 100644 --- a/DNN Platform/Modules/Groups/GroupsModuleBase.cs +++ b/DNN Platform/Modules/Groups/GroupsModuleBase.cs @@ -25,8 +25,8 @@ public enum GroupMode Setup = 0, List = 1, View = 2, - } - + } + public GroupMode LoadView { get @@ -44,13 +44,11 @@ public GroupMode LoadView break; } } - + return mode; } } - - protected INavigationManager NavigationManager { get; } - + public int GroupId { get @@ -60,16 +58,16 @@ public int GroupId { return groupId; } - + if (int.TryParse(this.Request.QueryString["GroupId"], out groupId)) { return groupId; } - + return -1; } } - + public int DefaultRoleGroupId { get @@ -78,16 +76,16 @@ public int DefaultRoleGroupId if (this.Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) { int id; - if (int.TryParse(this.Settings[Constants.DefaultRoleGroupSetting].ToString(), out id)) - { - roleGroupId = id; - } + if (int.TryParse(this.Settings[Constants.DefaultRoleGroupSetting].ToString(), out id)) + { + roleGroupId = id; + } } return roleGroupId; // -2 is for "< All Roles >" } } - + public int GroupListTabId { get @@ -96,11 +94,11 @@ public int GroupListTabId { return Convert.ToInt32(this.Settings[Constants.GroupListPage].ToString()); } - + return this.TabId; } } - + public int GroupViewTabId { get @@ -109,11 +107,11 @@ public int GroupViewTabId { return Convert.ToInt32(this.Settings[Constants.GroupViewPage].ToString()); } - + return this.TabId; } } - + public string GroupViewTemplate { get @@ -126,11 +124,11 @@ public string GroupViewTemplate template = this.Settings[Constants.GroupViewTemplate].ToString(); } } - + return template; } } - + public string GroupListTemplate { get @@ -143,11 +141,11 @@ public string GroupListTemplate template = this.Settings[Constants.GroupListTemplate].ToString(); } } - + return template; } } - + public string DefaultGroupMode { get @@ -156,11 +154,11 @@ public string DefaultGroupMode { return this.Settings[Constants.DefautlGroupViewMode].ToString(); } - + return string.Empty; } } - + public bool GroupModerationEnabled { get @@ -169,11 +167,11 @@ public bool GroupModerationEnabled { return Convert.ToBoolean(this.Settings[Constants.GroupModerationEnabled].ToString()); } - + return false; } } - + public bool CanCreate { get @@ -184,10 +182,10 @@ public bool CanCreate { return true; } - + return ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, "CREATEGROUP"); } - + return false; } } @@ -211,11 +209,11 @@ public int GroupListPageSize return Convert.ToInt32(this.Settings[Constants.GroupListPageSize].ToString()); } } - + return 20; } } - + public bool GroupListSearchEnabled { get @@ -233,7 +231,7 @@ public bool GroupListSearchEnabled return enableSearch; } } - + public string GroupListSortField { get @@ -241,7 +239,7 @@ public string GroupListSortField return this.Settings.ContainsKey(Constants.GroupListSortField) ? this.Settings[Constants.GroupListSortField].ToString() : string.Empty; } } - + public string GroupListSortDirection { get @@ -249,7 +247,7 @@ public string GroupListSortDirection return this.Settings.ContainsKey(Constants.GroupListSortDirection) ? this.Settings[Constants.GroupListSortDirection].ToString() : string.Empty; } } - + public bool GroupListUserGroupsOnly { get @@ -266,8 +264,10 @@ public bool GroupListUserGroupsOnly return userGroupsOnly; } - } - + } + + protected INavigationManager NavigationManager { get; } + public string GetCreateUrl() { return this.ModuleContext.EditUrl("Create"); // .NavigateUrl(GroupCreateTabId,"",true,null); @@ -281,6 +281,6 @@ public string GetClearFilterUrl() public string GetEditUrl() { return this.ModuleContext.EditUrl("GroupId", this.GroupId.ToString("D"), "Edit"); - } + } } } diff --git a/DNN Platform/Modules/Groups/GroupsSettingsBase.cs b/DNN Platform/Modules/Groups/GroupsSettingsBase.cs index 34a562cbb4c..57f25b77dad 100644 --- a/DNN Platform/Modules/Groups/GroupsSettingsBase.cs +++ b/DNN Platform/Modules/Groups/GroupsSettingsBase.cs @@ -6,6 +6,5 @@ namespace DotNetNuke.Modules.Groups using DotNetNuke.Entities.Modules; public class GroupsSettingsBase : ModuleSettingsBase - { - } + {} } diff --git a/DNN Platform/Modules/Groups/List.ascx.cs b/DNN Platform/Modules/Groups/List.ascx.cs index 75a67bb5311..8a67d0c2dca 100644 --- a/DNN Platform/Modules/Groups/List.ascx.cs +++ b/DNN Platform/Modules/Groups/List.ascx.cs @@ -17,9 +17,9 @@ public List() { this._navigationManager = this.DependencyProvider.GetRequiredService(); } - + public INavigationManager _navigationManager { get; } - + protected void Page_Load(object sender, EventArgs e) { ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); @@ -44,7 +44,7 @@ protected void Page_Load(object sender, EventArgs e) { this.ctlGroupList.SortDirection = this.GroupListSortDirection; } - + if (!string.IsNullOrEmpty(this.GroupListTemplate)) { this.ctlGroupList.ItemTemplate = this.GroupListTemplate; @@ -58,11 +58,11 @@ protected void Page_Load(object sender, EventArgs e) protected void btnSearch_Click(object sender, EventArgs e) { - if (!this.Page.IsValid) - { - return; - } - + if (!this.Page.IsValid) + { + return; + } + this.Response.Redirect(this._navigationManager.NavigateURL(this.TabId, string.Empty, "filter=" + this.txtFilter.Text.Trim())); } } diff --git a/DNN Platform/Modules/Groups/ListSettings.ascx.cs b/DNN Platform/Modules/Groups/ListSettings.ascx.cs index a90f79acc18..ab217609523 100644 --- a/DNN Platform/Modules/Groups/ListSettings.ascx.cs +++ b/DNN Platform/Modules/Groups/ListSettings.ascx.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Modules.Groups ///
    /// ----------------------------------------------------------------------------- public partial class ListSettings : GroupsSettingsBase - { + { /// ----------------------------------------------------------------------------- /// /// LoadSettings loads the settings from the Database and displays them. @@ -37,17 +37,17 @@ public override void LoadSettings() this.BindGroups(); this.BindPages(); - if (this.Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) + if (this.Settings.ContainsKey(Constants.DefaultRoleGroupSetting)) { this.drpRoleGroup.SelectedIndex = this.drpRoleGroup.Items.IndexOf(this.drpRoleGroup.Items.FindByValue(this.Settings[Constants.DefaultRoleGroupSetting].ToString())); } - if (this.Settings.ContainsKey(Constants.GroupViewPage)) + if (this.Settings.ContainsKey(Constants.GroupViewPage)) { this.drpGroupViewPage.SelectedIndex = this.drpGroupViewPage.Items.IndexOf(this.drpGroupViewPage.Items.FindByValue(this.Settings[Constants.GroupViewPage].ToString())); } - if (this.Settings.ContainsKey(Constants.GroupListTemplate)) + if (this.Settings.ContainsKey(Constants.GroupListTemplate)) { this.txtListTemplate.Text = this.Settings[Constants.GroupListTemplate].ToString(); } @@ -62,7 +62,7 @@ public override void LoadSettings() this.chkGroupModeration.Checked = Convert.ToBoolean(this.Settings[Constants.GroupModerationEnabled].ToString()); } - if (this.Settings.ContainsKey(Constants.GroupLoadView)) + if (this.Settings.ContainsKey(Constants.GroupLoadView)) { this.drpViewMode.SelectedIndex = this.drpViewMode.Items.IndexOf(this.drpViewMode.Items.FindByValue(this.Settings[Constants.GroupLoadView].ToString())); } @@ -124,21 +124,21 @@ public override void UpdateSettings() { Exceptions.ProcessModuleLoadException(this, exc); } - } - - private void BindGroups() + } + + private void BindGroups() { var arrGroups = RoleController.GetRoleGroups(this.PortalId); this.drpRoleGroup.Items.Add(new ListItem(Localization.GetString("AllRoles"), "-2")); this.drpRoleGroup.Items.Add(new ListItem(Localization.GetString("GlobalRoles"), "-1")); - foreach (RoleGroupInfo roleGroup in arrGroups) + foreach (RoleGroupInfo roleGroup in arrGroups) { this.drpRoleGroup.Items.Add(new ListItem(roleGroup.RoleGroupName, roleGroup.RoleGroupID.ToString())); } } - - private void BindPages() + + private void BindPages() { foreach (ModuleInfo moduleInfo in ModuleController.Instance.GetModules(this.PortalId)) { diff --git a/DNN Platform/Modules/Groups/Loader.ascx.cs b/DNN Platform/Modules/Groups/Loader.ascx.cs index ed49efe9cb3..e3810b20825 100644 --- a/DNN Platform/Modules/Groups/Loader.ascx.cs +++ b/DNN Platform/Modules/Groups/Loader.ascx.cs @@ -15,10 +15,10 @@ namespace DotNetNuke.Modules.Groups public partial class Loader : GroupsModuleBase { - protected void Page_Load(object sender, EventArgs e) + protected void Page_Load(object sender, EventArgs e) { string path = Constants.ModulePath; - switch (this.LoadView) + switch (this.LoadView) { case GroupMode.Setup: path += "Setup.ascx"; @@ -30,7 +30,7 @@ protected void Page_Load(object sender, EventArgs e) path += "GroupView.ascx"; break; } - + GroupsModuleBase ctl = new GroupsModuleBase(); ctl = (GroupsModuleBase)this.LoadControl(path); ctl.ModuleConfiguration = this.ModuleConfiguration; diff --git a/DNN Platform/Modules/Groups/ModerationServiceController.cs b/DNN Platform/Modules/Groups/ModerationServiceController.cs index 32f230b2ed5..1979ef531ec 100644 --- a/DNN Platform/Modules/Groups/ModerationServiceController.cs +++ b/DNN Platform/Modules/Groups/ModerationServiceController.cs @@ -30,8 +30,6 @@ public class ModerationServiceController : DnnApiController 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,6 +39,8 @@ public ModerationServiceController(INavigationManager navigationManager) this.NavigationManager = navigationManager; } + protected INavigationManager NavigationManager { get; } + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage ApproveGroup(NotificationDTO postData) @@ -48,27 +48,27 @@ public HttpResponseMessage ApproveGroup(NotificationDTO postData) try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); - if (recipient == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - } - + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); this.ParseKey(notification.Context); if (this._roleInfo == null) { return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); } - + if (!this.IsMod()) { return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); } - + this._roleInfo.Status = RoleStatus.Approved; RoleController.Instance.UpdateRole(this._roleInfo); var roleCreator = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); - + // Update the original creator's role RoleController.Instance.UpdateUserRole(this.PortalSettings.PortalId, roleCreator.UserID, this._roleInfo.RoleID, RoleStatus.Approved, true, false); GroupUtilities.CreateJournalEntry(this._roleInfo, roleCreator); @@ -94,23 +94,23 @@ public HttpResponseMessage RejectGroup(NotificationDTO postData) try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); - if (recipient == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - } - + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); this.ParseKey(notification.Context); if (this._roleInfo == null) { return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate role"); } - + if (!this.IsMod()) { return this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Not Authorized!"); } - + var notifications = new Notifications(); var roleCreator = UserController.GetUserById(this.PortalSettings.PortalId, this._roleInfo.CreatedByUserID); var siteAdmin = UserController.GetUserById(this.PortalSettings.PortalId, this.PortalSettings.AdministratorId); @@ -143,9 +143,9 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) { var requireApproval = false; - if (this._roleInfo.Settings.ContainsKey("ReviewMembers")) - { - requireApproval = Convert.ToBoolean(this._roleInfo.Settings["ReviewMembers"]); + if (this._roleInfo.Settings.ContainsKey("ReviewMembers")) + { + requireApproval = Convert.ToBoolean(this._roleInfo.Settings["ReviewMembers"]); } if ((this._roleInfo.IsPublic || this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) && !requireApproval) @@ -156,7 +156,7 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) var url = this.NavigationManager.NavigateURL(postData.GroupViewTabId, string.Empty, new[] { "groupid=" + this._roleInfo.RoleID }); return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success", URL = url }); } - + if (this._roleInfo.IsPublic && requireApproval) { RoleController.Instance.AddUserRole(this.PortalSettings.PortalId, this.UserInfo.UserID, this._roleInfo.RoleID, RoleStatus.Pending, false, Null.NullDate, Null.NullDate); @@ -176,11 +176,6 @@ public HttpResponseMessage JoinGroup(RoleDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - public class NotificationDTO - { - public int NotificationId { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] @@ -201,7 +196,7 @@ public HttpResponseMessage LeaveGroup(RoleDTO postData) { RoleController.DeleteUserRole(this.UserInfo, this._roleInfo, this.PortalSettings, false); } - + success = true; } } @@ -227,11 +222,11 @@ public HttpResponseMessage ApproveMember(NotificationDTO postData) try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); - if (recipient == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - } - + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); this.ParseKey(notification.Context); if (this._memberId <= 0) @@ -259,7 +254,7 @@ public HttpResponseMessage ApproveMember(NotificationDTO postData) return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - } + } catch (Exception exc) { Logger.Error(exc); @@ -268,7 +263,7 @@ public HttpResponseMessage ApproveMember(NotificationDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unknown Error"); } - + [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage RejectMember(NotificationDTO postData) @@ -276,25 +271,25 @@ public HttpResponseMessage RejectMember(NotificationDTO postData) try { var recipient = InternalMessagingController.Instance.GetMessageRecipient(postData.NotificationId, this.UserInfo.UserID); - if (recipient == null) - { - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); - } - + if (recipient == null) + { + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate recipient"); + } + var notification = NotificationsController.Instance.GetNotification(postData.NotificationId); this.ParseKey(notification.Context); if (this._memberId <= 0) { return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Member"); } - + if (this._roleInfo == null) { return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unable to locate Role"); } var member = UserController.GetUserById(this.PortalSettings.PortalId, this._memberId); - + if (member != null) { RoleController.DeleteUserRole(member, this._roleInfo, this.PortalSettings, false); @@ -305,7 +300,7 @@ public HttpResponseMessage RejectMember(NotificationDTO postData) return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); } - } + } catch (Exception exc) { Logger.Error(exc); @@ -315,13 +310,6 @@ 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; @@ -340,7 +328,7 @@ private void ParseKey(string key) this._memberId = Convert.ToInt32(keys[3]); } } - + if (this._roleId > 0) { this._roleInfo = RoleController.Instance.GetRoleById(this.PortalSettings.PortalId, this._roleId); @@ -352,5 +340,17 @@ private bool IsMod() var objModulePermissions = new ModulePermissionCollection(CBO.FillCollection(DataProvider.Instance().GetModulePermissionsByModuleID(this._moduleId, -1), typeof(ModulePermissionInfo))); return ModulePermissionController.HasModulePermission(objModulePermissions, "MODGROUP"); } + + public class NotificationDTO + { + public int NotificationId { get; set; } + } + + public class RoleDTO + { + public int RoleId { get; set; } + + public int GroupViewTabId { get; set; } + } } } diff --git a/DNN Platform/Modules/Groups/View.ascx.cs b/DNN Platform/Modules/Groups/View.ascx.cs index 00950eca756..7c0a840c564 100644 --- a/DNN Platform/Modules/Groups/View.ascx.cs +++ b/DNN Platform/Modules/Groups/View.ascx.cs @@ -25,12 +25,12 @@ namespace DotNetNuke.Modules.Groups public partial class View : GroupsModuleBase { private readonly INavigationManager _navigationManager; - + public View() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + protected override void OnInit(EventArgs e) { this.InitializeComponent(); @@ -41,7 +41,7 @@ private void InitializeComponent() { this.Load += this.Page_Load; } - + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -52,14 +52,14 @@ private void Page_Load(object sender, EventArgs e) try { JavaScript.RequestRegistration(CommonJs.DnnPlugins); - if (this.GroupId < 0) + if (this.GroupId < 0) { - if (this.TabId != this.GroupListTabId && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) - { + if (this.TabId != this.GroupListTabId && !this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName)) + { this.Response.Redirect(this._navigationManager.NavigateURL(this.GroupListTabId)); } } - + GroupsModuleBase ctl = (GroupsModuleBase)this.LoadControl(this.ControlPath); ctl.ModuleConfiguration = this.ModuleConfiguration; this.plhContent.Controls.Clear(); @@ -69,6 +69,6 @@ private void Page_Load(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs b/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs index 56eacafcc99..dbeae2bcd52 100644 --- a/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs +++ b/DNN Platform/Modules/HTML/Components/CompareWorkflowStatePermissions.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Security.Permissions /// WorkflowStatePermissionInfo objects. /// internal class CompareWorkflowStatePermissions : IComparer - { + { public int Compare(object x, object y) { return ((WorkflowStatePermissionInfo)x).WorkflowStatePermissionID.CompareTo(((WorkflowStatePermissionInfo)y).WorkflowStatePermissionID); - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/DataProvider.cs b/DNN Platform/Modules/HTML/Components/DataProvider.cs index 05f066e33a7..48cfae2417d 100644 --- a/DNN Platform/Modules/HTML/Components/DataProvider.cs +++ b/DNN Platform/Modules/HTML/Components/DataProvider.cs @@ -14,8 +14,8 @@ namespace DotNetNuke.Modules.Html.Components /// /// public class DataProvider - { - // singleton reference to the instantiated object + { + // singleton reference to the instantiated object private static readonly DataProvider provider; // constructor @@ -28,8 +28,8 @@ static DataProvider() public static DataProvider Instance() { return provider; - } - + } + public virtual IDataReader GetHtmlText(int ModuleID, int ItemID) { return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetHtmlText", ModuleID, ItemID); @@ -103,6 +103,6 @@ public virtual IDataReader GetWorkflowStatePermissions() public virtual IDataReader GetWorkflowStatePermissionsByStateID(int StateID) { return DotNetNuke.Data.DataProvider.Instance().ExecuteReader("GetWorkflowStatePermissionsByStateID", StateID); - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs b/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs index 13ab8d69807..ca768ede578 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlModuleBase.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Modules.Html.Components public class HtmlModuleBase : PortalModuleBase { private HtmlModuleSettings _settings; - + public new HtmlModuleSettings Settings { get @@ -24,10 +24,10 @@ public class HtmlModuleBase : PortalModuleBase var repo = new HtmlModuleSettingsRepository(); this._settings = repo.GetSettings(this.ModuleConfiguration); } - + return this._settings; } - + set { this._settings = value; } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs b/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs index 16bbff5ac35..0be8bc5ad4d 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlModuleSettings.cs @@ -38,6 +38,5 @@ public class HtmlModuleSettings /// The used for storing and retrieving . /// public class HtmlModuleSettingsRepository : SettingsRepository - { - } + {} } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs index 3ab6195d0b8..2278a94c4e9 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextController.cs @@ -213,197 +213,6 @@ public void DeleteHtmlText(int ModuleID, int ItemID) ModuleController.SynchronizeModule(ModuleID); } - private static void AddHtmlNotification(string subject, string body, UserInfo user) - { - var notificationType = NotificationsController.Instance.GetNotificationType("HtmlNotification"); - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var sender = UserController.GetUserById(portalSettings.PortalId, portalSettings.AdministratorId); - - var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID }; - NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, null, new List { user }); - } - - private void ClearModuleSettings(ModuleInfo objModule) - { - if (objModule.ModuleDefinition.FriendlyName == "Text/HTML") - { - ModuleController.Instance.DeleteModuleSetting(objModule.ModuleID, "WorkFlowID"); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// CreateUserNotifications creates HtmlTextUser records and optionally sends email notifications to participants in a Workflow. - /// - /// - /// - /// An HtmlTextInfo object. - private void CreateUserNotifications(HtmlTextInfo objHtmlText) - { - var _htmlTextUserController = new HtmlTextUserController(); - HtmlTextUserInfo _htmlTextUser = null; - UserInfo _user = null; - - // clean up old user notification records - _htmlTextUserController.DeleteHtmlTextUsers(); - - // ensure we have latest htmltext object loaded - objHtmlText = this.GetHtmlText(objHtmlText.ModuleID, objHtmlText.ItemID); - - // build collection of users to notify - var objWorkflow = new WorkflowStateController(); - var arrUsers = new ArrayList(); - - // if not published - if (objHtmlText.IsPublished == false) - { - arrUsers.Add(objHtmlText.CreatedByUserID); // include content owner - } - - // if not draft and not published - if (objHtmlText.StateID != objWorkflow.GetFirstWorkflowStateID(objHtmlText.WorkflowID) && objHtmlText.IsPublished == false) - { - // get users from permissions for state - foreach (WorkflowStatePermissionInfo permission in WorkflowStatePermissionController.GetWorkflowStatePermissions(objHtmlText.StateID)) - { - if (permission.AllowAccess) - { - if (Null.IsNull(permission.UserID)) - { - int roleId = permission.RoleID; - RoleInfo objRole = RoleController.Instance.GetRole(objHtmlText.PortalID, r => r.RoleID == roleId); - if (objRole != null) - { - foreach (UserRoleInfo objUserRole in RoleController.Instance.GetUserRoles(objHtmlText.PortalID, null, objRole.RoleName)) - { - if (!arrUsers.Contains(objUserRole.UserID)) - { - arrUsers.Add(objUserRole.UserID); - } - } - } - } - else - { - if (!arrUsers.Contains(permission.UserID)) - { - arrUsers.Add(permission.UserID); - } - } - } - } - } - - // process notifications - if (arrUsers.Count > 0 || (objHtmlText.IsPublished && objHtmlText.Notify)) - { - // get tabid from module - ModuleInfo objModule = ModuleController.Instance.GetModule(objHtmlText.ModuleID, Null.NullInteger, true); - - PortalSettings objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (objPortalSettings != null) - { - string strResourceFile = string.Format( - "{0}/DesktopModules/{1}/{2}/{3}", - Globals.ApplicationPath, - objModule.DesktopModule.FolderName, - Localization.LocalResourceDirectory, - Localization.LocalSharedResourceFile); - string strSubject = Localization.GetString("NotificationSubject", strResourceFile); - string strBody = Localization.GetString("NotificationBody", strResourceFile); - strBody = strBody.Replace("[URL]", this.NavigationManager.NavigateURL(objModule.TabID)); - strBody = strBody.Replace("[STATE]", objHtmlText.StateName); - - // process user notification collection - foreach (int intUserID in arrUsers) - { - // create user notification record - _htmlTextUser = new HtmlTextUserInfo(); - _htmlTextUser.ItemID = objHtmlText.ItemID; - _htmlTextUser.StateID = objHtmlText.StateID; - _htmlTextUser.ModuleID = objHtmlText.ModuleID; - _htmlTextUser.TabID = objModule.TabID; - _htmlTextUser.UserID = intUserID; - _htmlTextUserController.AddHtmlTextUser(_htmlTextUser); - - // send an email notification to a user if the state indicates to do so - if (objHtmlText.Notify) - { - _user = UserController.GetUserById(objHtmlText.PortalID, intUserID); - if (_user != null) - { - AddHtmlNotification(strSubject, strBody, _user); - } - } - } - - // if published and the published state specifies to notify members of the workflow - if (objHtmlText.IsPublished && objHtmlText.Notify) - { - // send email notification to the author - _user = UserController.GetUserById(objHtmlText.PortalID, objHtmlText.CreatedByUserID); - if (_user != null) - { - try - { - Services.Mail.Mail.SendEmail(objPortalSettings.Email, objPortalSettings.Email, strSubject, strBody); - } - catch (Exception exc) - { - Exceptions.LogException(exc); - } - } - } - } - } - } - - private string DeTokeniseLinks(string content, int portalId) - { - var portal = PortalController.Instance.GetPortal(portalId); - var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); - if (!portalRoot.StartsWith("/")) - { - portalRoot = "/" + portalRoot; - } - - if (!portalRoot.EndsWith("/")) - { - portalRoot = portalRoot + "/"; - } - - content = Regex.Replace(content, PortalRootToken + "\\/{0,1}", portalRoot, RegexOptions.IgnoreCase); - - return content; - } - - private string TokeniseLinks(string content, int portalId) - { - // Replace any relative portal root reference by a token "{{PortalRoot}}" - var portal = PortalController.Instance.GetPortal(portalId); - var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); - if (!portalRoot.StartsWith("/")) - { - portalRoot = "/" + portalRoot; - } - - if (!portalRoot.EndsWith("/")) - { - portalRoot = portalRoot + "/"; - } - - // Portal Root regular expression - var regex = @"(? - (? - (?[A-Za-z]{3,9}:(?:\/\/)?) - (?(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+))? - (?" + portalRoot + "))"; - - var matchEvaluator = new MatchEvaluator(this.ReplaceWithRootToken); - var exp = RegexUtils.GetCachedRegex(regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - return exp.Replace(content, matchEvaluator); - } - /// ----------------------------------------------------------------------------- /// /// GetAllHtmlText gets a collection of HtmlTextInfo objects for the Module and Workflow. @@ -851,6 +660,16 @@ public string UpgradeModule(string Version) return string.Empty; } + private static void AddHtmlNotification(string subject, string body, UserInfo user) + { + var notificationType = NotificationsController.Instance.GetNotificationType("HtmlNotification"); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var sender = UserController.GetUserById(portalSettings.PortalId, portalSettings.AdministratorId); + + var notification = new Notification { NotificationTypeID = notificationType.NotificationTypeId, Subject = subject, Body = body, IncludeDismissAction = true, SenderUserID = sender.UserID }; + NotificationsController.Instance.SendNotification(notification, portalSettings.PortalId, null, new List { user }); + } + private static List CollectHierarchicalTags(List terms) { Func, List, List> collectTagsFunc = null; @@ -871,6 +690,187 @@ private static List CollectHierarchicalTags(List terms) return collectTagsFunc(terms, new List()); } + private void ClearModuleSettings(ModuleInfo objModule) + { + if (objModule.ModuleDefinition.FriendlyName == "Text/HTML") + { + ModuleController.Instance.DeleteModuleSetting(objModule.ModuleID, "WorkFlowID"); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// CreateUserNotifications creates HtmlTextUser records and optionally sends email notifications to participants in a Workflow. + /// + /// + /// + /// An HtmlTextInfo object. + private void CreateUserNotifications(HtmlTextInfo objHtmlText) + { + var _htmlTextUserController = new HtmlTextUserController(); + HtmlTextUserInfo _htmlTextUser = null; + UserInfo _user = null; + + // clean up old user notification records + _htmlTextUserController.DeleteHtmlTextUsers(); + + // ensure we have latest htmltext object loaded + objHtmlText = this.GetHtmlText(objHtmlText.ModuleID, objHtmlText.ItemID); + + // build collection of users to notify + var objWorkflow = new WorkflowStateController(); + var arrUsers = new ArrayList(); + + // if not published + if (objHtmlText.IsPublished == false) + { + arrUsers.Add(objHtmlText.CreatedByUserID); // include content owner + } + + // if not draft and not published + if (objHtmlText.StateID != objWorkflow.GetFirstWorkflowStateID(objHtmlText.WorkflowID) && objHtmlText.IsPublished == false) + { + // get users from permissions for state + foreach (WorkflowStatePermissionInfo permission in WorkflowStatePermissionController.GetWorkflowStatePermissions(objHtmlText.StateID)) + { + if (permission.AllowAccess) + { + if (Null.IsNull(permission.UserID)) + { + int roleId = permission.RoleID; + RoleInfo objRole = RoleController.Instance.GetRole(objHtmlText.PortalID, r => r.RoleID == roleId); + if (objRole != null) + { + foreach (UserRoleInfo objUserRole in RoleController.Instance.GetUserRoles(objHtmlText.PortalID, null, objRole.RoleName)) + { + if (!arrUsers.Contains(objUserRole.UserID)) + { + arrUsers.Add(objUserRole.UserID); + } + } + } + } + else + { + if (!arrUsers.Contains(permission.UserID)) + { + arrUsers.Add(permission.UserID); + } + } + } + } + } + + // process notifications + if (arrUsers.Count > 0 || (objHtmlText.IsPublished && objHtmlText.Notify)) + { + // get tabid from module + ModuleInfo objModule = ModuleController.Instance.GetModule(objHtmlText.ModuleID, Null.NullInteger, true); + + PortalSettings objPortalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (objPortalSettings != null) + { + string strResourceFile = string.Format( + "{0}/DesktopModules/{1}/{2}/{3}", + Globals.ApplicationPath, + objModule.DesktopModule.FolderName, + Localization.LocalResourceDirectory, + Localization.LocalSharedResourceFile); + string strSubject = Localization.GetString("NotificationSubject", strResourceFile); + string strBody = Localization.GetString("NotificationBody", strResourceFile); + strBody = strBody.Replace("[URL]", this.NavigationManager.NavigateURL(objModule.TabID)); + strBody = strBody.Replace("[STATE]", objHtmlText.StateName); + + // process user notification collection + foreach (int intUserID in arrUsers) + { + // create user notification record + _htmlTextUser = new HtmlTextUserInfo(); + _htmlTextUser.ItemID = objHtmlText.ItemID; + _htmlTextUser.StateID = objHtmlText.StateID; + _htmlTextUser.ModuleID = objHtmlText.ModuleID; + _htmlTextUser.TabID = objModule.TabID; + _htmlTextUser.UserID = intUserID; + _htmlTextUserController.AddHtmlTextUser(_htmlTextUser); + + // send an email notification to a user if the state indicates to do so + if (objHtmlText.Notify) + { + _user = UserController.GetUserById(objHtmlText.PortalID, intUserID); + if (_user != null) + { + AddHtmlNotification(strSubject, strBody, _user); + } + } + } + + // if published and the published state specifies to notify members of the workflow + if (objHtmlText.IsPublished && objHtmlText.Notify) + { + // send email notification to the author + _user = UserController.GetUserById(objHtmlText.PortalID, objHtmlText.CreatedByUserID); + if (_user != null) + { + try + { + Services.Mail.Mail.SendEmail(objPortalSettings.Email, objPortalSettings.Email, strSubject, strBody); + } + catch (Exception exc) + { + Exceptions.LogException(exc); + } + } + } + } + } + } + + private string DeTokeniseLinks(string content, int portalId) + { + var portal = PortalController.Instance.GetPortal(portalId); + var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); + if (!portalRoot.StartsWith("/")) + { + portalRoot = "/" + portalRoot; + } + + if (!portalRoot.EndsWith("/")) + { + portalRoot = portalRoot + "/"; + } + + content = Regex.Replace(content, PortalRootToken + "\\/{0,1}", portalRoot, RegexOptions.IgnoreCase); + + return content; + } + + private string TokeniseLinks(string content, int portalId) + { + // Replace any relative portal root reference by a token "{{PortalRoot}}" + var portal = PortalController.Instance.GetPortal(portalId); + var portalRoot = UrlUtils.Combine(Globals.ApplicationPath, portal.HomeDirectory); + if (!portalRoot.StartsWith("/")) + { + portalRoot = "/" + portalRoot; + } + + if (!portalRoot.EndsWith("/")) + { + portalRoot = portalRoot + "/"; + } + + // Portal Root regular expression + var regex = @"(? + (? + (?[A-Za-z]{3,9}:(?:\/\/)?) + (?(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+))? + (?" + portalRoot + "))"; + + var matchEvaluator = new MatchEvaluator(this.ReplaceWithRootToken); + var exp = RegexUtils.GetCachedRegex(regex, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); + return exp.Replace(content, matchEvaluator); + } + private void AddNotificationTypes() { var type = new NotificationType { Name = "HtmlNotification", Description = "Html Module Notification" }; diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs b/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs index 779b6ad8afe..764900da1f8 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextInfo.cs @@ -36,7 +36,7 @@ public int ItemID { return this._ItemID; } - + set { this._ItemID = value; @@ -69,7 +69,7 @@ public bool IsActive { return this._IsActive; } - + set { this._IsActive = value; @@ -82,7 +82,7 @@ public string Comment { return this._Comment; } - + set { this._Comment = value; @@ -95,7 +95,7 @@ public bool Approved { return this._Approved; } - + set { this._Approved = value; diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs index 6bade8b65f0..e18bc10d2fc 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextLogController.cs @@ -22,14 +22,14 @@ namespace DotNetNuke.Modules.Html /// /// ----------------------------------------------------------------------------- public class HtmlTextLogController - { + { /// ----------------------------------------------------------------------------- /// /// GetHtmlTextLog retrieves a collection of HtmlTextLogInfo objects for an Item. /// /// /// - /// The Id of the Item. + /// The Id of the Item. /// /// ----------------------------------------------------------------------------- public ArrayList GetHtmlTextLog(int ItemID) @@ -48,6 +48,6 @@ public ArrayList GetHtmlTextLog(int ItemID) public void AddHtmlTextLog(HtmlTextLogInfo objHtmlTextLog) { DataProvider.Instance().AddHtmlTextLog(objHtmlTextLog.ItemID, objHtmlTextLog.StateID, objHtmlTextLog.Comment, objHtmlTextLog.Approved, UserController.Instance.GetCurrentUserInfo().UserID); - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs b/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs index 90fee4842da..0418a1ad296 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextUserController.cs @@ -21,14 +21,14 @@ namespace DotNetNuke.Modules.Html /// /// ----------------------------------------------------------------------------- public class HtmlTextUserController - { + { /// ----------------------------------------------------------------------------- /// /// GetHtmlTextUser retrieves a collection of HtmlTextUserInfo objects for an Item. /// /// /// - /// The Id of the User. + /// The Id of the User. /// /// ----------------------------------------------------------------------------- public ArrayList GetHtmlTextUser(int UserID) @@ -59,6 +59,6 @@ public void AddHtmlTextUser(HtmlTextUserInfo objHtmlTextUser) public void DeleteHtmlTextUsers() { DataProvider.Instance().DeleteHtmlTextUsers(); - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs b/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs index 688e6fbbc69..cc31860029c 100644 --- a/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs +++ b/DNN Platform/Modules/HTML/Components/HtmlTextUserInfo.cs @@ -21,17 +21,9 @@ namespace DotNetNuke.Modules.Html /// /// ----------------------------------------------------------------------------- public class HtmlTextUserInfo - { - // local property declarations - private ModuleInfo _Module; - - public int ItemID { get; set; } - - public int StateID { get; set; } - - public string StateName { get; set; } - - public int ModuleID { get; set; } + { + // local property declarations + private ModuleInfo _Module; public string ModuleTitle { @@ -42,7 +34,7 @@ public string ModuleTitle { _ModuleTitle = this.Module.ModuleTitle; } - + return _ModuleTitle; } } @@ -55,15 +47,23 @@ public ModuleInfo Module { this._Module = ModuleController.Instance.GetModule(this.ModuleID, this.TabID, false); } - + return this._Module; } } - + + public int ItemID { get; set; } + + public int StateID { get; set; } + + public string StateName { get; set; } + + public int ModuleID { get; set; } + public int TabID { get; set; } public int UserID { get; set; } - public DateTime CreatedOnDate { get; set; } + public DateTime CreatedOnDate { get; set; } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs index b662047dabc..7eae078f966 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStateController.cs @@ -26,15 +26,15 @@ public class WorkflowStateController private const string WORKFLOW_CACHE_KEY = "Workflow{0}"; private const int WORKFLOW_CACHE_TIMEOUT = 20; - private const CacheItemPriority WORKFLOW_CACHE_PRIORITY = CacheItemPriority.Normal; - + private const CacheItemPriority WORKFLOW_CACHE_PRIORITY = CacheItemPriority.Normal; + /// ----------------------------------------------------------------------------- /// /// GetWorkFlows retrieves a collection of workflows for the portal. /// /// /// - /// The ID of the Portal. + /// The ID of the Portal. /// /// ----------------------------------------------------------------------------- public ArrayList GetWorkflows(int PortalID) @@ -48,7 +48,7 @@ public ArrayList GetWorkflows(int PortalID) /// /// /// - /// The ID of the Workflow. + /// The ID of the Workflow. /// /// ----------------------------------------------------------------------------- public ArrayList GetWorkflowStates(int WorkflowID) @@ -63,7 +63,7 @@ public ArrayList GetWorkflowStates(int WorkflowID) ///
    /// /// - /// Arguments passed by the GetWorkflowStates method. + /// Arguments passed by the GetWorkflowStates method. /// /// ----------------------------------------------------------------------------- public object GetWorkflowStatesCallBack(CacheItemArgs cacheItemArgs) @@ -78,7 +78,7 @@ public object GetWorkflowStatesCallBack(CacheItemArgs cacheItemArgs) ///
    /// /// - /// The ID of the Workflow. + /// The ID of the Workflow. /// /// ----------------------------------------------------------------------------- public int GetFirstWorkflowStateID(int WorkflowID) @@ -89,7 +89,7 @@ public int GetFirstWorkflowStateID(int WorkflowID) { intStateID = ((WorkflowStateInfo)arrWorkflowStates[0]).StateID; } - + return intStateID; } @@ -100,7 +100,7 @@ public int GetFirstWorkflowStateID(int WorkflowID) /// /// /// The ID of the Workflow. - /// The ID of the State. + /// The ID of the State. /// /// ----------------------------------------------------------------------------- public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) @@ -130,7 +130,7 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) intPreviousStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } - + intItem = intItem - 1; } } @@ -151,7 +151,7 @@ public int GetPreviousWorkflowStateID(int WorkflowID, int StateID) /// /// /// The ID of the Workflow. - /// The ID of the State. + /// The ID of the State. /// /// ----------------------------------------------------------------------------- public int GetNextWorkflowStateID(int WorkflowID, int StateID) @@ -181,7 +181,7 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) intNextStateID = ((WorkflowStateInfo)arrWorkflowStates[intItem]).StateID; break; } - + intItem = intItem + 1; } } @@ -201,7 +201,7 @@ public int GetNextWorkflowStateID(int WorkflowID, int StateID) ///
    /// /// - /// The ID of the Workflow. + /// The ID of the Workflow. /// /// ----------------------------------------------------------------------------- public int GetLastWorkflowStateID(int WorkflowID) @@ -212,8 +212,8 @@ public int GetLastWorkflowStateID(int WorkflowID) { intStateID = ((WorkflowStateInfo)arrWorkflowStates[arrWorkflowStates.Count - 1]).StateID; } - + return intStateID; - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs b/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs index cb42d8b5e2c..8722212df35 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStateInfo.cs @@ -48,7 +48,7 @@ public bool IsActive { return this._IsActive; } - + set { this._IsActive = value; diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs index dba64ca00ee..9986ba077a0 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionCollection.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Security.Permissions /// ----------------------------------------------------------------------------- [Serializable] public class WorkflowStatePermissionCollection : CollectionBase - { + { public WorkflowStatePermissionCollection() { } @@ -46,21 +46,21 @@ public WorkflowStatePermissionCollection(ArrayList WorkflowStatePermissions, int this.Add(permission); } } - } - + } + public WorkflowStatePermissionInfo this[int index] { get { return (WorkflowStatePermissionInfo)this.List[index]; } - + set { this.List[index] = value; } - } - + } + public int Add(WorkflowStatePermissionInfo value) { return this.List.Add(value); @@ -84,13 +84,13 @@ public int Add(WorkflowStatePermissionInfo value, bool checkForDuplicates) break; } } - + if (!isMatch) { id = this.Add(value); } } - + return id; } @@ -116,7 +116,7 @@ public bool CompareTo(WorkflowStatePermissionCollection objWorkflowStatePermissi { return false; } - + this.InnerList.Sort(new CompareWorkflowStatePermissions()); objWorkflowStatePermissionCollection.InnerList.Sort(new CompareWorkflowStatePermissions()); @@ -171,13 +171,13 @@ public List ToList() { list.Add(permission); } - + return list; } public string ToString(string key) { return PermissionController.BuildPermissions(this.List, key); - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs index 46f213952f9..176ad84ccbc 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionController.cs @@ -29,13 +29,13 @@ public class WorkflowStatePermissionController public const CacheItemPriority WorkflowStatePermissionCachePriority = CacheItemPriority.Normal; public const int WorkflowStatePermissionCacheTimeOut = 20; - private static readonly DataProvider provider = DataProvider.Instance(); - + private static readonly DataProvider provider = DataProvider.Instance(); + /// ----------------------------------------------------------------------------- /// /// GetWorkflowStatePermissions gets a WorkflowStatePermissionCollection. /// - /// The ID of the State. + /// The ID of the State. /// /// ----------------------------------------------------------------------------- public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int StateID) @@ -52,27 +52,27 @@ public static WorkflowStatePermissionCollection GetWorkflowStatePermissions(int if (!bFound) { // try the database - WorkflowStatePermissions = new WorkflowStatePermissionCollection( + 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. + /// 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 @@ -81,7 +81,7 @@ public static bool HasWorkflowStatePermission(WorkflowStatePermissionCollection /// ----------------------------------------------------------------------------- private static Dictionary GetWorkflowStatePermissions() { - return CBO.GetCachedObject>( + return CBO.GetCachedObject>( new CacheItemArgs(WorkflowStatePermissionCacheKey, WorkflowStatePermissionCachePriority), GetWorkflowStatePermissionsCallBack); } @@ -147,8 +147,8 @@ private static Dictionary FillWorkflowSt dr.Close(); } } - + return dic; - } + } } } diff --git a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs index 41016d4b8e7..41a4ed2f23a 100644 --- a/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs +++ b/DNN Platform/Modules/HTML/Components/WorkflowStatePermissionInfo.cs @@ -25,10 +25,10 @@ public class WorkflowStatePermissionInfo : PermissionInfoBase, IHydratable { // local property declarations private int _StateID; - private int _WorkflowStatePermissionID; - + private int _WorkflowStatePermissionID; + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new WorkflowStatePermissionInfo. /// @@ -37,18 +37,18 @@ public WorkflowStatePermissionInfo() { this._WorkflowStatePermissionID = Null.NullInteger; this._StateID = Null.NullInteger; - } - - // New - + } + + // New + /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new WorkflowStatePermissionInfo. /// /// A PermissionInfo object. /// ----------------------------------------------------------------------------- - public WorkflowStatePermissionInfo(PermissionInfo permission) + public WorkflowStatePermissionInfo(PermissionInfo permission) : this() { this.ModuleDefID = permission.ModuleDefID; @@ -56,8 +56,8 @@ public WorkflowStatePermissionInfo(PermissionInfo permission) this.PermissionID = permission.PermissionID; this.PermissionKey = permission.PermissionKey; this.PermissionName = permission.PermissionName; - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the WorkflowState Permission ID. @@ -70,7 +70,7 @@ public int WorkflowStatePermissionID { return this._WorkflowStatePermissionID; } - + set { this._WorkflowStatePermissionID = value; @@ -89,12 +89,12 @@ public int StateID { return this._StateID; } - + set { this._StateID = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -108,13 +108,13 @@ public int KeyID { return this.WorkflowStatePermissionID; } - + set { this.WorkflowStatePermissionID = value; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Compares if two WorkflowStatePermissionInfo objects are equivalent/equal. @@ -135,17 +135,17 @@ public override bool Equals(object obj) { return false; } - + if (ReferenceEquals(this, obj)) { return true; } - + if (obj.GetType() != typeof(WorkflowStatePermissionInfo)) { return false; } - + return this.Equals((WorkflowStatePermissionInfo)obj); } @@ -155,12 +155,12 @@ public bool Equals(WorkflowStatePermissionInfo other) { return false; } - + if (ReferenceEquals(this, other)) { return true; } - + return (this.AllowAccess == other.AllowAccess) && (this.StateID == other.StateID) && (this.RoleID == other.RoleID) && (this.PermissionID == other.PermissionID); } @@ -170,8 +170,8 @@ public override int GetHashCode() { return (this._StateID * 397) ^ this._WorkflowStatePermissionID; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Fills a WorkflowStatePermissionInfo from a Data Reader. diff --git a/DNN Platform/Modules/HTML/EditHtml.ascx.cs b/DNN Platform/Modules/HTML/EditHtml.ascx.cs index ed9e00d5c75..a33da278256 100644 --- a/DNN Platform/Modules/HTML/EditHtml.ascx.cs +++ b/DNN Platform/Modules/HTML/EditHtml.ascx.cs @@ -288,6 +288,172 @@ protected void OnSaveClick(object sender, EventArgs e) } } + protected void OnEditClick(object sender, EventArgs e) + { + try + { + this.DisplayEdit(this.hfEditor.Value); + + if (this.phMasterContent.Visible) + { + this.DisplayMasterLanguageContent(); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnPreviewClick(object sender, EventArgs e) + { + try + { + if (this.phEdit.Visible) + { + this.hfEditor.Value = this.txtContent.Text; + } + + this.DisplayPreview(this.phEdit.Visible ? this.txtContent.Text : this.hfEditor.Value); + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnHistoryGridItemDataBound(object sender, GridViewRowEventArgs e) + { + var item = e.Row; + + if (item.RowType == DataControlRowType.DataRow) + { + // Localize columns + item.Cells[2].Text = Localization.GetString(item.Cells[2].Text, this.LocalResourceFile); + item.Cells[3].Text = Localization.GetString(item.Cells[3].Text, this.LocalResourceFile); + } + } + + protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs e) + { + try + { + HtmlTextInfo htmlContent; + + // disable delete button if user doesn't have delete rights??? + switch (e.CommandName.ToLowerInvariant()) + { + case "remove": + htmlContent = this.GetHTMLContent(e); + this._htmlTextController.DeleteHtmlText(this.ModuleId, htmlContent.ItemID); + break; + case "rollback": + htmlContent = this.GetHTMLContent(e); + htmlContent.ItemID = -1; + htmlContent.ModuleID = this.ModuleId; + htmlContent.WorkflowID = this.WorkflowID; + htmlContent.StateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); + this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); + break; + case "preview": + htmlContent = this.GetHTMLContent(e); + this.DisplayPreview(htmlContent); + break; + } + + if (e.CommandName.ToLowerInvariant() != "preview") + { + var latestContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); + if (latestContent == null) + { + this.DisplayInitialContent(this._workflowStateController.GetWorkflowStates(this.WorkflowID)[0] as WorkflowStateInfo); + } + else + { + this.DisplayContent(latestContent); + + // DisplayPreview(latestContent); + // DisplayVersions(); + } + } + + // Module failed to load + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e) + { + if (e.Row.RowType == DataControlRowType.DataRow) + { + var htmlContent = e.Row.DataItem as HtmlTextInfo; + var createdBy = "Default"; + + if (htmlContent.CreatedByUserID != -1) + { + var createdByByUser = UserController.GetUserById(this.PortalId, htmlContent.CreatedByUserID); + if (createdByByUser != null) + { + createdBy = createdByByUser.DisplayName; + } + } + + foreach (TableCell cell in e.Row.Cells) + { + foreach (Control cellControl in cell.Controls) + { + if (cellControl is ImageButton) + { + var imageButton = cellControl as ImageButton; + imageButton.CommandArgument = htmlContent.ItemID.ToString(); + switch (imageButton.CommandName.ToLowerInvariant()) + { + case "rollback": + // hide rollback for the first item + if (this.dgVersions.CurrentPageIndex == 0) + { + if (e.Row.RowIndex == 0) + { + imageButton.Visible = false; + break; + } + } + + imageButton.Visible = true; + + break; + case "remove": + var msg = this.GetLocalizedString("DeleteVersion.Confirm"); + msg = + msg.Replace("[VERSION]", htmlContent.Version.ToString()).Replace("[STATE]", htmlContent.StateName).Replace("[DATECREATED]", htmlContent.CreatedOnDate.ToString()) + .Replace("[USERNAME]", createdBy); + imageButton.OnClientClick = "return confirm(\"" + msg + "\");"; + + // hide the delete button + var showDelete = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); + + if (!showDelete) + { + showDelete = htmlContent.IsPublished == false; + } + + imageButton.Visible = showDelete; + break; + } + } + } + } + } + } + + protected void OnVersionsGridPageIndexChanged(object source, EventArgs e) + { + this.DisplayVersions(); + } + /// /// Displays the history of an html content item in a grid in the preview section. /// @@ -573,103 +739,6 @@ private void OnRenderSelectedIndexChanged(object sender, EventArgs e) this.txtContent.ChangeMode(this.ddlRender.SelectedValue); } - protected void OnEditClick(object sender, EventArgs e) - { - try - { - this.DisplayEdit(this.hfEditor.Value); - - if (this.phMasterContent.Visible) - { - this.DisplayMasterLanguageContent(); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnPreviewClick(object sender, EventArgs e) - { - try - { - if (this.phEdit.Visible) - { - this.hfEditor.Value = this.txtContent.Text; - } - - this.DisplayPreview(this.phEdit.Visible ? this.txtContent.Text : this.hfEditor.Value); - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - protected void OnHistoryGridItemDataBound(object sender, GridViewRowEventArgs e) - { - var item = e.Row; - - if (item.RowType == DataControlRowType.DataRow) - { - // Localize columns - item.Cells[2].Text = Localization.GetString(item.Cells[2].Text, this.LocalResourceFile); - item.Cells[3].Text = Localization.GetString(item.Cells[3].Text, this.LocalResourceFile); - } - } - - protected void OnVersionsGridItemCommand(object source, GridViewCommandEventArgs e) - { - try - { - HtmlTextInfo htmlContent; - - // disable delete button if user doesn't have delete rights??? - switch (e.CommandName.ToLowerInvariant()) - { - case "remove": - htmlContent = this.GetHTMLContent(e); - this._htmlTextController.DeleteHtmlText(this.ModuleId, htmlContent.ItemID); - break; - case "rollback": - htmlContent = this.GetHTMLContent(e); - htmlContent.ItemID = -1; - htmlContent.ModuleID = this.ModuleId; - htmlContent.WorkflowID = this.WorkflowID; - htmlContent.StateID = this._workflowStateController.GetFirstWorkflowStateID(this.WorkflowID); - this._htmlTextController.UpdateHtmlText(htmlContent, this._htmlTextController.GetMaximumVersionHistory(this.PortalId)); - break; - case "preview": - htmlContent = this.GetHTMLContent(e); - this.DisplayPreview(htmlContent); - break; - } - - if (e.CommandName.ToLowerInvariant() != "preview") - { - var latestContent = this._htmlTextController.GetTopHtmlText(this.ModuleId, false, this.WorkflowID); - if (latestContent == null) - { - this.DisplayInitialContent(this._workflowStateController.GetWorkflowStates(this.WorkflowID)[0] as WorkflowStateInfo); - } - else - { - this.DisplayContent(latestContent); - - // DisplayPreview(latestContent); - // DisplayVersions(); - } - } - - // Module failed to load - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - private void OnHistoryClick(object sender, EventArgs e) { try @@ -707,75 +776,6 @@ private void OnMasterContentClick(object sender, EventArgs e) } } - protected void OnVersionsGridItemDataBound(object sender, GridViewRowEventArgs e) - { - if (e.Row.RowType == DataControlRowType.DataRow) - { - var htmlContent = e.Row.DataItem as HtmlTextInfo; - var createdBy = "Default"; - - if (htmlContent.CreatedByUserID != -1) - { - var createdByByUser = UserController.GetUserById(this.PortalId, htmlContent.CreatedByUserID); - if (createdByByUser != null) - { - createdBy = createdByByUser.DisplayName; - } - } - - foreach (TableCell cell in e.Row.Cells) - { - foreach (Control cellControl in cell.Controls) - { - if (cellControl is ImageButton) - { - var imageButton = cellControl as ImageButton; - imageButton.CommandArgument = htmlContent.ItemID.ToString(); - switch (imageButton.CommandName.ToLowerInvariant()) - { - case "rollback": - // hide rollback for the first item - if (this.dgVersions.CurrentPageIndex == 0) - { - if (e.Row.RowIndex == 0) - { - imageButton.Visible = false; - break; - } - } - - imageButton.Visible = true; - - break; - case "remove": - var msg = this.GetLocalizedString("DeleteVersion.Confirm"); - msg = - msg.Replace("[VERSION]", htmlContent.Version.ToString()).Replace("[STATE]", htmlContent.StateName).Replace("[DATECREATED]", htmlContent.CreatedOnDate.ToString()) - .Replace("[USERNAME]", createdBy); - imageButton.OnClientClick = "return confirm(\"" + msg + "\");"; - - // hide the delete button - var showDelete = this.UserInfo.IsSuperUser || PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); - - if (!showDelete) - { - showDelete = htmlContent.IsPublished == false; - } - - imageButton.Visible = showDelete; - break; - } - } - } - } - } - } - - 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())); diff --git a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs index 483a1a2352a..868a988ff1c 100644 --- a/DNN Platform/Modules/HTML/HtmlModule.ascx.cs +++ b/DNN Platform/Modules/HTML/HtmlModule.ascx.cs @@ -29,16 +29,15 @@ namespace DotNetNuke.Modules.Html /// ----------------------------------------------------------------------------- public partial class HtmlModule : HtmlModuleBase, IActionable { + private readonly INavigationManager _navigationManager; private bool EditorEnabled; private int WorkflowID; - private readonly INavigationManager _navigationManager; - public HtmlModule() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets moduleActions is an interface property that returns the module actions collection for the module. @@ -52,7 +51,7 @@ public ModuleActionCollection ModuleActions { // add the Edit Text action var Actions = new ModuleActionCollection(); - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, @@ -79,7 +78,7 @@ public ModuleActionCollection ModuleActions if (objWorkflow.GetWorkflowStates(this.WorkflowID).Count > 1) { // add publish action - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString("PublishContent.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -101,7 +100,7 @@ public ModuleActionCollection ModuleActions if (WorkflowStatePermissionController.HasWorkflowStatePermission(WorkflowStatePermissionController.GetWorkflowStatePermissions(objContent.StateID), "REVIEW")) { // add approve and reject actions - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString("ApproveContent.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -112,7 +111,7 @@ public ModuleActionCollection ModuleActions SecurityAccessLevel.Edit, true, false); - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString("RejectContent.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -129,7 +128,7 @@ public ModuleActionCollection ModuleActions } // add mywork to action menu - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString("MyWork.Action", this.LocalResourceFile), "MyWork.Action", @@ -143,8 +142,8 @@ public ModuleActionCollection ModuleActions return Actions; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Init runs when the control is initialized. @@ -358,6 +357,6 @@ private void ModuleAction_Click(object sender, ActionEventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Modules/HTML/MyWork.ascx.cs b/DNN Platform/Modules/HTML/MyWork.ascx.cs index db11ea0da71..f37ce921ee6 100644 --- a/DNN Platform/Modules/HTML/MyWork.ascx.cs +++ b/DNN Platform/Modules/HTML/MyWork.ascx.cs @@ -19,18 +19,18 @@ namespace DotNetNuke.Modules.Html public partial class MyWork : PortalModuleBase { private readonly INavigationManager _navigationManager; - + public MyWork() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + public string FormatURL(object dataItem) { var objHtmlTextUser = (HtmlTextUserInfo)dataItem; return "" + objHtmlTextUser.ModuleTitle + " ( " + objHtmlTextUser.StateName + " )"; - } - + } + /// /// Page_Load runs when the control is loaded. /// @@ -54,6 +54,6 @@ protected override void OnLoad(EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Modules/HTML/Settings.ascx.cs b/DNN Platform/Modules/HTML/Settings.ascx.cs index 7922315633c..dd83c3a8b9f 100644 --- a/DNN Platform/Modules/HTML/Settings.ascx.cs +++ b/DNN Platform/Modules/HTML/Settings.ascx.cs @@ -20,15 +20,15 @@ namespace DotNetNuke.Modules.Html public partial class Settings : ModuleSettingsBase { private HtmlModuleSettings _moduleSettings; - + private new HtmlModuleSettings ModuleSettings { get { return this._moduleSettings ?? (this._moduleSettings = new HtmlModuleSettingsRepository().GetSettings(this.ModuleConfiguration)); } - } - + } + /// /// LoadSettings loads the settings from the Database and displays them. /// @@ -55,7 +55,7 @@ public override void LoadSettings() workflows.Add(state); } } - + this.cboWorkflow.DataSource = workflows; this.cboWorkflow.DataBind(); var workflow = htmlTextController.GetWorkflow(this.ModuleId, this.TabId, this.PortalId); @@ -63,9 +63,9 @@ public override void LoadSettings() { this.cboWorkflow.FindItemByValue(workflow.Value.ToString()).Selected = true; } - + this.DisplayWorkflowDetails(); - + if (this.rblApplyTo.Items.FindByValue(workflow.Key) != null) { this.rblApplyTo.Items.FindByValue(workflow.Key).Selected = true; @@ -73,7 +73,7 @@ public override void LoadSettings() this.txtSearchDescLength.Text = this.ModuleSettings.SearchDescLength.ToString(); } - + // Module failed to load } catch (Exception exc) @@ -129,8 +129,8 @@ public override void UpdateSettings() { Exceptions.ProcessModuleLoadException(this, exc); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -140,8 +140,8 @@ protected override void OnLoad(EventArgs e) protected void OnWorkflowSelectedIndexChanged(object sender, EventArgs e) { this.DisplayWorkflowDetails(); - } - + } + private void DisplayWorkflowDetails() { if (this.cboWorkflow.SelectedValue != null) @@ -155,12 +155,12 @@ private void DisplayWorkflowDetails() { 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 f31330f2029..5ede286411a 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Components/UpgradeController.cs @@ -161,41 +161,6 @@ 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"); @@ -237,5 +202,40 @@ private static string UpdateTelerikEncryptionKey(string keyName) return strError; } + + /// 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")); + } } } diff --git a/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs b/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs index 07a56295685..e6014ebe508 100644 --- a/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs +++ b/DNN Platform/Modules/HtmlEditorManager/Controls/InvalidConfiguration.ascx.cs @@ -10,6 +10,5 @@ namespace DotNetNuke.Modules.HtmlEditorManager.Views /// Control to display information about provider not being supported. ///
    public partial class InvalidConfiguration : PortalModuleBase - { - } + {} } diff --git a/DNN Platform/Modules/Journal/Components/FeatureController.cs b/DNN Platform/Modules/Journal/Components/FeatureController.cs index 455c2a76fff..14dd3223e08 100644 --- a/DNN Platform/Modules/Journal/Components/FeatureController.cs +++ b/DNN Platform/Modules/Journal/Components/FeatureController.cs @@ -47,18 +47,18 @@ public class FeatureController : ModuleSearchBase, IModuleSearchResultController public FeatureController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); - } - + } + protected INavigationManager NavigationManager { get; } - + /// ----------------------------------------------------------------------------- /// /// ExportModule implements the IPortable ExportModule Interface. /// - /// The Id of the module to be exported. + /// The Id of the module to be exported. /// /// ----------------------------------------------------------------------------- - public string ExportModule(int moduleID) + public string ExportModule(int moduleID) { // string strXML = ""; @@ -89,7 +89,7 @@ public string ExportModule(int moduleID) /// The version of the module to be imported. /// The Id of the user performing the import. /// ----------------------------------------------------------------------------- - public void ImportModule(int moduleID, string content, string version, int userId) + public void ImportModule(int moduleID, string content, string version, int userId) { // XmlNode xmlJournals = DotNetNuke.Common.Globals.GetContent(Content, "Journals"); // foreach (XmlNode xmlJournal in xmlJournals.SelectNodes("Journal")) @@ -107,14 +107,14 @@ public void ImportModule(int moduleID, string content, string version, int userI /// /// UpgradeModule implements the IUpgradeable Interface. /// - /// The current version of the module. + /// The current version of the module. /// /// ----------------------------------------------------------------------------- - public string UpgradeModule(string version) + public string UpgradeModule(string version) { throw new NotImplementedException("The method or operation is not implemented."); - } - + } + public override IList GetModifiedSearchDocuments(ModuleInfo moduleInfo, DateTime beginDateUtc) { var searchDocuments = new Dictionary(); @@ -132,7 +132,7 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu while (reader.Read()) { var journalId = Convert.ToInt32(reader["JournalId"]); - + // var journalTypeId = reader["JournalTypeId"].ToString(); var userId = Convert.ToInt32(reader["UserId"]); var dateUpdated = Convert.ToDateTime(reader["DateUpdated"]); @@ -199,8 +199,8 @@ public override IList GetModifiedSearchDocuments(ModuleInfo modu } return searchDocuments.Values.ToList(); - } - + } + public bool HasViewPermission(SearchResult searchResult) { if (!searchResult.UniqueKey.StartsWith("JI_", StringComparison.InvariantCultureIgnoreCase)) @@ -269,7 +269,7 @@ public string GetDocUrl(SearchResult searchResult) var journalId = Convert.ToInt32(searchResult.UniqueKey.Split('_')[1]); var groupId = Convert.ToInt32(searchResult.Keywords["GroupId"]); var tabId = Convert.ToInt32(searchResult.Keywords["TabId"]); - + // var tabModuleId = Convert.ToInt32(searchResult.Keywords["TabModuleId"]); var profileId = Convert.ToInt32(searchResult.Keywords["ProfileId"]); @@ -287,8 +287,8 @@ public string GetDocUrl(SearchResult searchResult) } return url; - } - + } + private void AddCommentItems(Dictionary journalIds, IDictionary searchDocuments) { var comments = JournalController.Instance.GetCommentsByJournalIds(journalIds.Keys.ToList()); @@ -304,6 +304,6 @@ private void AddCommentItems(Dictionary journalIds, IDictionary[^\]]*)\]\]\>", 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); + 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; } - - private int ProfileId { get; set; } - - private int SocialGroupId { get; set; } - - private int ModuleId { get; set; } - - private UserInfo CurrentUser { get; set; } - - private int OwnerPortalId { get; set; } - 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) { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -68,25 +52,41 @@ public JournalParser(PortalSettings portalSettings, int moduleId, int profileId, this.OwnerPortalId = moduleInfo.OwnerPortalID; } - if (string.IsNullOrEmpty(this.url)) + if (string.IsNullOrEmpty(this.url)) { this.url = HttpContext.Current.Request.Url.Host; } - - this.url = string.Format( + + this.url = string.Format( "{0}://{1}{2}", UrlUtils.IsSecureConnectionOrSslOffload(HttpContext.Current.Request) ? "https" : "http", this.url, !HttpContext.Current.Request.Url.IsDefaultPort && !this.url.Contains(":") ? ":" + HttpContext.Current.Request.Url.Port : string.Empty); } + public int JournalId { get; set; } + + protected INavigationManager NavigationManager { get; } + + private PortalSettings PortalSettings { get; set; } + + private int ProfileId { get; set; } + + private int SocialGroupId { get; set; } + + private int ModuleId { get; set; } + + private UserInfo CurrentUser { get; set; } + + private int OwnerPortalId { get; set; } + public string GetList(int currentIndex, int rows) { - if (this.CurrentUser.UserID > 0) + if (this.CurrentUser.UserID > 0) { this.isAdmin = this.CurrentUser.IsInRole(this.PortalSettings.AdministratorRoleName); } - + this.isUnverifiedUser = !this.CurrentUser.IsSuperUser && this.CurrentUser.IsInRole("Unverified Users"); var journalControllerInternal = InternalJournalController.Instance; @@ -131,32 +131,32 @@ public string GetList(int currentIndex, int rows) var journalIds = journalList.Select(ji => ji.JournalId).ToList(); IList comments = JournalController.Instance.GetCommentsByJournalIds(journalIds); - foreach (JournalItem ji in journalList) + foreach (JournalItem ji in journalList) { string replacement = this.GetStringReplacement(ji); string rowTemplate; - if (ji.JournalType == "status") + if (ji.JournalType == "status") { rowTemplate = statusTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } - else if (ji.JournalType == "link") + } + else if (ji.JournalType == "link") { rowTemplate = linkTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } - else if (ji.JournalType == "photo") + } + else if (ji.JournalType == "photo") { rowTemplate = photoTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } - else if (ji.JournalType == "file") + } + else if (ji.JournalType == "file") { rowTemplate = fileTemplate; rowTemplate = TemplateRegex.Replace(rowTemplate, replacement); - } - else + } + else { rowTemplate = this.GetJournalTemplate(ji.JournalType, ji); } @@ -204,11 +204,11 @@ public string GetList(int currentIndex, int rows) string tmp = tokenReplace.ReplaceJournalItemTokens(rowTemplate); tmp = tmp.Replace("
    ", "
    "); sb.Append("
    "); - if (this.isAdmin || this.CurrentUser.UserID == ji.UserId || (this.ProfileId > Null.NullInteger && this.CurrentUser.UserID == this.ProfileId)) + if (this.isAdmin || this.CurrentUser.UserID == ji.UserId || (this.ProfileId > Null.NullInteger && this.CurrentUser.UserID == this.ProfileId)) { sb.Append("
    "); } - + sb.Append(tmp); sb.Append("
    "); } @@ -235,134 +235,134 @@ internal string GetLikeListHTML(JournalItem ji, ref bool isLiked) { var sb = new StringBuilder(); isLiked = false; - if (ji.JournalXML == null) + if (ji.JournalXML == null) { return string.Empty; } - + XmlNodeList xLikes = ji.JournalXML.DocumentElement.SelectNodes("//likes/u"); - if (xLikes == null) + if (xLikes == null) { return string.Empty; } - - foreach (XmlNode xLike in xLikes) + + foreach (XmlNode xLike in xLikes) { - if (Convert.ToInt32(xLike.Attributes["uid"].Value) == this.CurrentUser.UserID) + if (Convert.ToInt32(xLike.Attributes["uid"].Value) == this.CurrentUser.UserID) { ji.CurrentUserLikes = true; isLiked = true; break; } } - + int xc = 0; sb.Append("
    "); - if (xLikes.Count == 1 && ji.CurrentUserLikes) + if (xLikes.Count == 1 && ji.CurrentUserLikes) { sb.Append("{resx:youlikethis}"); - } - else if (xLikes.Count > 1) + } + else if (xLikes.Count > 1) { - if (ji.CurrentUserLikes) + if (ji.CurrentUserLikes) { sb.Append("{resx:you}"); xc += 1; } - - foreach (XmlNode l in xLikes) + + foreach (XmlNode l in xLikes) { int userId = Convert.ToInt32(l.Attributes["uid"].Value); string name = l.Attributes["un"].Value; - if (userId != this.CurrentUser.UserID) + if (userId != this.CurrentUser.UserID) { - if (xc < xLikes.Count - 1 && xc > 0 && xc < 3) + if (xc < xLikes.Count - 1 && xc > 0 && xc < 3) { sb.Append(", "); - } - else if (xc > 0 & xc < xLikes.Count & xc < 3) + } + else if (xc > 0 & xc < xLikes.Count & xc < 3) { sb.Append(" {resx:and} "); - } - else if (xc >= 3) + } + else if (xc >= 3) { int diff = xLikes.Count - xc; sb.Append(" {resx:and} " + (xLikes.Count - xc).ToString(CultureInfo.InvariantCulture)); - if (diff > 1) + if (diff > 1) { sb.Append(" {resx:others}"); - } - else + } + else { sb.Append(" {resx:other}"); } - + break; } - + sb.AppendFormat("{1}", userId, name); xc += 1; } } - - if (xc == 1) + + if (xc == 1) { sb.Append(" {resx:likesthis}"); - } - else if (xc > 1) + } + 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} "); - } - else if (xc < xLikes.Count - 1) - { - sb.Append(", "); - } - } - - if (xc == 1) - { - sb.Append(" {resx:likesthis}"); - } - 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} "); + } + else if (xc < xLikes.Count - 1) + { + sb.Append(", "); + } + } + + if (xc == 1) + { + sb.Append(" {resx:likesthis}"); + } + else if (xc > 1) + { + sb.Append(" {resx:likethis}"); + } + } + sb.Append("
    "); return sb.ToString(); } - internal string GetCommentAreaHTML(JournalItem journal, IList comments) + internal string GetCommentAreaHTML(JournalItem journal, IList comments) { if (journal.CommentsHidden) { return string.Empty; } - + var sb = new StringBuilder(); sb.AppendFormat("
      ", journal.JournalId); - foreach (CommentInfo ci in comments) + foreach (CommentInfo ci in comments) { if (ci.JournalId == journal.JournalId) { sb.Append(this.GetCommentRow(journal, ci)); } } - + if (this.CurrentUser.UserID > 0 && !journal.CommentsDisabled) { sb.AppendFormat("
    • ", journal.JournalId); @@ -376,16 +376,16 @@ internal string GetCommentAreaHTML(JournalItem journal, IList comme return sb.ToString(); } - internal string GetCommentRow(JournalItem journal, CommentInfo comment) + internal string GetCommentRow(JournalItem journal, CommentInfo comment) { var sb = new StringBuilder(); string pic = UserController.Instance.GetUserProfilePictureUrl(comment.UserId, 32, 32); sb.AppendFormat("
    • ", comment.CommentId); - if (comment.UserId == this.CurrentUser.UserID || journal.UserId == this.CurrentUser.UserID || this.isAdmin) + if (comment.UserId == this.CurrentUser.UserID || journal.UserId == this.CurrentUser.UserID || this.isAdmin) { sb.Append("
      "); } - + sb.AppendFormat("", pic); sb.Append("

      "); string userUrl = this.NavigationManager.NavigateURL(this.PortalSettings.UserTabId, string.Empty, new[] { "userId=" + comment.UserId }); @@ -403,7 +403,7 @@ internal string GetCommentRow(JournalItem journal, CommentInfo comment) { text = comment.CommentXML.SelectSingleNode("/root/comment").InnerText; } - + sb.Append(text.Replace("\n", "
      ")); } else @@ -418,8 +418,8 @@ internal string GetCommentRow(JournalItem journal, CommentInfo comment) sb.Append("

      "); sb.Append("
    • "); return sb.ToString(); - } - + } + private string GetStringReplacement(JournalItem journalItem) { string replacement = string.Empty; @@ -427,13 +427,13 @@ private string GetStringReplacement(JournalItem journalItem) { replacement = "$1"; } - + if (this.CurrentUser.UserID > 0 && journalItem.SocialGroupId > 0 && !this.isUnverifiedUser) { replacement = this.CurrentUser.IsInRole(journalItem.JournalOwner.Name) ? "$1" : string.Empty; } - + return replacement; - } + } } } diff --git a/DNN Platform/Modules/Journal/Components/LinkInfo.cs b/DNN Platform/Modules/Journal/Components/LinkInfo.cs index 53b68f8e5b2..fec70d42be4 100644 --- a/DNN Platform/Modules/Journal/Components/LinkInfo.cs +++ b/DNN Platform/Modules/Journal/Components/LinkInfo.cs @@ -12,11 +12,11 @@ namespace DotNetNuke.Modules.Journal.Components public class LinkInfo { public string URL { get; set; } - + public string Title { get; set; } - + public string Description { get; set; } - + public List Images { get; set; } } } diff --git a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs index 803f31f9245..96ecc6c0662 100644 --- a/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs +++ b/DNN Platform/Modules/Journal/Components/ProfilePicPropertyAccess.cs @@ -19,23 +19,23 @@ public ProfilePicPropertyAccess(int userId) this._userId = userId; } - public int Size { get; set; } = 32; - public CacheLevel Cacheability => CacheLevel.notCacheable; + public int Size { get; set; } = 32; + public string GetProperty(string propertyName, string format, CultureInfo formatProvider, UserInfo accessingUser, Scope currentScope, ref bool propertyNotFound) { if (propertyName.ToLowerInvariant() == "relativeurl") { int size; - if (int.TryParse(format, out size)) + if (int.TryParse(format, out size)) { this.Size = size; } - + return UserController.Instance.GetUserProfilePictureUrl(this._userId, this.Size, this.Size); } - + propertyNotFound = true; return string.Empty; } diff --git a/DNN Platform/Modules/Journal/Components/Utilities.cs b/DNN Platform/Modules/Journal/Components/Utilities.cs index 98e27170a73..4975e9cb57a 100644 --- a/DNN Platform/Modules/Journal/Components/Utilities.cs +++ b/DNN Platform/Modules/Journal/Components/Utilities.cs @@ -19,11 +19,11 @@ namespace DotNetNuke.Modules.Journal.Components public class Utilities { - private static readonly Regex PageRegex = new Regex( + private static readonly Regex PageRegex = new Regex( "<(title)[^>]*?>((?:.|\\n)*?)", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); - private static readonly Regex MetaRegex = new Regex( + private static readonly Regex MetaRegex = new Regex( " ]+)\\s*)?)*)/?\\s*>", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); @@ -39,76 +39,102 @@ public class Utilities private static readonly Regex HtmlTextRegex = new Regex("<(.|\\n)*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - public static string LocalizeControl(string controlText) + 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) + foreach (Match match in matches) { sKey = match.Value; sReplace = GetSharedResource(sKey); string newValue = match.Value; - if (!string.IsNullOrEmpty(sReplace)) + if (!string.IsNullOrEmpty(sReplace)) { newValue = sReplace; } - + controlText = controlText.Replace(sKey, newValue); } return controlText; } - - public static string GetSharedResource(string key) + + public static string GetSharedResource(string key) { string sValue = key; sValue = DotNetNuke.Services.Localization.Localization.GetString(key, Constants.SharedResourcesPath); - if (sValue == string.Empty) + if (sValue == string.Empty) { return key; - } - else + } + else { return sValue; } } - internal static Bitmap GetImageFromURL(string url) + public static string RemoveHTML(string sText) + { + if (string.IsNullOrEmpty(sText)) + { + return string.Empty; + } + + sText = HttpUtility.HtmlDecode(sText); + sText = HttpUtility.UrlDecode(sText); + sText = sText.Trim(); + if (string.IsNullOrEmpty(sText)) + { + return string.Empty; + } + + sText = HtmlTextRegex.Replace(sText, string.Empty); + sText = HttpUtility.HtmlEncode(sText); + return sText; + } + + public static bool AreFriends(UserInfo profileUser, UserInfo currentUser) + { + var friendsRelationShip = RelationshipController.Instance.GetFriendRelationship(profileUser, currentUser); + return friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted; + } + + internal static Bitmap GetImageFromURL(string url) { string sImgName = string.Empty; System.Net.WebRequest myRequest = default(System.Net.WebRequest); Bitmap bmp = null; - try + try { myRequest = System.Net.WebRequest.Create(url); myRequest.Proxy = null; - using (WebResponse myResponse = myRequest.GetResponse()) + using (WebResponse myResponse = myRequest.GetResponse()) { - using (Stream myStream = myResponse.GetResponseStream()) + using (Stream myStream = myResponse.GetResponseStream()) { string sContentType = myResponse.ContentType; string sExt = string.Empty; - if (sContentType.Contains("png")) + if (sContentType.Contains("png")) { sExt = ".png"; - } - else if (sContentType.Contains("jpg")) + } + else if (sContentType.Contains("jpg")) { sExt = ".jpg"; - } - else if (sContentType.Contains("jpeg")) + } + else if (sContentType.Contains("jpeg")) { sExt = ".jpg"; - } - else if (sContentType.Contains("gif")) + } + else if (sContentType.Contains("gif")) { sExt = ".gif"; } - - if (!string.IsNullOrEmpty(sExt)) + + if (!string.IsNullOrEmpty(sExt)) { bmp = new Bitmap(myStream); } @@ -116,51 +142,51 @@ internal static Bitmap GetImageFromURL(string url) } return bmp; - } - catch + } + catch { return null; } } - internal static string PrepareURL(string url) + internal static string PrepareURL(string url) { url = url.Trim(); - if (!url.StartsWith("http")) + if (!url.StartsWith("http")) { url = "http://" + url; } - - if (url.Contains("https://")) + + if (url.Contains("https://")) { url = url.Replace("https://", "http://"); } - - if (url.Contains("http://http://")) + + if (url.Contains("http://http://")) { url = url.Replace("http://http://", "http://"); } - - if (!(url.IndexOf("http://") == 0)) + + if (!(url.IndexOf("http://") == 0)) { url = "http://" + url; } - + Uri objURI = null; objURI = new Uri(url); return url; } - internal static LinkInfo GetLinkData(string URL) + internal static LinkInfo GetLinkData(string URL) { string sPage = GetPageFromURL(ref URL, string.Empty, string.Empty); LinkInfo link = new LinkInfo(); - if (string.IsNullOrEmpty(sPage)) + if (string.IsNullOrEmpty(sPage)) { return link; } - + string sTitle = string.Empty; string sDescription = string.Empty; string sImage = string.Empty; @@ -168,34 +194,34 @@ internal static LinkInfo GetLinkData(string URL) link.URL = URL; link.Images = new List(); Match m = PageRegex.Match(sPage); - if (m.Success) + if (m.Success) { link.Title = m.Groups[2].ToString().Trim(); } - + MatchCollection matches = default(MatchCollection); matches = MetaRegex.Matches(sPage); int i = 0; - foreach (Match match in matches) + foreach (Match match in matches) { string sTempDesc = match.Groups[0].Value; - foreach (Match subM in MetaSubRegex.Matches(sTempDesc)) + foreach (Match subM in MetaSubRegex.Matches(sTempDesc)) { - if (subM.Groups[4].Value.Equals("OG:DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) + if (subM.Groups[4].Value.Equals("OG:DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) { link.Description = subM.Groups[9].Value; - } - else if (subM.Groups[4].Value.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) + } + else if (subM.Groups[4].Value.Equals("DESCRIPTION", StringComparison.InvariantCultureIgnoreCase)) { link.Description = subM.Groups[9].Value; } - - if (subM.Groups[4].Value.Equals("OG:TITLE", StringComparison.InvariantCultureIgnoreCase)) + + if (subM.Groups[4].Value.Equals("OG:TITLE", StringComparison.InvariantCultureIgnoreCase)) { link.Title = subM.Groups[9].Value; } - if (subM.Groups[4].Value.Equals("OG:IMAGE", StringComparison.InvariantCultureIgnoreCase)) + if (subM.Groups[4].Value.Equals("OG:IMAGE", StringComparison.InvariantCultureIgnoreCase)) { sImage = subM.Groups[9].Value; ImageInfo img = new ImageInfo(); @@ -205,62 +231,62 @@ internal static LinkInfo GetLinkData(string URL) } } } - - if (!string.IsNullOrEmpty(link.Description)) + + if (!string.IsNullOrEmpty(link.Description)) { link.Description = HttpUtility.HtmlDecode(link.Description); link.Description = HttpUtility.UrlDecode(link.Description); link.Description = RemoveHTML(link.Description); } - - if (!string.IsNullOrEmpty(link.Title)) + + if (!string.IsNullOrEmpty(link.Title)) { link.Title = link.Title.Replace("&", "&"); } - + matches = MetaSubRegex2.Matches(sPage); string imgList = string.Empty; string hostUrl = string.Empty; - if (!URL.Contains("http")) + if (!URL.Contains("http")) { URL = "http://" + URL; } - + Uri uri = new Uri(URL); hostUrl = uri.Host; - if (URL.Contains("https:")) + if (URL.Contains("https:")) { hostUrl = "https://" + hostUrl; - } - else + } + else { hostUrl = "http://" + hostUrl; } - - foreach (Match match in matches) + + foreach (Match match in matches) { string sImg = match.Groups[5].Value; - if (string.IsNullOrEmpty(sImg)) + if (string.IsNullOrEmpty(sImg)) { sImg = match.Groups[8].Value; } - - if (!string.IsNullOrEmpty(sImg)) + + if (!string.IsNullOrEmpty(sImg)) { - if (!sImg.Contains("http")) + if (!sImg.Contains("http")) { sImg = hostUrl + sImg; } ImageInfo img = new ImageInfo(); img.URL = sImg; - if (!imgList.Contains(sImg)) + if (!imgList.Contains(sImg)) { Bitmap bmp = Utilities.GetImageFromURL(sImg); - if (bmp != null) + if (bmp != null) { - if (bmp.Height > 25 & bmp.Height < 500 & bmp.Width > 25 & bmp.Width < 500) + if (bmp.Height > 25 & bmp.Height < 500 & bmp.Width > 25 & bmp.Width < 500) { link.Images.Add(img); imgList += sImg; @@ -268,18 +294,18 @@ internal static LinkInfo GetLinkData(string URL) } } } - - if (i == 10) + + if (i == 10) { break; } } } - + return link; } - - internal static string GetPageFromURL(ref string url, string username, string password) + + internal static string GetPageFromURL(ref string url, string username, string password) { url = PrepareURL(url); HttpWebRequest objWebRequest = default(HttpWebRequest); @@ -290,21 +316,21 @@ internal static string GetPageFromURL(ref string url, string username, string pa objWebRequest.KeepAlive = false; objWebRequest.Proxy = null; objWebRequest.CookieContainer = cookies; - if (!string.IsNullOrEmpty(username) & !string.IsNullOrEmpty(password)) + if (!string.IsNullOrEmpty(username) & !string.IsNullOrEmpty(password)) { NetworkCredential nc = new NetworkCredential(username, password); objWebRequest.Credentials = nc; } - + string sHTML = string.Empty; - try + try { objWebResponse = (HttpWebResponse)objWebRequest.GetResponse(); Encoding enc = Encoding.UTF8; - + string contentType = objWebResponse.ContentType; - if ((objWebRequest.HaveResponse == true) & objWebResponse.StatusCode == HttpStatusCode.OK) + if ((objWebRequest.HaveResponse == true) & objWebResponse.StatusCode == HttpStatusCode.OK) { objWebResponse.Cookies = objWebRequest.CookieContainer.GetCookies(objWebRequest.RequestUri); using (Stream objStream = objWebResponse.GetResponseStream()) @@ -315,41 +341,15 @@ internal static string GetPageFromURL(ref string url, string username, string pa objStream.Close(); } } - + objWebResponse.Close(); - } - catch (Exception ex) + } + catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); } return sHTML; } - - public static string RemoveHTML(string sText) - { - if (string.IsNullOrEmpty(sText)) - { - return string.Empty; - } - - sText = HttpUtility.HtmlDecode(sText); - sText = HttpUtility.UrlDecode(sText); - sText = sText.Trim(); - if (string.IsNullOrEmpty(sText)) - { - return string.Empty; - } - - sText = HtmlTextRegex.Replace(sText, string.Empty); - sText = HttpUtility.HtmlEncode(sText); - return sText; - } - - public static bool AreFriends(UserInfo profileUser, UserInfo currentUser) - { - var friendsRelationShip = RelationshipController.Instance.GetFriendRelationship(profileUser, currentUser); - return friendsRelationShip != null && friendsRelationShip.Status == RelationshipStatus.Accepted; - } } } diff --git a/DNN Platform/Modules/Journal/Edit.ascx.cs b/DNN Platform/Modules/Journal/Edit.ascx.cs index 12098f09d16..9868240d8dd 100644 --- a/DNN Platform/Modules/Journal/Edit.ascx.cs +++ b/DNN Platform/Modules/Journal/Edit.ascx.cs @@ -26,14 +26,14 @@ namespace DotNetNuke.Modules.Journal ///
    /// ----------------------------------------------------------------------------- public partial class Edit : JournalModuleBase - { - protected override void OnInit(EventArgs e) + { + protected override void OnInit(EventArgs e) { this.InitializeComponent(); base.OnInit(e); } - private void InitializeComponent() + private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } @@ -43,16 +43,16 @@ private void InitializeComponent() /// Page_Load runs when the control is loaded. ///
    /// ----------------------------------------------------------------------------- - private void Page_Load(object sender, System.EventArgs e) + private void Page_Load(object sender, System.EventArgs e) { - try + try { // Implement your edit logic for your module - } + } catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Modules/Journal/FileUploadController.cs b/DNN Platform/Modules/Journal/FileUploadController.cs index 793a5a0e5b7..5693acb6f29 100644 --- a/DNN Platform/Modules/Journal/FileUploadController.cs +++ b/DNN Platform/Modules/Journal/FileUploadController.cs @@ -64,13 +64,13 @@ private void UploadWholeFile(HttpContextBase context, ICollection s for (var i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; - if (file == null) - { - continue; - } - + if (file == null) + { + continue; + } + var fileName = Path.GetFileName(file.FileName); - + // fix any filename issues that would cause double escaping exceptions if (IsImageExtension(Path.GetExtension(fileName))) { @@ -85,7 +85,7 @@ private void UploadWholeFile(HttpContextBase context, ICollection s { fileIcon = Entities.Icons.IconController.IconURL("File", "32x32"); } - + statuses.Add(new FilesStatus { success = true, diff --git a/DNN Platform/Modules/Journal/FilesStatus.cs b/DNN Platform/Modules/Journal/FilesStatus.cs index 3057120dadd..6930848197d 100644 --- a/DNN Platform/Modules/Journal/FilesStatus.cs +++ b/DNN Platform/Modules/Journal/FilesStatus.cs @@ -7,29 +7,28 @@ namespace DotNetNuke.Modules.Journal public class FilesStatus { // ReSharper restore InconsistentNaming + public FilesStatus() { - } - - // ReSharper disable InconsistentNaming + } // ReSharper disable InconsistentNaming public bool success { get; set; } - + public string name { get; set; } - + public string extension { get; set; } - + public string type { get; set; } - + public int size { get; set; } - + public string progress { get; set; } - + public string url { get; set; } - + public string thumbnail_url { get; set; } - + public string message { get; set; } - + public int file_id { get; set; } } } diff --git a/DNN Platform/Modules/Journal/JournalList.cs b/DNN Platform/Modules/Journal/JournalList.cs index 5a864c79fcd..a7c031946d6 100644 --- a/DNN Platform/Modules/Journal/JournalList.cs +++ b/DNN Platform/Modules/Journal/JournalList.cs @@ -18,14 +18,14 @@ namespace DotNetNuke.Modules.Journal public class JournalList : WebControl { public int PortalId { get; set; } - + public int ProfileId { get; set; } - + public int SocialGroupId { get; set; } - + public int DisplayMode { get; set; } - protected override void Render(HtmlTextWriter output) + protected override void Render(HtmlTextWriter output) { output.Write("Hello World"); } diff --git a/DNN Platform/Modules/Journal/JournalListControl.cs b/DNN Platform/Modules/Journal/JournalListControl.cs index 47c9b57c23c..ee74467dfac 100644 --- a/DNN Platform/Modules/Journal/JournalListControl.cs +++ b/DNN Platform/Modules/Journal/JournalListControl.cs @@ -27,27 +27,27 @@ namespace DotNetNuke.Modules.Journal.Controls [ToolboxData("<{0}:JournalListControl runat=server>")] public class JournalListControl : WebControl { - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public PortalSettings portalSettings + public PortalSettings portalSettings { - get + get { return PortalController.Instance.GetCurrentPortalSettings(); } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public UserInfo userInfo + public UserInfo userInfo { - get + get { return UserController.Instance.GetCurrentUserInfo(); } } - [Browsable(false)] + [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public int JournalId { @@ -74,13 +74,13 @@ public int JournalId protected override void Render(HtmlTextWriter output) { - if (this.Enabled) + if (this.Enabled) { - if (this.CurrentIndex < 0) + if (this.CurrentIndex < 0) { this.CurrentIndex = 0; } - + JournalParser jp = new JournalParser(this.portalSettings, this.ModuleId, this.ProfileId, this.SocialGroupId, this.userInfo) { JournalId = this.JournalId }; output.Write(jp.GetList(this.CurrentIndex, this.PageSize)); } diff --git a/DNN Platform/Modules/Journal/JournalModuleBase.cs b/DNN Platform/Modules/Journal/JournalModuleBase.cs index fba7560e6f5..cc23fead5c0 100644 --- a/DNN Platform/Modules/Journal/JournalModuleBase.cs +++ b/DNN Platform/Modules/Journal/JournalModuleBase.cs @@ -22,58 +22,58 @@ namespace DotNetNuke.Modules.Journal public class JournalModuleBase : DotNetNuke.Entities.Modules.PortalModuleBase { - public enum JournalMode + public enum JournalMode { Auto = 0, Profile = 1, Group = 2, } - - public JournalMode FilterMode + + public JournalMode FilterMode { - get + get { - if (!this.Settings.ContainsKey(Constants.JournalFilterMode)) + if (!this.Settings.ContainsKey(Constants.JournalFilterMode)) { return JournalMode.Auto; - } - else + } + else { - if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilterMode].ToString())) + if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilterMode].ToString())) { return JournalMode.Auto; - } - else + } + else { return (JournalMode)Convert.ToInt16(this.Settings[Constants.JournalFilterMode].ToString()); } } } } - - public int GroupId + + public int GroupId { - get + get { int groupId = -1; - if (!string.IsNullOrEmpty(this.Request.QueryString["groupid"])) + if (!string.IsNullOrEmpty(this.Request.QueryString["groupid"])) { - if (int.TryParse(this.Request.QueryString["groupid"], out groupId)) + if (int.TryParse(this.Request.QueryString["groupid"], out groupId)) { return groupId; - } - else + } + else { return -1; } - } - else + } + else { return -1; } } } - + public bool EditorEnabled { get @@ -81,13 +81,13 @@ public bool EditorEnabled if (!this.Settings.ContainsKey(Constants.JournalEditorEnabled)) { return true; - } + } else { if (string.IsNullOrEmpty(this.Settings[Constants.JournalEditorEnabled].ToString())) { return true; - } + } else { return (bool)Convert.ToBoolean(this.Settings[Constants.JournalEditorEnabled].ToString()); diff --git a/DNN Platform/Modules/Journal/JournalSettingsBase.cs b/DNN Platform/Modules/Journal/JournalSettingsBase.cs index 275e1a6cadd..397f0595925 100644 --- a/DNN Platform/Modules/Journal/JournalSettingsBase.cs +++ b/DNN Platform/Modules/Journal/JournalSettingsBase.cs @@ -19,6 +19,5 @@ namespace DotNetNuke.Modules.Journal using DotNetNuke.Entities.Modules; public class JournalSettingsBase : ModuleSettingsBase - { - } + {} } diff --git a/DNN Platform/Modules/Journal/MyFiles.ascx.cs b/DNN Platform/Modules/Journal/MyFiles.ascx.cs index 13c18e49624..0baeb503053 100644 --- a/DNN Platform/Modules/Journal/MyFiles.ascx.cs +++ b/DNN Platform/Modules/Journal/MyFiles.ascx.cs @@ -14,55 +14,55 @@ namespace DotNetNuke.Modules.Journal public partial class MyFiles : PortalModuleBase { - protected override void OnInit(EventArgs e) + protected override void OnInit(EventArgs e) { this.InitializeComponent(); base.OnInit(e); } - - protected void Page_Load(object sender, EventArgs e) + + protected void Page_Load(object sender, EventArgs e) { } - - protected void btnUp_Upload(object sender, EventArgs e) + + protected void btnUp_Upload(object sender, EventArgs e) { var folderManager = FolderManager.Instance; var userFolder = folderManager.GetUserFolder(this.UserInfo); string message = string.Empty; IFileInfo fi = null; - try + try { fi = FileManager.Instance.AddFile(userFolder, this.fileUp.PostedFile.FileName, this.fileUp.PostedFile.InputStream, true); - } - catch (PermissionsNotMetException) + } + catch (PermissionsNotMetException) { message = string.Format(Localization.GetString("InsufficientFolderPermission"), userFolder.FolderPath); - } - catch (NoSpaceAvailableException) + } + catch (NoSpaceAvailableException) { message = string.Format(Localization.GetString("DiskSpaceExceeded"), this.fileUp.PostedFile.FileName); - } - catch (InvalidFileExtensionException) + } + catch (InvalidFileExtensionException) { message = string.Format(Localization.GetString("RestrictedFileType"), this.fileUp.PostedFile.FileName, Host.AllowedExtensionWhitelist.ToDisplayString()); - } - catch + } + catch { message = string.Format(Localization.GetString("SaveFileError"), this.fileUp.PostedFile.FileName); } - - if (string.IsNullOrEmpty(message) && fi != null) + + if (string.IsNullOrEmpty(message) && fi != null) { this.litOut.Text = ""; - } - else + } + else { this.litOut.Text = message; } } - private void InitializeComponent() + 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/ServicesController.cs b/DNN Platform/Modules/Journal/ServicesController.cs index 8beeb59b4c3..d471517e39f 100644 --- a/DNN Platform/Modules/Journal/ServicesController.cs +++ b/DNN Platform/Modules/Journal/ServicesController.cs @@ -34,11 +34,11 @@ public class ServicesController : DnnApiController { 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" }; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ServicesController)); + + private static readonly string[] AcceptedFileExtensions = { "jpg", "png", "gif", "jpe", "jpeg", "tiff", "bmp" }; [HttpPost] [ValidateAntiForgeryToken] @@ -105,55 +105,6 @@ public HttpResponseMessage Delete(JournalIdDTO postData) } } - private static bool IsImageFile(string relativePath) - { - if (relativePath == null) - { - return false; - } - - if (relativePath.Contains("?")) - { - relativePath = relativePath.Substring( - 0, - relativePath.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)); - } - - var extension = relativePath.Substring(relativePath.LastIndexOf( - ".", - StringComparison.Ordinal) + 1).ToLowerInvariant(); - return AcceptedFileExtensions.Contains(extension); - } - - 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")] @@ -201,138 +152,6 @@ public HttpResponseMessage PreviewUrl(PreviewDTO postData) } } - // Check if a user can post content on a specific profile's page - private void checkProfileAccess(int profileId, UserInfo currentUser) - { - if (profileId != currentUser.UserID) - { - var profileUser = UserController.Instance.GetUser(this.PortalSettings.PortalId, profileId); - if (profileUser == null || (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !Utilities.AreFriends(profileUser, currentUser))) - { - throw new ArgumentException("you have no permission to post journal on current profile page."); - } - } - } - - private void checkGroupAccess(CreateDTO postData) - { - if (postData.GroupId > 0) - { - postData.ProfileId = -1; - - RoleInfo roleInfo = RoleController.Instance.GetRoleById(this.ActiveModule.OwnerPortalID, postData.GroupId); - if (roleInfo != null) - { - if (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !this.UserInfo.IsInRole(roleInfo.RoleName)) - { - throw new ArgumentException("you have no permission to post journal on current group."); - } - - if (!roleInfo.IsPublic) - { - postData.SecuritySet = "R"; - } - } - } - } - - private JournalItem prepareJournalItem(CreateDTO postData, IDictionary mentionedUsers) - { - var journalTypeId = 1; - switch (postData.JournalType) - { - case "link": - journalTypeId = 2; - break; - case "photo": - journalTypeId = 3; - break; - case "file": - journalTypeId = 4; - break; - } - - var ji = new JournalItem - { - JournalId = -1, - JournalTypeId = journalTypeId, - PortalId = this.ActiveModule.OwnerPortalID, - UserId = this.UserInfo.UserID, - SocialGroupId = postData.GroupId, - ProfileId = postData.ProfileId, - Summary = postData.Text ?? string.Empty, - SecuritySet = postData.SecuritySet, - }; - ji.Title = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Title)); - ji.Summary = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Summary)); - - var ps = PortalSecurity.Instance; - - ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoScripting); - ji.Title = Utilities.RemoveHTML(ji.Title); - ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoMarkup); - - ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoScripting); - ji.Summary = Utilities.RemoveHTML(ji.Summary); - ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoMarkup); - - // parse the mentions context in post data - var originalSummary = ji.Summary; - - ji.Summary = this.ParseMentions(ji.Summary, postData.Mentions, ref mentionedUsers); - - if (ji.Summary.Length > 2000) - { - ji.Body = ji.Summary; - ji.Summary = null; - } - - if (!string.IsNullOrEmpty(postData.ItemData)) - { - ji.ItemData = postData.ItemData.FromJson(); - var originalImageUrl = ji.ItemData.ImageUrl; - if (!IsImageFile(ji.ItemData.ImageUrl)) - { - ji.ItemData.ImageUrl = string.Empty; - } - - ji.ItemData.Description = HttpUtility.UrlDecode(ji.ItemData.Description); - - if (!IsAllowedLink(ji.ItemData.Url)) - { - ji.ItemData.Url = string.Empty; - } - - if (!string.IsNullOrEmpty(ji.ItemData.Url) && ji.ItemData.Url.StartsWith("fileid=")) - { - var fileId = Convert.ToInt32(ji.ItemData.Url.Replace("fileid=", string.Empty).Trim()); - var file = FileManager.Instance.GetFile(fileId); - - if (!this.IsCurrentUserFile(file)) - { - throw new ArgumentException("you have no permission to attach files not belongs to you."); - } - - ji.ItemData.Title = file.FileName; - ji.ItemData.Url = Globals.LinkClick(ji.ItemData.Url, Null.NullInteger, Null.NullInteger); - - if (string.IsNullOrEmpty(ji.ItemData.ImageUrl) && - originalImageUrl.ToLowerInvariant().StartsWith("/linkclick.aspx?") && - AcceptedFileExtensions.Contains(file.Extension.ToLowerInvariant())) - { - ji.ItemData.ImageUrl = originalImageUrl; - } - } - } - - return ji; - } - - public class JournalIdDTO - { - public int JournalId { get; set; } - } - [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage GetListForProfile(GetListForProfileDTO postData) @@ -401,22 +220,6 @@ public HttpResponseMessage CommentSave(CommentSaveDTO postData) return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } - - public class PreviewDTO - { - public string Url { get; set; } - } - - 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] @@ -473,12 +276,12 @@ 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, }); } } @@ -490,8 +293,160 @@ public HttpResponseMessage GetSuggestions(string keyword) Logger.Error(exc); return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } - } - + } + + private static bool IsImageFile(string relativePath) + { + if (relativePath == null) + { + return false; + } + + if (relativePath.Contains("?")) + { + relativePath = relativePath.Substring( + 0, + relativePath.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)); + } + + var extension = relativePath.Substring(relativePath.LastIndexOf( + ".", + StringComparison.Ordinal) + 1).ToLowerInvariant(); + return AcceptedFileExtensions.Contains(extension); + } + + private static bool IsAllowedLink(string url) + { + return !string.IsNullOrEmpty(url) && !url.Contains("//"); + } + + // Check if a user can post content on a specific profile's page + private void checkProfileAccess(int profileId, UserInfo currentUser) + { + if (profileId != currentUser.UserID) + { + var profileUser = UserController.Instance.GetUser(this.PortalSettings.PortalId, profileId); + if (profileUser == null || (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !Utilities.AreFriends(profileUser, currentUser))) + { + throw new ArgumentException("you have no permission to post journal on current profile page."); + } + } + } + + private void checkGroupAccess(CreateDTO postData) + { + if (postData.GroupId > 0) + { + postData.ProfileId = -1; + + RoleInfo roleInfo = RoleController.Instance.GetRoleById(this.ActiveModule.OwnerPortalID, postData.GroupId); + if (roleInfo != null) + { + if (!this.UserInfo.IsInRole(this.PortalSettings.AdministratorRoleName) && !this.UserInfo.IsInRole(roleInfo.RoleName)) + { + throw new ArgumentException("you have no permission to post journal on current group."); + } + + if (!roleInfo.IsPublic) + { + postData.SecuritySet = "R"; + } + } + } + } + + private JournalItem prepareJournalItem(CreateDTO postData, IDictionary mentionedUsers) + { + var journalTypeId = 1; + switch (postData.JournalType) + { + case "link": + journalTypeId = 2; + break; + case "photo": + journalTypeId = 3; + break; + case "file": + journalTypeId = 4; + break; + } + + var ji = new JournalItem + { + JournalId = -1, + JournalTypeId = journalTypeId, + PortalId = this.ActiveModule.OwnerPortalID, + UserId = this.UserInfo.UserID, + SocialGroupId = postData.GroupId, + ProfileId = postData.ProfileId, + Summary = postData.Text ?? string.Empty, + SecuritySet = postData.SecuritySet, + }; + ji.Title = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Title)); + ji.Summary = HttpUtility.HtmlDecode(HttpUtility.UrlDecode(ji.Summary)); + + var ps = PortalSecurity.Instance; + + ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoScripting); + ji.Title = Utilities.RemoveHTML(ji.Title); + ji.Title = ps.InputFilter(ji.Title, PortalSecurity.FilterFlag.NoMarkup); + + ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoScripting); + ji.Summary = Utilities.RemoveHTML(ji.Summary); + ji.Summary = ps.InputFilter(ji.Summary, PortalSecurity.FilterFlag.NoMarkup); + + // parse the mentions context in post data + var originalSummary = ji.Summary; + + ji.Summary = this.ParseMentions(ji.Summary, postData.Mentions, ref mentionedUsers); + + if (ji.Summary.Length > 2000) + { + ji.Body = ji.Summary; + ji.Summary = null; + } + + if (!string.IsNullOrEmpty(postData.ItemData)) + { + ji.ItemData = postData.ItemData.FromJson(); + var originalImageUrl = ji.ItemData.ImageUrl; + if (!IsImageFile(ji.ItemData.ImageUrl)) + { + ji.ItemData.ImageUrl = string.Empty; + } + + ji.ItemData.Description = HttpUtility.UrlDecode(ji.ItemData.Description); + + if (!IsAllowedLink(ji.ItemData.Url)) + { + ji.ItemData.Url = string.Empty; + } + + if (!string.IsNullOrEmpty(ji.ItemData.Url) && ji.ItemData.Url.StartsWith("fileid=")) + { + var fileId = Convert.ToInt32(ji.ItemData.Url.Replace("fileid=", string.Empty).Trim()); + var file = FileManager.Instance.GetFile(fileId); + + if (!this.IsCurrentUserFile(file)) + { + throw new ArgumentException("you have no permission to attach files not belongs to you."); + } + + ji.ItemData.Title = file.FileName; + ji.ItemData.Url = Globals.LinkClick(ji.ItemData.Url, Null.NullInteger, Null.NullInteger); + + if (string.IsNullOrEmpty(ji.ItemData.ImageUrl) && + originalImageUrl.ToLowerInvariant().StartsWith("/linkclick.aspx?") && + AcceptedFileExtensions.Contains(file.Extension.ToLowerInvariant())) + { + ji.ItemData.ImageUrl = originalImageUrl; + } + } + } + + return ji; + } + private string ParseMentions(string content, IList mentions, ref IDictionary mentionedUsers) { if (mentions == null || mentions.Count == 0) @@ -509,7 +464,7 @@ private string ParseMentions(string content, IList mentions, ref IDi RelationshipController.Instance.GetFriendRelationship(this.UserInfo, user); if (relationship != null && relationship.Status == RelationshipStatus.Accepted) { - var userLink = string.Format( + var userLink = string.Format( "{1}", Globals.UserProfileURL(user.UserID), MentionIdentityChar + user.DisplayName); @@ -519,7 +474,7 @@ private string ParseMentions(string content, IList mentions, ref IDi } } } - + return content; } @@ -539,7 +494,7 @@ private void SendMentionNotifications(IDictionary mentionedUse { mentionText = mentionText.Substring(0, MentionNotificationLength) + MentionNotificationSuffix; } - + var notification = new Notification { Subject = string.Format(subjectTemplate, this.UserInfo.DisplayName, mentionType), @@ -554,33 +509,6 @@ 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) @@ -614,6 +542,78 @@ private IList GetSubFolders(IFolderInfo parentFolder) } return folders; - } + } + + 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; } + } + + public class JournalIdDTO + { + public int JournalId { get; set; } + } + + public class PreviewDTO + { + public string Url { get; set; } + } + + public class GetListForProfileDTO + { + public int ProfileId { get; set; } + + public int GroupId { get; set; } + + public int RowIndex { get; set; } + + public int MaxRows { get; set; } + } + + 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; } + } } } diff --git a/DNN Platform/Modules/Journal/Settings.ascx.cs b/DNN Platform/Modules/Journal/Settings.ascx.cs index dafe9c3c503..07786907c85 100644 --- a/DNN Platform/Modules/Journal/Settings.ascx.cs +++ b/DNN Platform/Modules/Journal/Settings.ascx.cs @@ -32,53 +32,53 @@ namespace DotNetNuke.Modules.Journal ///
    /// ----------------------------------------------------------------------------- public partial class Settings : JournalSettingsBase - { + { /// ----------------------------------------------------------------------------- /// /// LoadSettings loads the settings from the Database and displays them. /// /// ----------------------------------------------------------------------------- - public override void LoadSettings() + public override void LoadSettings() { - try + try { - if (this.Page.IsPostBack == false) + if (this.Page.IsPostBack == false) { this.BindJournalTypes(); - + // Check for existing settings and use those on this page - if (this.Settings.ContainsKey(Constants.DefaultPageSize)) + if (this.Settings.ContainsKey(Constants.DefaultPageSize)) { this.drpDefaultPageSize.SelectedIndex = this.drpDefaultPageSize.Items.IndexOf(this.drpDefaultPageSize.Items.FindByValue(this.Settings[Constants.DefaultPageSize].ToString())); - } - else + } + else { this.drpDefaultPageSize.SelectedIndex = this.drpDefaultPageSize.Items.IndexOf(this.drpDefaultPageSize.Items.FindByValue("20")); } - - if (this.Settings.ContainsKey(Constants.MaxCharacters)) + + if (this.Settings.ContainsKey(Constants.MaxCharacters)) { this.drpMaxMessageLength.SelectedIndex = this.drpMaxMessageLength.Items.IndexOf(this.drpMaxMessageLength.Items.FindByValue(this.Settings[Constants.MaxCharacters].ToString())); - } - else + } + else { this.drpMaxMessageLength.SelectedIndex = this.drpMaxMessageLength.Items.IndexOf(this.drpMaxMessageLength.Items.FindByValue("250")); } - - if (this.Settings.ContainsKey(Constants.AllowFiles)) + + if (this.Settings.ContainsKey(Constants.AllowFiles)) { this.chkAllowFiles.Checked = Convert.ToBoolean(this.Settings[Constants.AllowFiles].ToString()); - } - else + } + else { this.chkAllowFiles.Checked = true; } - - if (this.Settings.ContainsKey(Constants.AllowPhotos)) + + if (this.Settings.ContainsKey(Constants.AllowPhotos)) { this.chkAllowPhotos.Checked = Convert.ToBoolean(this.Settings[Constants.AllowPhotos].ToString()); - } - else + } + else { this.chkAllowPhotos.Checked = true; } @@ -95,12 +95,12 @@ public override void LoadSettings() if (this.Settings.ContainsKey(Constants.JournalEditorEnabled)) { this.chkEnableEditor.Checked = Convert.ToBoolean(this.Settings[Constants.JournalEditorEnabled].ToString()); - } + } else { this.chkEnableEditor.Checked = true; } - + if (!this.chkEnableEditor.Checked) { this.chkAllowFiles.Enabled = false; @@ -109,32 +109,32 @@ public override void LoadSettings() this.chkAllowResize.Enabled = this.chkEnableEditor.Checked && this.chkAllowPhotos.Checked; - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { li.Selected = true; } - - if (this.Settings.ContainsKey(Constants.JournalFilters)) + + if (this.Settings.ContainsKey(Constants.JournalFilters)) { - if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilters].ToString())) + if (string.IsNullOrEmpty(this.Settings[Constants.JournalFilters].ToString())) { - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { li.Selected = true; } - } - else + } + else { - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { li.Selected = false; } - - foreach (string s in this.Settings[Constants.JournalFilters].ToString().Split(';')) + + foreach (string s in this.Settings[Constants.JournalFilters].ToString().Split(';')) { - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { - if (li.Value == s) + if (li.Value == s) { li.Selected = true; } @@ -143,7 +143,7 @@ public override void LoadSettings() } } } - } + } catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); @@ -155,9 +155,9 @@ public override void LoadSettings() /// UpdateSettings saves the modified settings to the Database. ///
    /// ----------------------------------------------------------------------------- - public override void UpdateSettings() + public override void UpdateSettings() { - try + try { ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.DefaultPageSize, this.drpDefaultPageSize.SelectedItem.Value); ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.AllowFiles, this.chkAllowFiles.Checked.ToString()); @@ -167,43 +167,43 @@ public override void UpdateSettings() ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.MaxCharacters, this.drpMaxMessageLength.SelectedItem.Value); string journalTypes = string.Empty; bool allTypes = true; - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { - if (!li.Selected) + if (!li.Selected) { allTypes = false; } } - + var jc = InternalJournalController.Instance; jc.DeleteFilters(this.PortalId, this.ModuleId); - foreach (ListItem li in this.chkJournalFilters.Items) + foreach (ListItem li in this.chkJournalFilters.Items) { - if (li.Selected) + if (li.Selected) { - if (!allTypes) + if (!allTypes) { jc.SaveFilters(this.PortalId, this.ModuleId, Convert.ToInt32(li.Value)); journalTypes += li.Value + ";"; } } } - + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, Constants.JournalFilters, journalTypes); - } + } catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } - - private void BindJournalTypes() + } + + private void BindJournalTypes() { foreach (JournalTypeInfo journalTypeInfo in JournalController.Instance.GetJournalTypes(this.PortalId)) { this.chkJournalFilters.Items.Add(new ListItem(Localization.GetString(journalTypeInfo.JournalType, "~/desktopmodules/journal/app_localresources/sharedresources.resx"), journalTypeInfo.JournalTypeId.ToString())); } - } + } } } diff --git a/DNN Platform/Modules/Journal/UserFolderHelper.cs b/DNN Platform/Modules/Journal/UserFolderHelper.cs index f201bc3248a..13b1ec8dc03 100644 --- a/DNN Platform/Modules/Journal/UserFolderHelper.cs +++ b/DNN Platform/Modules/Journal/UserFolderHelper.cs @@ -16,8 +16,6 @@ public UserFolderHelper(PortalSettings portalSettings) this.UserFolder = FolderManager.Instance.GetUserFolder(portalSettings.UserInfo); } - public IFolderInfo UserFolder { get; set; } - public string UserFolderPhysicalPath { get @@ -33,5 +31,7 @@ public string UserFolderPath return this.UserFolder.FolderPath; } } + + public IFolderInfo UserFolder { get; set; } } } diff --git a/DNN Platform/Modules/Journal/View.ascx.cs b/DNN Platform/Modules/Journal/View.ascx.cs index a0e302f8116..ac7919802c6 100644 --- a/DNN Platform/Modules/Journal/View.ascx.cs +++ b/DNN Platform/Modules/Journal/View.ascx.cs @@ -41,7 +41,6 @@ public partial class View : JournalModuleBase { public int PageSize = 20; public bool AllowPhotos = true; - private readonly INavigationManager _navigationManager; public bool AllowFiles = true; public int MaxMessageLength = 250; public bool CanRender = true; @@ -54,12 +53,13 @@ public partial class View : JournalModuleBase public int Pid = -1; public long MaxUploadSize = Config.GetMaxUploadSize(); public bool IsPublicGroup = false; + private readonly INavigationManager _navigationManager; public View() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + protected override void OnInit(EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); @@ -86,22 +86,22 @@ protected override void OnInit(EventArgs e) { this.PageSize = Convert.ToInt16(this.Settings[Constants.DefaultPageSize]); } - + if (this.Settings.ContainsKey(Constants.MaxCharacters)) { this.MaxMessageLength = Convert.ToInt16(this.Settings[Constants.MaxCharacters]); } - + if (this.Settings.ContainsKey(Constants.AllowPhotos)) { this.AllowPhotos = Convert.ToBoolean(this.Settings[Constants.AllowPhotos]); } - + if (this.Settings.ContainsKey(Constants.AllowFiles)) { this.AllowFiles = Convert.ToBoolean(this.Settings[Constants.AllowFiles]); } - + this.ctlJournalList.Enabled = true; this.ctlJournalList.ProfileId = -1; this.ctlJournalList.PageSize = this.PageSize; @@ -129,7 +129,7 @@ protected override void OnInit(EventArgs e) this.ShowEditor = true; this.CanComment = true; this.IsGroup = true; - } + } else { this.ShowEditor = false; @@ -140,17 +140,17 @@ protected override void OnInit(EventArgs e) { this.ctlJournalList.Enabled = false; } - + if (roleInfo.IsPublic && !this.ShowEditor) { this.ctlJournalList.Enabled = true; } - + if (roleInfo.IsPublic && this.ShowEditor) { this.ctlJournalList.Enabled = true; } - + if (roleInfo.IsPublic) { this.IsPublicGroup = true; @@ -182,7 +182,7 @@ protected override void OnInit(EventArgs e) base.OnInit(e); } - private void InitializeComponent() + private void InitializeComponent() { this.Load += this.Page_Load; } @@ -192,7 +192,7 @@ private void InitializeComponent() /// Page_Load runs when the control is loaded. ///
    /// ----------------------------------------------------------------------------- - private void Page_Load(object sender, EventArgs e) + private void Page_Load(object sender, EventArgs e) { try { @@ -212,13 +212,13 @@ private void Page_Load(object sender, EventArgs e) this.Gid = this.GroupId; this.ctlJournalList.SocialGroupId = this.GroupId; } - + this.ctlJournalList.PageSize = this.PageSize; } catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Modules/MemberDirectory/Services/Member.cs b/DNN Platform/Modules/MemberDirectory/Services/Member.cs index 84287971378..434538ef58e 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/Member.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/Member.cs @@ -103,7 +103,7 @@ public Dictionary ProfileProperties var propertyAccess = new ProfilePropertyAccess(this._user); foreach (ProfilePropertyDefinition property in this._user.Profile.ProfileProperties) { - string value = propertyAccess.GetProperty( + string value = propertyAccess.GetProperty( property.PropertyName, string.Empty, Thread.CurrentThread.CurrentUICulture, @@ -113,7 +113,7 @@ public Dictionary ProfileProperties properties[property.PropertyName] = string.IsNullOrEmpty(value) ? string.Empty : Common.Utilities.HtmlUtils.Clean(HttpUtility.HtmlDecode(value), false); } - + return properties; } } diff --git a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs index b7f34e35750..6dd9d1dc9dc 100644 --- a/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs +++ b/DNN Platform/Modules/MemberDirectory/Services/MemberDirectoryController.cs @@ -26,18 +26,18 @@ namespace DotNetNuke.Modules.MemberDirectory.Services [DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)] public class MemberDirectoryController : DnnApiController { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MemberDirectoryController)); - + 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; - } - + 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"); @@ -74,7 +74,128 @@ public HttpResponseMessage BasicSearch(int groupId, string searchTerm, int pageI return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } - + + [HttpGet] + public HttpResponseMessage GetMember(int userId) + { + try + { + var users = new List(); + var user = UserController.GetUserById(this.PortalSettings.PortalId, userId); + users.Add(user); + + 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 GetSuggestions(int groupId, string displayName) + { + try + { + var names = (from UserInfo user in this.GetUsers(-1, groupId, displayName.Trim(), 0, 10, string.Empty, string.Empty) + select new { label = user.DisplayName, value = user.DisplayName, userId = user.UserID }) + .ToList(); + + return this.Request.CreateResponse(HttpStatusCode.OK, names); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage AcceptFriend(FriendDTO postData) + { + try + { + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); + FriendsController.Instance.AcceptFriend(friend); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage AddFriend(FriendDTO postData) + { + try + { + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); + FriendsController.Instance.AddFriend(friend); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage Follow(FollowDTO postData) + { + try + { + var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); + FollowersController.Instance.FollowUser(follow); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage RemoveFriend(FriendDTO postData) + { + try + { + var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); + FriendsController.Instance.DeleteFriend(friend); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + catch (Exception exc) + { + Logger.Error(exc); + return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); + } + } + + [HttpPost] + [ValidateAntiForgeryToken] + public HttpResponseMessage UnFollow(FollowDTO postData) + { + try + { + var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); + FollowersController.Instance.UnFollowUser(follow); + return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); + } + 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)) @@ -86,7 +207,7 @@ private static void AddSearchTerm(ref string propertyNames, ref string propertyV { value = GetMatchedListEntryIds(name, value); } - + propertyValues += value + ","; } } @@ -109,7 +230,7 @@ private static string GetSetting(IDictionary settings, string key, string defaul { setting = Convert.ToString(settings[key]); } - + return setting; } @@ -130,7 +251,7 @@ private bool CanViewGroupMembers(int portalId, int groupId) { canView = ModulePermissionController.CanViewModule(this.ActiveModule) && group.IsPublic; } - + return canView; } @@ -184,7 +305,7 @@ private IEnumerable GetUsers(int userId, int groupId, string searchTer { groupId = int.Parse(filterValue); } - + if (this.CanViewGroupMembers(portalId, groupId)) { users = UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, @@ -197,7 +318,7 @@ private IEnumerable GetUsers(int userId, int groupId, string searchTer { users = new List(); } - + break; case "Relationship": users = UserController.Instance.GetUsersAdvancedSearch(portalId, this.PortalSettings.UserId, userId, -1, @@ -225,141 +346,20 @@ private IEnumerable GetUsers(int userId, int groupId, string searchTer propertyNames, propertyValues); break; } - + if (excludeHostUsers) { return this.FilterExcludedUsers(users); } - + return users; } private IEnumerable FilterExcludedUsers(IEnumerable users) { return users.Where(u => !u.IsSuperUser).Select(u => u).ToList(); - } - - [HttpGet] - public HttpResponseMessage GetMember(int userId) - { - try - { - var users = new List(); - var user = UserController.GetUserById(this.PortalSettings.PortalId, userId); - users.Add(user); - - 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 GetSuggestions(int groupId, string displayName) - { - try - { - var names = (from UserInfo user in this.GetUsers(-1, groupId, displayName.Trim(), 0, 10, string.Empty, string.Empty) - select new { label = user.DisplayName, value = user.DisplayName, userId = user.UserID }) - .ToList(); - - return this.Request.CreateResponse(HttpStatusCode.OK, names); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } } - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage AcceptFriend(FriendDTO postData) - { - try - { - var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); - FriendsController.Instance.AcceptFriend(friend); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage AddFriend(FriendDTO postData) - { - try - { - var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); - FriendsController.Instance.AddFriend(friend); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage Follow(FollowDTO postData) - { - try - { - var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); - FollowersController.Instance.FollowUser(follow); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage RemoveFriend(FriendDTO postData) - { - try - { - var friend = UserController.GetUserById(this.PortalSettings.PortalId, postData.FriendId); - FriendsController.Instance.DeleteFriend(friend); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - - [HttpPost] - [ValidateAntiForgeryToken] - public HttpResponseMessage UnFollow(FollowDTO postData) - { - try - { - var follow = UserController.GetUserById(this.PortalSettings.PortalId, postData.FollowId); - FollowersController.Instance.UnFollowUser(follow); - return this.Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }); - } - catch (Exception exc) - { - Logger.Error(exc); - return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); - } - } - public class FollowDTO { public int FollowId { get; set; } @@ -368,6 +368,6 @@ public class FollowDTO public class FriendDTO { public int FriendId { get; set; } - } + } } } diff --git a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs index 197b2ba7426..7420fd37935 100644 --- a/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/Settings.ascx.cs @@ -28,7 +28,7 @@ namespace DotNetNuke.Modules.MemberDirectory public partial class Settings : SettingsView { public const int DefaultPageSize = 20; - + private static string templatePath = "~/DesktopModules/MemberDirectory/Templates/"; private string _defaultSearchField1 = "DisplayName"; @@ -57,7 +57,7 @@ public static string DefaultAlternateItemTemplate { template = sr.ReadToEnd(); } - + return template; } } @@ -71,7 +71,7 @@ public static string DefaultItemTemplate { template = sr.ReadToEnd(); } - + return template; } } @@ -85,7 +85,7 @@ public static string DefaultPopUpTemplate { template = sr.ReadToEnd(); } - + return template; } } @@ -118,11 +118,11 @@ protected override void OnLoad(EventArgs e) { this.relationShipList.AddItem(Localization.GetString(rel.Name, Localization.SharedResourceFile), rel.RelationshipId.ToString()); } - + var profileResourceFile = "~/DesktopModules/Admin/Security/App_LocalResources/Profile.ascx"; - + System.Web.UI.WebControls.ListItemCollection propertiesCollection = this.GetPropertiesCollection(profileResourceFile); - + // Bind the ListItemCollection to the list this.propertyList.DataSource = propertiesCollection; this.propertyList.DataBind(); @@ -285,7 +285,7 @@ private ListItem AddSearchItem(string name, string resourceKey) { text = resourceKey; } - + var item = new ListItem(text, name); return item; } diff --git a/DNN Platform/Modules/MemberDirectory/View.ascx.cs b/DNN Platform/Modules/MemberDirectory/View.ascx.cs index 9bb03aca794..8c13c296854 100644 --- a/DNN Platform/Modules/MemberDirectory/View.ascx.cs +++ b/DNN Platform/Modules/MemberDirectory/View.ascx.cs @@ -32,7 +32,7 @@ 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); } @@ -47,24 +47,6 @@ 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 { @@ -85,7 +67,7 @@ protected int GroupId { groupId = int.Parse(this.Request.Params["GroupId"]); } - + return groupId; } } @@ -161,8 +143,26 @@ protected PortalSettings PortalSettings protected UserInfo UserInfo { get { return UserController.Instance.GetCurrentUserInfo(); } - } - + } + + 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); + } + private void AddIe7StyleSheet() { var browser = this.Request.Browser; @@ -180,7 +180,7 @@ private string GetSetting(Hashtable settings, string key, string defaultValue) { setting = Convert.ToString(settings[key]); } - + return setting; } @@ -191,8 +191,8 @@ private int GetSettingAsInt32(Hashtable settings, string key, int defaultValue) { setting = Convert.ToInt32(settings[key]); } - + return setting; - } + } } } diff --git a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs index 406babb8f74..cdb39dad79b 100644 --- a/DNN Platform/Modules/RazorHost/AddScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/AddScript.ascx.cs @@ -16,8 +16,8 @@ namespace DotNetNuke.Modules.RazorHost [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] public partial class AddScript : ModuleUserControlBase { - private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; private readonly INavigationManager _navigationManager; + private string razorScriptFileFormatString = "~/DesktopModules/RazorModules/RazorHost/Scripts/{0}"; public AddScript() { @@ -42,11 +42,6 @@ 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) { @@ -91,6 +86,11 @@ protected void cmdAdd_Click(object sender, EventArgs e) } } + private void DisplayExtension() + { + this.fileExtension.Text = "." + this.scriptFileType.SelectedValue.ToLowerInvariant(); + } + private void scriptFileType_SelectedIndexChanged(object sender, EventArgs e) { this.DisplayExtension(); diff --git a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs index bd635fe9a12..a1e94f8ca38 100644 --- a/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs +++ b/DNN Platform/Modules/RazorHost/CreateModule.ascx.cs @@ -57,7 +57,7 @@ protected string RazorScriptFile { m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } - + return m_RazorScriptFile; } } @@ -166,7 +166,7 @@ private void Create() { Logger.Error(ex); } - + // Optionally goto new Page if (this.chkAddPage.Checked) { @@ -272,7 +272,7 @@ private void LoadScripts() { item.Selected = true; } - + this.scriptList.Items.Add(item); } } diff --git a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs index 7eb84b83271..be47237ac5f 100644 --- a/DNN Platform/Modules/RazorHost/EditScript.ascx.cs +++ b/DNN Platform/Modules/RazorHost/EditScript.ascx.cs @@ -39,7 +39,7 @@ protected string RazorScriptFile { m_RazorScriptFile = string.Format(this.razorScriptFileFormatString, scriptFileSetting); } - + return m_RazorScriptFile; } } @@ -81,7 +81,7 @@ private void LoadScripts() { item.Selected = true; } - + this.scriptList.Items.Add(item); } } diff --git a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs index 3054eeaec5a..4e0f9235d77 100644 --- a/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs +++ b/DNN Platform/Modules/RazorHost/RazorHost.ascx.cs @@ -15,14 +15,14 @@ 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")] public ModuleActionCollection ModuleActions { get { var Actions = new ModuleActionCollection(); - Actions.Add( + Actions.Add( this.ModuleContext.GetNextActionID(), Localization.GetString(ModuleActionType.EditContent, this.LocalResourceFile), ModuleActionType.AddContent, @@ -33,7 +33,7 @@ public ModuleActionCollection ModuleActions SecurityAccessLevel.Host, true, false); - Actions.Add( + Actions.Add( this.ModuleContext.GetNextActionID(), Localization.GetString("CreateModule.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -46,7 +46,7 @@ public ModuleActionCollection ModuleActions false); return Actions; } - } + } [Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")] protected override string RazorScriptFile @@ -59,9 +59,9 @@ protected override string RazorScriptFile { 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 80235e66cf9..ee6efab4453 100644 --- a/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs +++ b/DNN Platform/Modules/RazorHost/RazorHostSettingsExtensions.cs @@ -22,21 +22,21 @@ public static Settings LoadRazorSettingsControl(this UserControl parent, ModuleI EnsureEditScriptControlIsRegistered(configuration.ModuleDefID); return control; } - + private static void EnsureEditScriptControlIsRegistered(int moduleDefId) { - if (ModuleControlController.GetModuleControlByControlKey("EditRazorScript", moduleDefId) != null) - { - return; - } - - var m = new ModuleControlInfo - { - ControlKey = "EditRazorScript", - ControlSrc = "DesktopModules/RazorModules/RazorHost/EditScript.ascx", - ControlTitle = "Edit Script", - ControlType = SecurityAccessLevel.Host, - ModuleDefID = moduleDefId, + if (ModuleControlController.GetModuleControlByControlKey("EditRazorScript", moduleDefId) != null) + { + return; + } + + 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 81bdf8f15d7..3ecd7357f0e 100644 --- a/DNN Platform/Modules/RazorHost/Settings.ascx.cs +++ b/DNN Platform/Modules/RazorHost/Settings.ascx.cs @@ -28,7 +28,7 @@ public override void LoadSettings() { item.Selected = true; } - + this.scriptList.Items.Add(item); } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs index 737a1a01349..aa95936b2c6 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookClient.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Authentication.Facebook.Components using DotNetNuke.Services.Authentication.OAuth; public class FacebookClient : OAuthClientBase - { + { public FacebookClient(int portalId, AuthMode mode) : base(portalId, mode, "Facebook") { @@ -27,8 +27,8 @@ public FacebookClient(int portalId, AuthMode mode) this.OAuthVersion = "2.0"; this.LoadTokenCookie(string.Empty); - } - + } + protected override TimeSpan GetExpiry(string responseText) { TimeSpan expiry = TimeSpan.MinValue; @@ -37,7 +37,7 @@ protected override TimeSpan GetExpiry(string responseText) var dictionary = Json.Deserialize>(responseText); expiry = new TimeSpan(0, 0, Convert.ToInt32(dictionary["expires_in"])); } - + return expiry; } @@ -49,7 +49,7 @@ protected override string GetToken(string responseText) var dictionary = Json.Deserialize>(responseText); authToken = Convert.ToString(dictionary["access_token"]); } - + return authToken; } } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs index 7d28ae96d4b..643c2b3a4bf 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Components/FacebookUserData.cs @@ -10,7 +10,7 @@ namespace DotNetNuke.Authentication.Facebook.Components [DataContract] public class FacebookUserData : UserData - { + { public override string FirstName { get { return this.FacebookFirstName; } @@ -21,8 +21,8 @@ public override string LastName { get { return this.FacebookLastName; } set { } - } - + } + [DataMember(Name = "birthday")] public string Birthday { get; set; } 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 4c55495c0eb..ab8c1efc19a 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Facebook/Login.ascx.cs @@ -18,7 +18,7 @@ public override bool SupportsRegistration { get { return true; } } - + protected override string AuthSystemApplicationName { get { return "Facebook"; } @@ -47,7 +47,7 @@ protected override void AddCustomProperties(NameValueCollection properties) base.AddCustomProperties(properties); var facebookUserData = this.OAuthClient.GetCurrentUser(); - if (facebookUserData.Link != null) + if (facebookUserData.Link != null) { properties.Add("Facebook", facebookUserData.Link.ToString()); } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs index 6ea653bb010..795005cbd76 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleClient.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Authentication.Google.Components using DotNetNuke.Services.Authentication.OAuth; public class GoogleClient : OAuthClientBase - { + { public GoogleClient(int portalId, AuthMode mode) : base(portalId, mode, "Google") { @@ -28,8 +28,8 @@ public GoogleClient(int portalId, AuthMode mode) this.OAuthVersion = "2.0"; this.LoadTokenCookie(string.Empty); - } - + } + protected override TimeSpan GetExpiry(string responseText) { var jsonSerializer = new JavaScriptSerializer(); diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs index 3bb6852c31a..bdeae89410b 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Components/GoogleUserData.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Authentication.Google.Components [DataContract] public class GoogleUserData : UserData - { + { public override string FirstName { get { return this.GivenName; } @@ -26,8 +26,8 @@ public override string ProfileImage { get { return this.Picture; } set { } - } - + } + [DataMember(Name = "given_name")] public string GivenName { get; set; } 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 4c328f94fb0..25a83e0bd85 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Google/Login.ascx.cs @@ -17,7 +17,7 @@ public override bool SupportsRegistration { get { return true; } } - + protected override string AuthSystemApplicationName { get { return "Google"; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs index 390aa06ff1c..b4e713b7734 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveClient.cs @@ -12,8 +12,8 @@ namespace DotNetNuke.Authentication.LiveConnect.Components using DotNetNuke.Services.Authentication.OAuth; public class LiveClient : OAuthClientBase - { - public LiveClient(int portalId, AuthMode mode) + { + public LiveClient(int portalId, AuthMode mode) : base(portalId, mode, "Live") { // DNN-6464 Correct TokenEndpoint and AuthorizationEndpoint Urls @@ -30,8 +30,8 @@ public LiveClient(int portalId, AuthMode mode) this.OAuthVersion = "2.0"; this.LoadTokenCookie(string.Empty); - } - + } + protected override TimeSpan GetExpiry(string responseText) { var jsonSerializer = new JavaScriptSerializer(); diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs index a5f50d71bd7..0f2c71fa787 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Components/LiveUserData.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Authentication.LiveConnect.Components [DataContract] public class LiveUserData : UserData - { + { public override string FirstName { get { return this.LiveFirstName; } @@ -22,8 +22,8 @@ public override string LastName { get { return this.LiveLastName; } set { } - } - + } + [DataMember(Name = "link")] public Uri Link { get; set; } 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 0051d01ef6b..8b09265ffc5 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.LiveConnect/Login.ascx.cs @@ -17,7 +17,7 @@ public override bool SupportsRegistration { get { return true; } } - + protected override string AuthSystemApplicationName { get { return "Live"; } diff --git a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs index 7f01a498645..f2157f23081 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Components/TwitterUserData.cs @@ -9,7 +9,7 @@ namespace DotNetNuke.Authentication.Twitter.Components [DataContract] public class TwitterUserData : UserData - { + { public override string DisplayName { get { return this.ScreenName; } @@ -32,8 +32,8 @@ public override string Website { get { return this.Url; } set { } - } - + } + [DataMember(Name = "screen_name")] public string ScreenName { get; set; } 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 9b386f7d239..c235c0342f8 100644 --- a/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs +++ b/DNN Platform/Providers/AuthenticationProviders/DotNetNuke.Authentication.Twitter/Login.ascx.cs @@ -17,7 +17,7 @@ public override bool SupportsRegistration { get { return true; } } - + protected override string AuthSystemApplicationName { get { return "Twitter"; } 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 9e5a2d48509..c8770a87643 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmCachingProvider.cs @@ -23,20 +23,20 @@ public class SimpleWebFarmCachingProvider : CachingProvider { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SimpleWebFarmCachingProvider)); - private readonly int executionTimeout = 5000; // Limit timeout to 5 seconds as cache operations should be quick - + 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 + if (CacheExpirationDisable) + { + return; + } + + // Notify other servers this.NotifyOtherServers("Clear~" + type, data); } @@ -46,15 +46,15 @@ public override void Remove(string key) this.RemoveInternal(key); // Per API implementation standards only notify others if expiration has not been disabled - if (CacheExpirationDisable) - { - return; - } - - // Notify Other Servers + if (CacheExpirationDisable) + { + return; + } + + // Notify Other Servers this.NotifyOtherServers("Remove", key); - } - + } + /// /// This method responds to an incoming request to process synchronization from an additional server. /// @@ -78,31 +78,31 @@ internal void ProcessSynchronizationRequest(string command, string detail) var commandParts = command.Split('~'); this.ClearCacheInternal(commandParts[1], detail, true); } - } - + } + private static void HandleNotificationTimeout(object state, bool timedOut) { - if (!timedOut) - { - return; - } - - // Abort if possible + 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 - if (Globals.Status != Globals.UpgradeStatus.None) - { - return; - } - - // Get all servers currently in the database that could be used for synchronization, excluding this one - // But focus on only servers that could be used for this application and notifications - // including activity within 60 minutes + if (Globals.Status != Globals.UpgradeStatus.None) + { + return; + } + + // Get all servers currently in the database that could be used for synchronization, excluding this one + // But focus on only servers that could be used for this application and notifications + // including activity within 60 minutes var lastActivityDate = DateTime.Now.AddHours(-1); var additionalServers = ServerController.GetEnabledServers() .Where(s => !string.IsNullOrWhiteSpace(s.Url) @@ -111,12 +111,12 @@ private void NotifyOtherServers(string command, string detail) .ToList(); // If we have no additional servers do nothing - if (additionalServers.Count == 0) - { - return; - } - - // Otherwise notify each server + if (additionalServers.Count == 0) + { + return; + } + + // Otherwise notify each server foreach (var server in additionalServers) { // Setup parameters for sending @@ -152,12 +152,12 @@ private void OnServerNotificationCompleteCallback(IAsyncResult asynchronousResul using (var response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) { // If status code is ok do nothing - if (response.StatusCode == HttpStatusCode.OK) - { - return; - } - - // Otherwise log the failure + if (response.StatusCode == HttpStatusCode.OK) + { + return; + } + + // Otherwise log the failure Exceptions.LogException(new ApplicationException( $"Error sending cache server notification. Url: {request.RequestUri.AbsoluteUri} with a status code {response.StatusCode}")); } 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 9cc193912cb..e4facf901a2 100644 --- a/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs +++ b/DNN Platform/Providers/CachingProviders/DotNetNuke.Providers.Caching.SimpleWebFarmCachingProvider/SimpleWebFarmSynchronizationHandler.cs @@ -20,27 +20,27 @@ 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 - if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"])) - { - return; // No command we cannot process - } - - if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"])) - { - return; // No action we cannot return - } - - // Only continue if our provider is current - if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)) - { - return; - } - - // Get the values, noting that if in debug we are not encrypted + if (string.IsNullOrWhiteSpace(context.Request.QueryString["command"])) + { + return; // No command we cannot process + } + + if (string.IsNullOrWhiteSpace(context.Request.QueryString["detail"])) + { + return; // No action we cannot return + } + + // Only continue if our provider is current + if (!(CachingProvider.Instance() is Caching.SimpleWebFarmCachingProvider.SimpleWebFarmCachingProvider)) + { + return; + } + + // Get the values, noting that if in debug we are not encrypted var command = Host.DebugMode ? context.Request.QueryString["command"] : UrlUtils.DecryptParameter(context.Request.QueryString["command"], Host.GUID); diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs index 404883c9bde..ff9e6aa347e 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/AspNetClientCapability.cs @@ -24,18 +24,28 @@ public class AspNetClientCapability : Services.ClientCapability.ClientCapability 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"; + private const string LinuxAgent = "linux "; + private const string UnixAgent = "i686"; + private const string UnixAgent2 = "i586"; + private const string UnixAgent3 = "i386"; + private const string X11Agent = "x11"; + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AspNetClientCapability)); + 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 readonly char[] Separators = { ';', ')' }; + private readonly IDictionary _properties; - - /// + + /// /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// @@ -59,7 +69,7 @@ public AspNetClientCapability(string userAgent, HttpCapabilitiesBase browserCaps { this.Capabilities = new Dictionary(); } - + this.SupportsFlash = false; this.HtmlPreferedDTD = null; @@ -81,18 +91,18 @@ public AspNetClientCapability(string userAgent, HttpCapabilitiesBase browserCaps Logger.Error(ex); } } - } - - /// + } + + /// /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// - public AspNetClientCapability(HttpRequest request) + public AspNetClientCapability(HttpRequest request) : this(request.UserAgent ?? string.Empty, request.Browser) { - } - - /// + } + + /// /// Initializes a new instance of the class. /// Constructs a new instance of ClientCapability. /// @@ -107,7 +117,7 @@ public AspNetClientCapability(IDictionary properties) this.IsMobile = GetBoolValue(this._properties, "IsMobile"); this.ScreenResolutionWidthInPixels = GetIntValue(this._properties, "ScreenPixelsWidth"); this.ScreenResolutionHeightInPixels = GetIntValue(this._properties, "ScreenPixelsHeight"); - + // Set Premium properties this.IsTablet = GetBoolValue(this._properties, "IsTablet"); this.IsTouchScreen = GetBoolValue(this._properties, "HasTouchScreen"); @@ -118,12 +128,12 @@ public AspNetClientCapability(IDictionary properties) this.HtmlPreferedDTD = null; // set IsMobile to false when IsTablet is true. - if (this.IsTablet) - { - this.IsMobile = false; - } + if (this.IsTablet) + { + this.IsMobile = false; + } } - } + } public override string this[string name] { @@ -136,8 +146,8 @@ public override string this[string 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 /// keys and values held in the browser capabilities provided. The value string may @@ -161,11 +171,11 @@ private static bool GetBoolValue(IDictionary properties, string { bool value; if (properties.ContainsKey(property) && - bool.TryParse(properties[property], out value)) - { - return value; - } - + bool.TryParse(properties[property], out value)) + { + return value; + } + return false; } @@ -180,11 +190,11 @@ private static int GetIntValue(IDictionary properties, string pr { int value; if (properties.ContainsKey(property) && - int.TryParse(properties[property], out value)) - { - return value; - } - + int.TryParse(properties[property], out value)) + { + return value; + } + return 0; } @@ -273,12 +283,12 @@ private static void DetectOperatingSystem(string userAgent, IDictionary public class AspNetClientCapabilityProvider : ClientCapabilityProvider - { + { private static readonly object _allCapabilitiesLock = new object(); - private static IQueryable _allCapabilities; private static readonly object _allClientCapabilityValuesLock = new object(); + private static IQueryable _allCapabilities; 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 { @@ -52,7 +52,7 @@ private static IQueryable AllCapabilities } } } - + return _allCapabilities; } } @@ -86,7 +86,7 @@ private static IDictionary> ClientCapabilityValues { return HighPiorityCapabilityValues[kvp.Key]; } - + return 0; }).ThenBy(kvp => kvp.Key).ToDictionary(pair => pair.Key, pair => pair.Value); } @@ -113,7 +113,7 @@ private static IDictionary HighPiorityCapabilityValues { "HardwareVendor", 55 }, }); } - } + } private static IDictionary DummyProperties { @@ -133,7 +133,7 @@ private static IDictionary DummyProperties }); } } - + public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollection headers, string userAgent) { var factory = new BrowserCapabilitiesFactory(); @@ -144,11 +144,11 @@ public static HttpBrowserCapabilities GetHttpBrowserCapabilities(NameValueCollec factory.ConfigureBrowserCapabilities(headers, browserCaps); factory.ConfigureCustomCapabilities(headers, browserCaps); return browserCaps; - } + } /// /// Returns ClientCapability based on the user agent provided. - /// + /// /// public override IClientCapability GetClientCapability(string userAgent) { @@ -162,7 +162,7 @@ public override IClientCapability GetClientCapability(string userAgent) /// /// Returns ClientCapability based on device Id provided. - /// + /// /// public override IClientCapability GetClientCapabilityById(string deviceId) { @@ -192,6 +192,6 @@ public override IDictionary> GetAllClientCapabilityValues() public override IQueryable GetAllClientCapabilities() { return AllCapabilities; - } + } } } diff --git a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs index 3b2666fe18c..854147be87f 100644 --- a/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs +++ b/DNN Platform/Providers/ClientCapabilityProviders/Provider.AspNetCCP/Components/FeatureController.cs @@ -28,9 +28,9 @@ namespace DotNetNuke.Providers.AspNetClientCapabilityProvider.Components /// /// ----------------------------------------------------------------------------- public class FeatureController : IUpgradeable - { - private const string ResourceFileRelativePath = "~/Providers/ClientCapabilityProviders/AspNetClientCapabilityProvider/App_LocalResources/SharedResources.resx"; - + { + private const string ResourceFileRelativePath = "~/Providers/ClientCapabilityProviders/AspNetClientCapabilityProvider/App_LocalResources/SharedResources.resx"; + /// /// Handles upgrading the module and adding the module to the hosts menu. /// @@ -44,11 +44,11 @@ public string UpgradeModule(string version) var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.Name == Constants.PackageName); var moduleTabs = TabController.Instance.GetTabsByPackageID(-1, package.PackageID, false); - if (moduleTabs.Count > 0) - { - return string.Empty; - } - + if (moduleTabs.Count > 0) + { + return string.Empty; + } + this.RemoveWurflProvider(); break; } @@ -78,9 +78,9 @@ private static IDictionary CreateMappedCapabilities() mappingCapabilites.Add("physical_screen_height", "ScreenMMHeight"); mappingCapabilites.Add("physical_screen_width", "ScreenMMWidth"); } - + return mappingCapabilites; - } + } private void RemoveWurflProvider() { diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs index 93d42b82374..30a9891092b 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureFolderProvider.cs @@ -40,7 +40,7 @@ protected override string FileNotFoundMessage return "Azure File Not Found"; } } - + protected override string ObjectCacheKey { get { return "Azure_Object_{0}_{1}"; } @@ -49,8 +49,8 @@ protected override string ObjectCacheKey protected override string ListObjectsCacheKey { get { return "Azure_ListObjects_{0}"; } - } - + } + /// /// 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. @@ -65,7 +65,7 @@ public override void AddFolder(string folderPath, FolderMappingInfo folderMappin /// /// Gets the direct Url to the file. - /// + /// /// public override string GetFileUrl(IFileInfo file) { @@ -139,7 +139,30 @@ public override string GetFileUrl(IFileInfo file) return FileLinkClickController.Instance.GetFileLinkClick(file); } - + + /// + /// Gets the URL of the image to display in FileManager tree. + /// + /// + public override string GetFolderProviderIconPath() + { + return Globals.ResolveUrl("~/Providers/FolderProviders/AzureFolderProvider/images/FolderAzure_32x32_Standard.png"); + } + + public List GetAllContainers(FolderMappingInfo folderMapping) + { + List containers = new List(); + var accountName = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountName); + var accountKey = this.GetEncryptedSetting(folderMapping.FolderMappingSettings, Constants.AccountKey); + var useHttps = GetBooleanSetting(folderMapping, Constants.UseHttps); + + var sc = new StorageCredentials(accountName, accountKey); + var csa = new CloudStorageAccount(sc, useHttps); + var blobClient = csa.CreateCloudBlobClient(); + blobClient.ListContainers().ToList().ForEach(x => containers.Add(x.Name)); + return containers; + } + protected override void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri) { var container = this.GetContainer(folderMapping); @@ -161,34 +184,6 @@ 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) { @@ -211,8 +206,8 @@ protected override IList GetObjectList(FolderMappingInfo fol { var cacheKey = string.Format(this.ListObjectsCacheKey, folderMapping.FolderMappingID); - return CBO.GetCachedObject>( - new CacheItemArgs( + return CBO.GetCachedObject>( + new CacheItemArgs( cacheKey, this.ListObjectsCacheTimeout, CacheItemPriority.Default, @@ -288,29 +283,34 @@ protected override void UpdateFileInternal(Stream stream, FolderMappingInfo fold blob.SetProperties(); this.ClearCache(folderMapping.FolderMappingID); - } + } - /// - /// Gets the URL of the image to display in FileManager tree. - /// - /// - public override string GetFolderProviderIconPath() + private static void CheckSettings(FolderMappingInfo folderMapping) { - return Globals.ResolveUrl("~/Providers/FolderProviders/AzureFolderProvider/images/FolderAzure_32x32_Standard.png"); + 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."); + } } - public List GetAllContainers(FolderMappingInfo folderMapping) + private CloudBlobContainer GetContainer(FolderMappingInfo folderMapping) { - List containers = new List(); + 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(); - blobClient.ListContainers().ToList().ForEach(x => containers.Add(x.Name)); - return containers; - } + return blobClient.GetContainerReference(container); + } } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs index 5031f811a20..3c3665905f4 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/AzureRemoteStorageItem.cs @@ -12,8 +12,6 @@ namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider [Serializable] public class AzureRemoteStorageItem : IRemoteStorageItem { - public AzureBlob Blob { get; set; } - public string Key { get @@ -28,5 +26,6 @@ public string Key public long Size => this.Blob.Length; public string HashCode => this.Blob.ETag; + public AzureBlob Blob { get; set; } } } diff --git a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs index 75f28e002a9..44fe20a3e28 100644 --- a/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs +++ b/DNN Platform/Providers/FolderProviders/AzureFolderProvider/Settings.ascx.cs @@ -21,8 +21,8 @@ namespace DotNetNuke.Providers.FolderProviders.AzureFolderProvider /// public partial class Settings : FolderMappingSettingsControlBase { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Settings)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Settings)); + /// /// Loads concrete settings. /// @@ -121,17 +121,17 @@ public override void UpdateSettings(int folderMappingID) folderMapping.FolderMappingSettings[Constants.SyncBatchSize] = synchBatchSize; folderMappingController.UpdateFolderMapping(folderMapping); - } - + } + /// /// protected void ddlContainers_SelectedIndexChanged(object sender, EventArgs e) { - if (this.ddlContainers.SelectedIndex != 1) - { - return; - } - + if (this.ddlContainers.SelectedIndex != 1) + { + return; + } + if (this.tbAccountName.Text.Trim().Length > 0 && this.tbAccountKey.Text.Trim().Length > 0) { this.ddlContainers.Items.Clear(); @@ -161,7 +161,40 @@ protected void btnNewContainer_Click(object sender, EventArgs e) this.SelectContainerPanel.Visible = false; this.CreateContainerPanel.Visible = true; } - + + /// + /// + protected void btnSelectExistingContainer_Click(object sender, EventArgs e) + { + this.SelectContainerPanel.Visible = true; + this.CreateContainerPanel.Visible = false; + } + + /// + /// + protected void valContainerName_ServerValidate(object source, ServerValidateEventArgs args) + { + if (this.SelectContainerPanel.Visible) + { + if (this.ddlContainers.SelectedIndex > 1) + { + args.IsValid = true; + return; + } + } + else + { + if (this.tbContainerName.Text.Trim().Length > 0) + { + args.IsValid = true; + return; + } + } + + this.valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", this.LocalResourceFile); + args.IsValid = false; + } + private static bool AreThereFolderMappingsWithSameSettings(FolderMappingInfo folderMapping, string accountName, string container) { var folderMappingController = FolderMappingController.Instance; @@ -189,10 +222,10 @@ private string GetContainer() else { container = this.tbContainerName.Text.Trim().ToLowerInvariant(); - if (!this.CreateContainer(container)) - { - throw new Exception(); - } + if (!this.CreateContainer(container)) + { + throw new Exception(); + } } return container; @@ -242,7 +275,7 @@ private bool CreateContainer(string containerName) switch (ex.RequestInformation.ExtendedErrorInformation.ErrorCode) { case "AccountNotFound": - this.valContainerName.ErrorMessage = Localization.GetString( + this.valContainerName.ErrorMessage = Localization.GetString( "AccountNotFound.ErrorMessage", this.LocalResourceFile); break; @@ -251,7 +284,7 @@ private bool CreateContainer(string containerName) "AuthenticationFailure.ErrorMessage", this.LocalResourceFile); break; case "AccessDenied": - this.valContainerName.ErrorMessage = Localization.GetString( + this.valContainerName.ErrorMessage = Localization.GetString( "AccessDenied.ErrorMessage", this.LocalResourceFile); break; @@ -259,7 +292,7 @@ private bool CreateContainer(string containerName) return true; default: Logger.Error(ex); - this.valContainerName.ErrorMessage = Localization.GetString( + this.valContainerName.ErrorMessage = Localization.GetString( "NewContainer.ErrorMessage", this.LocalResourceFile); break; @@ -360,39 +393,6 @@ private void LoadContainers() this.valContainerName.ErrorMessage = Localization.GetString("ListContainers.ErrorMessage", this.LocalResourceFile); this.valContainerName.IsValid = false; } - } - - /// - /// - protected void btnSelectExistingContainer_Click(object sender, EventArgs e) - { - this.SelectContainerPanel.Visible = true; - this.CreateContainerPanel.Visible = false; } - - /// - /// - protected void valContainerName_ServerValidate(object source, ServerValidateEventArgs args) - { - if (this.SelectContainerPanel.Visible) - { - if (this.ddlContainers.SelectedIndex > 1) - { - args.IsValid = true; - return; - } - } - else - { - if (this.tbContainerName.Text.Trim().Length > 0) - { - args.IsValid = true; - return; - } - } - - this.valContainerName.ErrorMessage = Localization.GetString("valContainerName.ErrorMessage", this.LocalResourceFile); - args.IsValid = false; - } } } diff --git a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs index 947288712f6..572a7691a96 100644 --- a/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs +++ b/DNN Platform/Providers/FolderProviders/Components/BaseRemoteStorageProvider.cs @@ -19,10 +19,10 @@ namespace DotNetNuke.Providers.FolderProviders.Components using DotNetNuke.Services.FileSystem; public abstract class BaseRemoteStorageProvider : FolderProvider - { + { private readonly string _encryptionKey = Host.GUID; - private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance; - + private readonly PortalSecurity _portalSecurity = PortalSecurity.Instance; + public override bool SupportsMappedPaths { get { return true; } @@ -32,7 +32,12 @@ public override bool SupportsMoveFile { get { return false; } } - + + public override bool SupportsMoveFolder + { + get { return true; } + } + protected virtual string FileNotFoundMessage { get { return string.Empty; } @@ -47,25 +52,6 @@ protected virtual int ObjectCacheTimeout { get { return 150; } } - - private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key) - { - var cacheKey = string.Format(this.ObjectCacheKey, folderMapping.FolderMappingID, key); - - return CBO.GetCachedObject( - new CacheItemArgs( - cacheKey, - this.ObjectCacheTimeout, - CacheItemPriority.Default, - folderMapping.FolderMappingID), - c => - { - var list = this.GetObjectList(folderMapping, key); - - // return list.FirstOrDefault(i => i.Key == key); - return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); - }); - } protected virtual string ListObjectsCacheKey { @@ -75,13 +61,8 @@ protected virtual string ListObjectsCacheKey protected virtual int ListObjectsCacheTimeout { get { return 300; } - } + } - public override bool SupportsMoveFolder - { - get { return true; } - } - /// /// Adds a new folder. /// @@ -102,61 +83,11 @@ public override void AddFile(IFolderInfo folder, string fileName, Stream content this.UpdateFile(folder, fileName, content); } - protected static bool GetBooleanSetting(FolderMappingInfo folderMapping, string settingName) - { - return bool.Parse(folderMapping.FolderMappingSettings[settingName].ToString()); - } - - protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string settingName, int defaultValue) - { - int value; - if (int.TryParse(GetSetting(folderMapping, settingName), out value)) - { - return value; - } - - return defaultValue; - } - - protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); - - protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); - - protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); - - protected static string GetSetting(FolderMappingInfo folderMapping, string settingName) - { - Requires.NotNull(nameof(folderMapping), folderMapping); - Requires.NotNullOrEmpty(nameof(settingName), settingName); - - 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); - - protected abstract void UpdateFileInternal(Stream stream, FolderMappingInfo folderMapping, string uri); - - protected virtual IRemoteStorageItem GetStorageItem(FolderMappingInfo folderMapping, string key) - { - return this.GetStorageItemInternal(folderMapping, key); - } - public virtual void ClearCache(int folderMappingId) { var cacheKey = string.Format(this.ListObjectsCacheKey, folderMappingId); DataCache.RemoveCache(cacheKey); - + // Clear cached objects DataCache.ClearCache(string.Format(this.ObjectCacheKey, folderMappingId, string.Empty)); } @@ -171,11 +102,11 @@ public override void CopyFile(string folderPath, string fileName, string newFold Requires.NotNull("newFolderPath", newFolderPath); Requires.NotNull("folderMapping", folderMapping); - if (folderPath == newFolderPath) - { - return; - } - + if (folderPath == newFolderPath) + { + return; + } + this.CopyFileInternal(folderMapping, folderPath + fileName, newFolderPath + fileName); } @@ -207,7 +138,7 @@ public override void DeleteFolder(IFolderInfo folder) /// /// Checks the existence of the specified file. - /// + ///
    /// public override bool FileExists(IFolderInfo folder, string fileName) { @@ -221,7 +152,7 @@ public override bool FileExists(IFolderInfo folder, string fileName) /// /// Checks the existence of the specified folder. - /// + ///
    /// public override bool FolderExists(string folderPath, FolderMappingInfo folderMapping) { @@ -241,7 +172,7 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap /// /// Amazon doesn't support file attributes. - /// + /// /// public override FileAttributes? GetFileAttributes(IFileInfo file) { @@ -250,7 +181,7 @@ public override bool FolderExists(string folderPath, FolderMappingInfo folderMap /// /// Gets the list of file names contained in the specified folder. - /// + ///
    /// public override string[] GetFiles(IFolderInfo folder) { @@ -267,7 +198,7 @@ public override string[] GetFiles(IFolderInfo folder) // select Path.GetFileName(f)).ToArray(); var pattern = "^" + mappedPath; return (from i in list - let f = i.Key + 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(); @@ -275,7 +206,7 @@ where f.StartsWith(mappedPath, true, CultureInfo.InvariantCulture) && f.Length > /// /// Gets the file length. - /// + ///
    /// public override long GetFileSize(IFileInfo file) { @@ -289,13 +220,13 @@ public override long GetFileSize(IFileInfo file) { throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } - + return item.Size; } /// /// Gets a file Stream of the specified file. - /// + ///
    /// public override Stream GetFileStream(IFileInfo file) { @@ -310,7 +241,7 @@ public override Stream GetFileStream(IFileInfo file) /// /// Gets a file Stream of the specified file. - /// + ///
    /// public override Stream GetFileStream(IFolderInfo folder, string fileName) { @@ -324,7 +255,7 @@ public override Stream GetFileStream(IFolderInfo folder, string fileName) /// /// Gets the time when the specified file was last modified. - /// + ///
    /// public override DateTime GetLastModificationTime(IFileInfo file) { @@ -338,13 +269,13 @@ public override DateTime GetLastModificationTime(IFileInfo file) { throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } - + return item.LastModified; } /// /// Gets the list of subfolders for the specified folder. - /// + ///
    /// public override IEnumerable GetSubFolders(string folderPath, FolderMappingInfo folderMapping) { @@ -355,15 +286,15 @@ 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 + 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 @@ -382,7 +313,7 @@ where f.StartsWith(folderPath, StringComparison.InvariantCultureIgnoreCase) ///
    /// /// For now, it returns false always until we find a better way to check if the file is synchronized. - /// + /// /// public override bool IsInSync(IFileInfo file) { @@ -446,7 +377,7 @@ public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttrib /// /// Amazon doesn't support file attributes. - /// + /// /// public override bool SupportsFileAttributes() { @@ -493,7 +424,7 @@ public override string GetHashCode(IFileInfo file) { throw new FileNotFoundException(this.FileNotFoundMessage, file.RelativePath); } - + return (item.Size == file.Size) ? item.HashCode : string.Empty; } @@ -503,8 +434,77 @@ public override string GetHashCode(IFileInfo file, Stream fileContent) { return this.GetHashCode(file); } - + return string.Empty; } + + protected static bool GetBooleanSetting(FolderMappingInfo folderMapping, string settingName) + { + return bool.Parse(folderMapping.FolderMappingSettings[settingName].ToString()); + } + + protected static int GetIntegerSetting(FolderMappingInfo folderMapping, string settingName, int defaultValue) + { + int value; + if (int.TryParse(GetSetting(folderMapping, settingName), out value)) + { + return value; + } + + return defaultValue; + } + + protected static string GetSetting(FolderMappingInfo folderMapping, string settingName) + { + Requires.NotNull(nameof(folderMapping), folderMapping); + Requires.NotNullOrEmpty(nameof(settingName), settingName); + + return folderMapping.FolderMappingSettings[settingName]?.ToString(); + } + + protected abstract void CopyFileInternal(FolderMappingInfo folderMapping, string sourceUri, string newUri); + + protected abstract void DeleteFileInternal(FolderMappingInfo folderMapping, string uri); + + protected abstract void DeleteFolderInternal(FolderMappingInfo folderMapping, IFolderInfo folder); + + 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); + + protected abstract void UpdateFileInternal(Stream stream, FolderMappingInfo folderMapping, string uri); + + protected virtual IRemoteStorageItem GetStorageItem(FolderMappingInfo folderMapping, string key) + { + return this.GetStorageItemInternal(folderMapping, key); + } + + private IRemoteStorageItem GetStorageItemInternal(FolderMappingInfo folderMapping, string key) + { + var cacheKey = string.Format(this.ObjectCacheKey, folderMapping.FolderMappingID, key); + + return CBO.GetCachedObject( + new CacheItemArgs( + cacheKey, + this.ObjectCacheTimeout, + CacheItemPriority.Default, + folderMapping.FolderMappingID), + c => + { + var list = this.GetObjectList(folderMapping, key); + + // return list.FirstOrDefault(i => i.Key == key); + return list.FirstOrDefault(i => i.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); + }); + } } } diff --git a/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs b/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs index 1a7b4fd157e..1857fb72d88 100644 --- a/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs +++ b/DNN Platform/Providers/FolderProviders/Components/BusinessController.cs @@ -27,7 +27,7 @@ public string UpgradeModule(string version) { DataProvider.Instance().UnRegisterAssembly(package.PackageID, "Microsoft.WindowsAzure.StorageClient.dll"); } - + break; } diff --git a/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs b/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs index d32c5a880ba..299aab2d922 100644 --- a/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs +++ b/DNN Platform/Providers/FolderProviders/Components/IRemoteStorageItem.cs @@ -9,9 +9,9 @@ namespace DotNetNuke.Providers.FolderProviders.Components public interface IRemoteStorageItem { string Key { get; } - + DateTime LastModified { get; } - + long Size { get; } string HashCode { get; } diff --git a/DNN Platform/Syndication/OPML/Opml.cs b/DNN Platform/Syndication/OPML/Opml.cs index 29c379918bd..24a743b5569 100644 --- a/DNN Platform/Syndication/OPML/Opml.cs +++ b/DNN Platform/Syndication/OPML/Opml.cs @@ -42,7 +42,7 @@ public DateTime UtcExpiry { return this._utcExpiry; } - + set { this._utcExpiry = value; @@ -55,7 +55,7 @@ public string Title { return this._title; } - + set { this._title = value; @@ -68,7 +68,7 @@ public DateTime DateCreated { return this._dateCreated; } - + set { this._dateCreated = value; @@ -81,7 +81,7 @@ public DateTime DateModified { return this._dateModified; } - + set { this._dateModified = value; @@ -94,7 +94,7 @@ public string OwnerName { return this._ownerName; } - + set { this._ownerName = value; @@ -107,7 +107,7 @@ public string OwnerEmail { return this._ownerEmail; } - + set { this._ownerEmail = value; @@ -120,7 +120,7 @@ public string OwnerId { return this._ownerId; } - + set { this._ownerId = value; @@ -133,7 +133,7 @@ public string Docs { return this._docs; } - + set { this._docs = value; @@ -146,7 +146,7 @@ public string ExpansionState { return this._expansionState; } - + set { this._expansionState = value; @@ -159,7 +159,7 @@ public string VertScrollState { return this._vertScrollState; } - + set { this._vertScrollState = value; @@ -172,7 +172,7 @@ public string WindowTop { return this._windowTop; } - + set { this._windowTop = value; @@ -185,7 +185,7 @@ public string WindowLeft { return this._windowLeft; } - + set { this._windowLeft = value; @@ -198,7 +198,7 @@ public string WindowBottom { return this._windowBottom; } - + set { this._windowBottom = value; @@ -211,7 +211,7 @@ public string WindowRight { return this._windowRight; } - + set { this._windowRight = value; @@ -224,7 +224,7 @@ public OpmlOutlines Outlines { return this._outlines; } - + set { this._outlines = value; @@ -251,6 +251,108 @@ public static Opml LoadFromFile(string path) } } + public static Opml LoadFromXml(XmlDocument doc) + { + var _out = new Opml(); + try + { + // Parse head + XmlNode head = doc.GetElementsByTagName("head")[0]; + XmlNode title = head.SelectSingleNode("./title"); + XmlNode dateCreated = head.SelectSingleNode("./dateCreated"); + XmlNode dateModified = head.SelectSingleNode("./dateModified"); + XmlNode ownerName = head.SelectSingleNode("./ownerName"); + XmlNode ownerEmail = head.SelectSingleNode("./ownerEmail"); + XmlNode ownerId = head.SelectSingleNode("./ownerId"); + XmlNode docs = head.SelectSingleNode("./docs"); + XmlNode expansionState = head.SelectSingleNode("./expansionState"); + XmlNode vertScrollState = head.SelectSingleNode("./vertScrollState"); + XmlNode windowTop = head.SelectSingleNode("./windowTop"); + XmlNode windowLeft = head.SelectSingleNode("./windowLeft"); + XmlNode windowBottom = head.SelectSingleNode("./windowBottom"); + XmlNode windowRight = head.SelectSingleNode("./windowRight"); + + if (title != null) + { + _out.Title = title.InnerText; + } + + if (dateCreated != null) + { + _out.DateCreated = DateTime.Parse(dateCreated.InnerText); + } + + if (dateModified != null) + { + _out.DateModified = DateTime.Parse(dateModified.InnerText); + } + + if (ownerName != null) + { + _out.OwnerName = ownerName.InnerText; + } + + if (ownerEmail != null) + { + _out.OwnerEmail = ownerEmail.InnerText; + } + + if (ownerId != null) + { + _out.OwnerId = ownerId.InnerText; + } + + if (docs != null) + { + _out.Docs = docs.InnerText; + } + + if (expansionState != null) + { + _out.ExpansionState = expansionState.InnerText; + } + + if (vertScrollState != null) + { + _out.VertScrollState = vertScrollState.InnerText; + } + + if (windowTop != null) + { + _out.WindowTop = windowTop.InnerText; + } + + if (windowLeft != null) + { + _out.WindowLeft = windowLeft.InnerText; + } + + if (windowBottom != null) + { + _out.WindowBottom = windowBottom.InnerText; + } + + if (windowLeft != null) + { + _out.WindowLeft = windowLeft.InnerText; + } + + // Parse body + XmlNode body = doc.GetElementsByTagName("body")[0]; + XmlNodeList outlineList = body.SelectNodes("./outline"); + foreach (XmlElement outline in outlineList) + { + _out.Outlines.Add(ParseXml(outline)); + } + + return _out; + } + catch + { + return new Opml(); + } + } + public void AddOutline(OpmlOutline item) { this._outlines.Add(item); @@ -365,108 +467,6 @@ public void Save(string fileName) this.opmlDoc.Save(fileName); } - public static Opml LoadFromXml(XmlDocument doc) - { - var _out = new Opml(); - try - { - // Parse head - XmlNode head = doc.GetElementsByTagName("head")[0]; - XmlNode title = head.SelectSingleNode("./title"); - XmlNode dateCreated = head.SelectSingleNode("./dateCreated"); - XmlNode dateModified = head.SelectSingleNode("./dateModified"); - XmlNode ownerName = head.SelectSingleNode("./ownerName"); - XmlNode ownerEmail = head.SelectSingleNode("./ownerEmail"); - XmlNode ownerId = head.SelectSingleNode("./ownerId"); - XmlNode docs = head.SelectSingleNode("./docs"); - XmlNode expansionState = head.SelectSingleNode("./expansionState"); - XmlNode vertScrollState = head.SelectSingleNode("./vertScrollState"); - XmlNode windowTop = head.SelectSingleNode("./windowTop"); - XmlNode windowLeft = head.SelectSingleNode("./windowLeft"); - XmlNode windowBottom = head.SelectSingleNode("./windowBottom"); - XmlNode windowRight = head.SelectSingleNode("./windowRight"); - - if (title != null) - { - _out.Title = title.InnerText; - } - - if (dateCreated != null) - { - _out.DateCreated = DateTime.Parse(dateCreated.InnerText); - } - - if (dateModified != null) - { - _out.DateModified = DateTime.Parse(dateModified.InnerText); - } - - if (ownerName != null) - { - _out.OwnerName = ownerName.InnerText; - } - - if (ownerEmail != null) - { - _out.OwnerEmail = ownerEmail.InnerText; - } - - if (ownerId != null) - { - _out.OwnerId = ownerId.InnerText; - } - - if (docs != null) - { - _out.Docs = docs.InnerText; - } - - if (expansionState != null) - { - _out.ExpansionState = expansionState.InnerText; - } - - if (vertScrollState != null) - { - _out.VertScrollState = vertScrollState.InnerText; - } - - if (windowTop != null) - { - _out.WindowTop = windowTop.InnerText; - } - - if (windowLeft != null) - { - _out.WindowLeft = windowLeft.InnerText; - } - - if (windowBottom != null) - { - _out.WindowBottom = windowBottom.InnerText; - } - - if (windowLeft != null) - { - _out.WindowLeft = windowLeft.InnerText; - } - - // Parse body - XmlNode body = doc.GetElementsByTagName("body")[0]; - XmlNodeList outlineList = body.SelectNodes("./outline"); - foreach (XmlElement outline in outlineList) - { - _out.Outlines.Add(ParseXml(outline)); - } - - return _out; - } - catch - { - return new Opml(); - } - } - internal static OpmlOutline ParseXml(XmlElement node) { var newOutline = new OpmlOutline(); diff --git a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs index 4c0ed9fb59c..a454a507c22 100644 --- a/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs +++ b/DNN Platform/Syndication/OPML/OpmlDownloadManager.cs @@ -69,7 +69,7 @@ internal Opml GetFeed(Uri uri) return opmlFeed; } - + private static string PrepareTempDir() { string tempDir = null; diff --git a/DNN Platform/Syndication/OPML/OpmlOutline.cs b/DNN Platform/Syndication/OPML/OpmlOutline.cs index 95a4a2222b9..e0103db991d 100644 --- a/DNN Platform/Syndication/OPML/OpmlOutline.cs +++ b/DNN Platform/Syndication/OPML/OpmlOutline.cs @@ -25,13 +25,90 @@ public OpmlOutline() this.Outlines = new OpmlOutlines(); } + public string Version + { + get + { + return "2.0"; + } + } + + public XmlElement ToXml + { + get + { + var opmlDoc = new XmlDocument { XmlResolver = null }; + XmlElement outlineNode = opmlDoc.CreateElement("outline"); + + if (!string.IsNullOrEmpty(this.Title)) + { + outlineNode.SetAttribute("title", this.Title); + } + + if (!string.IsNullOrEmpty(this.Description)) + { + outlineNode.SetAttribute("description", this.Description); + } + + if (!string.IsNullOrEmpty(this.Text)) + { + outlineNode.SetAttribute("text", this.Text); + } + + if (!string.IsNullOrEmpty(this.Type)) + { + outlineNode.SetAttribute("type", this.Type); + } + + if (!string.IsNullOrEmpty(this.Language)) + { + outlineNode.SetAttribute("language", this.Language); + } + + if (!string.IsNullOrEmpty(this.Category)) + { + outlineNode.SetAttribute("category", this.Category); + } + + if (this.Created > DateTime.MinValue) + { + outlineNode.SetAttribute("created", this.Created.ToString("r", null)); + } + + if (this.HtmlUrl != null) + { + outlineNode.SetAttribute("htmlUrl", this.HtmlUrl.ToString()); + } + + if (this.XmlUrl != null) + { + outlineNode.SetAttribute("xmlUrl", this.XmlUrl.ToString()); + } + + if (this.Url != null) + { + outlineNode.SetAttribute("url", this.Url.ToString()); + } + + outlineNode.SetAttribute("isComment", this.IsComment ? "true" : "false"); + outlineNode.SetAttribute("isBreakpoint", this.IsBreakpoint ? "true" : "false"); + + foreach (OpmlOutline childOutline in this.Outlines) + { + outlineNode.AppendChild(childOutline.ToXml); + } + + return outlineNode; + } + } + public string Description { get { return this._description; } - + set { this._description = value; @@ -44,7 +121,7 @@ public string Title { return this._title; } - + set { this._title = value; @@ -57,7 +134,7 @@ public string Type { return this._type; } - + set { this._type = value; @@ -70,7 +147,7 @@ public string Text { return this._text; } - + set { this._text = value; @@ -89,7 +166,7 @@ public DateTime Created { return this._created; } - + set { this._created = value; @@ -106,7 +183,7 @@ public string Category { return this._category; } - + set { this._category = value; @@ -119,94 +196,16 @@ public string Language { return this._language; } - + set { this._language = value; } } - public string Version - { - get - { - return "2.0"; - } - } - public OpmlOutlines Outlines { get; set; } - - public XmlElement ToXml - { - get - { - var opmlDoc = new XmlDocument { XmlResolver = null }; - XmlElement outlineNode = opmlDoc.CreateElement("outline"); - - if (!string.IsNullOrEmpty(this.Title)) - { - outlineNode.SetAttribute("title", this.Title); - } - - if (!string.IsNullOrEmpty(this.Description)) - { - outlineNode.SetAttribute("description", this.Description); - } - - if (!string.IsNullOrEmpty(this.Text)) - { - outlineNode.SetAttribute("text", this.Text); - } - - if (!string.IsNullOrEmpty(this.Type)) - { - outlineNode.SetAttribute("type", this.Type); - } - - if (!string.IsNullOrEmpty(this.Language)) - { - outlineNode.SetAttribute("language", this.Language); - } - - if (!string.IsNullOrEmpty(this.Category)) - { - outlineNode.SetAttribute("category", this.Category); - } - - if (this.Created > DateTime.MinValue) - { - outlineNode.SetAttribute("created", this.Created.ToString("r", null)); - } - - if (this.HtmlUrl != null) - { - outlineNode.SetAttribute("htmlUrl", this.HtmlUrl.ToString()); - } - - if (this.XmlUrl != null) - { - outlineNode.SetAttribute("xmlUrl", this.XmlUrl.ToString()); - } - - if (this.Url != null) - { - outlineNode.SetAttribute("url", this.Url.ToString()); - } - - outlineNode.SetAttribute("isComment", this.IsComment ? "true" : "false"); - outlineNode.SetAttribute("isBreakpoint", this.IsBreakpoint ? "true" : "false"); - - foreach (OpmlOutline childOutline in this.Outlines) - { - outlineNode.AppendChild(childOutline.ToXml); - } - - return outlineNode; - } - } } public class OpmlOutlines : List - { - } + {} } diff --git a/DNN Platform/Syndication/RSS/GenericRssChannel.cs b/DNN Platform/Syndication/RSS/GenericRssChannel.cs index 099ff853d9a..bc68b66948b 100644 --- a/DNN Platform/Syndication/RSS/GenericRssChannel.cs +++ b/DNN Platform/Syndication/RSS/GenericRssChannel.cs @@ -34,7 +34,7 @@ public string this[string attributeName] { return this.GetAttributeValue(attributeName); } - + set { this.Attributes[attributeName] = value; diff --git a/DNN Platform/Syndication/RSS/GenericRssElement.cs b/DNN Platform/Syndication/RSS/GenericRssElement.cs index b47e0e05b28..b2e78b0ba18 100644 --- a/DNN Platform/Syndication/RSS/GenericRssElement.cs +++ b/DNN Platform/Syndication/RSS/GenericRssElement.cs @@ -24,7 +24,7 @@ public string this[string attributeName] { return this.GetAttributeValue(attributeName); } - + set { this.Attributes[attributeName] = value; diff --git a/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs index 25f7fc934d9..72e3f3e99ea 100644 --- a/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/GenericRssHttpHandlerBase.cs @@ -8,6 +8,5 @@ namespace DotNetNuke.Services.Syndication /// Late-bound RSS HTTP Handler to publish RSS channel. ///
    public class GenericRssHttpHandlerBase : RssHttpHandlerBase - { - } + {} } diff --git a/DNN Platform/Syndication/RSS/RssDataSource.cs b/DNN Platform/Syndication/RSS/RssDataSource.cs index e715b253a1d..c912016e9da 100644 --- a/DNN Platform/Syndication/RSS/RssDataSource.cs +++ b/DNN Platform/Syndication/RSS/RssDataSource.cs @@ -68,7 +68,7 @@ public class RssDataSourceView : DataSourceView { private readonly RssDataSource _owner; - internal RssDataSourceView(RssDataSource owner, string viewName) + internal RssDataSourceView(RssDataSource owner, string viewName) : base(owner, viewName) { this._owner = owner; diff --git a/DNN Platform/Syndication/RSS/RssDownloadManager.cs b/DNN Platform/Syndication/RSS/RssDownloadManager.cs index cbaa59e6c6f..e78ea7b71fd 100644 --- a/DNN Platform/Syndication/RSS/RssDownloadManager.cs +++ b/DNN Platform/Syndication/RSS/RssDownloadManager.cs @@ -58,6 +58,42 @@ private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) return defaultTtlMinutes; } + private static string PrepareTempDir() + { + string tempDir = null; + + try + { + string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + RSS_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(string url) + { + try + { + var uri = new Uri(url); + return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); + } + catch + { + return "rss"; + } + } + private RssChannelDom DownloadChannelDom(string url) { // look for disk cache first @@ -218,41 +254,5 @@ private RssChannelDom GetChannelDom(string url) return dom; } - - private static string PrepareTempDir() - { - string tempDir = null; - - try - { - string d = HttpContext.Current.Server.MapPath(Settings.CacheRoot + RSS_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(string url) - { - try - { - var uri = new Uri(url); - return string.Format("{0}_{1:x8}", uri.Host.Replace('.', '_'), uri.AbsolutePath.GetHashCode()); - } - catch - { - return "rss"; - } - } } } diff --git a/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs b/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs index c823c473070..28edc85616d 100644 --- a/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs +++ b/DNN Platform/Syndication/RSS/RssElementCustomTypeDescriptor.cs @@ -17,8 +17,8 @@ internal class RssElementCustomTypeDescriptor : ICustomTypeDescriptor public RssElementCustomTypeDescriptor(Dictionary attributes) { this._attributes = attributes; - } - + } + AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; @@ -77,8 +77,8 @@ PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return (pd is RssElementCustomPropertyDescriptor) ? this : null; - } - + } + private PropertyDescriptorCollection GetPropertyDescriptors() { var propertyDescriptors = new PropertyDescriptor[this._attributes.Count]; @@ -90,11 +90,11 @@ private PropertyDescriptorCollection GetPropertyDescriptors() } return new PropertyDescriptorCollection(propertyDescriptors); - } - + } + private class RssElementCustomPropertyDescriptor : PropertyDescriptor { - public RssElementCustomPropertyDescriptor(string propertyName) + public RssElementCustomPropertyDescriptor(string propertyName) : base(propertyName, null) { } @@ -157,6 +157,6 @@ public override object GetValue(object o) return string.Empty; } - } + } } } diff --git a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs index 4921676a41e..5f2e585f1b7 100644 --- a/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs +++ b/DNN Platform/Syndication/RSS/RssHttpHandlerBase.cs @@ -24,9 +24,9 @@ public abstract class RssHttpHandlerBase 0 && result[0].ContainsKey("ModulePermissionId")) - { - return int.Parse(result[0]["ModulePermissionId"].ToString()); - } - + if (result.Count > 0 && result[0].ContainsKey("ModulePermissionId")) + { + return int.Parse(result[0]["ModulePermissionId"].ToString()); + } + return -1; } 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 be6f21acf2f..0048ce1558c 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/RoleController.cs @@ -37,7 +37,7 @@ public static int CreateRoleIfNotPresent(string roleName, int portalId = 0) /// /// Get RoleId for role "Registered Users". - /// + ///
    /// public static int GetRegisteredUsersRoleId(int portalId = 0) { @@ -46,30 +46,13 @@ public static int GetRegisteredUsersRoleId(int portalId = 0) /// /// Get RoleId for role "Administrators". - /// + ///
    /// 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 @@ -106,5 +89,22 @@ public static void AssignRoleToUser(int roleId, int userId) DatabaseHelper.ExecuteQuery(script.ToString()); } + + 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); + } } } 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 924e6b22651..48745fcd4ca 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/SchedulerController.cs @@ -30,10 +30,10 @@ public static void DisableAllSchedulers(bool clearCache = true) public static void DisableAppStartDelay(bool clearCache = true) { DatabaseHelper.ExecuteStoredProcedure("UpdateHostSetting", "SchedulerdelayAtAppStart", "0", false, 1); - if (clearCache) - { - WebApiTestHelper.ClearHostCache(); - } + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static void DisableScheduler(string schedulerName, bool clearCache = false) @@ -41,10 +41,10 @@ public static void DisableScheduler(string schedulerName, bool clearCache = fals var query = string.Format( "UPDATE {{objectQualifier}}Schedule SET Enabled=0 WHERE FriendlyName = '{0}';", schedulerName); DatabaseHelper.ExecuteNonQuery(query); - if (clearCache) - { - WebApiTestHelper.ClearHostCache(); - } + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static void EnableScheduler(string schedulerName, bool clearCache = false) @@ -52,10 +52,10 @@ public static void EnableScheduler(string schedulerName, bool clearCache = false var query = string.Format( "UPDATE {{objectQualifier}}Schedule SET Enabled=1 WHERE FriendlyName = '{0}';", schedulerName); DatabaseHelper.ExecuteNonQuery(query); - if (clearCache) - { - WebApiTestHelper.ClearHostCache(); - } + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); + } } public static SchedulingMode GetSchedulingMode() @@ -74,10 +74,10 @@ public static void SetSchedulingMode(SchedulingMode mode, bool clearCache = true if (current != mode) { DatabaseHelper.ExecuteStoredProcedure("UpdateHostSetting", "SchedulerMode", mode.ToString("D"), false, 1); - if (clearCache) - { - WebApiTestHelper.ClearHostCache(); // must clear the site Cache afterwards - } + if (clearCache) + { + WebApiTestHelper.ClearHostCache(); // must clear the site Cache afterwards + } } } @@ -120,12 +120,12 @@ public static bool RunScheduler(string schedulerName, int maxWaitSeconds = 0) try { var schedulInfo = GetSchedulerByName(schedulerName); - if (schedulInfo == null || schedulInfo.Count == 0) - { - return false; - } - - // HOST modules have only single instance, so don't worry about receiving multiple rows + if (schedulInfo == null || schedulInfo.Count == 0) + { + return false; + } + + // HOST modules have only single instance, so don't worry about receiving multiple rows var results = ModuleController.GetModulesByFriendlyName(DnnDataHelper.PortalId, "Scheduler"); var moduleId = results.SelectMany(x => x.Where(y => y.Key == "ModuleID").Select(y => (int)y.Value)).FirstOrDefault(); @@ -139,11 +139,11 @@ public static bool RunScheduler(string schedulerName, int maxWaitSeconds = 0) } var resp = TriggerScheduler(schedulInfo, moduleId); - + // only OK is a successful POST in this case; all other codes are failures if (resp.StatusCode != HttpStatusCode.OK) { - Console.WriteLine( + Console.WriteLine( @"Error running scheduler {0}. Status: {1} - {2}", schedulerName, resp.StatusCode, resp.StatusDescription); return false; @@ -153,21 +153,21 @@ public static bool RunScheduler(string schedulerName, int maxWaitSeconds = 0) SetSchedulingMode(SchedulingMode.Disabled); disabled = true; - if (maxWaitSeconds <= 0) - { - return true; - } - - // wait for task to finish + if (maxWaitSeconds <= 0) + { + return true; + } + + // wait for task to finish var latestRunInfo = WaitForTaskToFinish(lastRunInfo, maxWaitSeconds); return latestRunInfo.Succeeded; } finally { - if (!disabled) - { - SetSchedulingMode(SchedulingMode.Disabled); - } + if (!disabled) + { + SetSchedulingMode(SchedulingMode.Disabled); + } } } @@ -198,7 +198,7 @@ private static HttpWebResponse TriggerScheduler(IDictionary sche { "__EVENTTARGET", fieldsPrefix + "$cmdRun" }, // button action; if missing, no click action is performed { "__EVENTARGUMENT", string.Empty }, { "__ASYNCPOST", string.Empty }, - + // all other inputs/fields are left as is }; @@ -289,15 +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 c795c1472a0..009d873fddc 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/TabController.cs @@ -12,7 +12,7 @@ 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( @@ -40,7 +40,7 @@ public static int GetTabIdByPathName(string tabPath) public static int GetModuleIdInsidePage(int pageId) { return DatabaseHelper.ExecuteScalar( - string.Format( + string.Format( @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND PaneName='contentPane' AND ContainerSrc IS NULL AND ISNULL(PortalID,0)={1};", @@ -49,7 +49,7 @@ SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules /// /// Returns all the tab related columns from vw_tabinfo. - /// + ///
    /// public static dynamic GetTabInfo(int tabId) { @@ -64,7 +64,7 @@ public static dynamic GetTabInfo(int tabId) /// List of all the modules on a page. public static List GetAllModuleIdInsidePage(int pageId) { - var squery = string.Format( + var squery = string.Format( @" SELECT ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND ISNULL(PortalID,0)={1};", @@ -77,7 +77,7 @@ SELECT ModuleID FROM {{objectQualifier}}vw_TabModules item.TryGetValue("ModuleID", out moduleId); listOfModules.Add(Convert.ToInt32(moduleId)); } - + return listOfModules; } @@ -89,7 +89,7 @@ SELECT ModuleID FROM {{objectQualifier}}vw_TabModules public static int GetModuleIdInsidePageAnyPane(int pageId) { return DatabaseHelper.ExecuteScalar( - string.Format( + string.Format( @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules WHERE TabId = '{0}' AND ContainerSrc IS NULL AND ISNULL(PortalID,0)={1};", @@ -98,7 +98,7 @@ SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules public static int GetModuleIdInsidePage(int tabId, string moduleFriendlyName) { - var query1 = string.Format( + var query1 = string.Format( @" SELECT TOP(1) ModuleID FROM {{objectQualifier}}vw_TabModules tm INNER JOIN {{objectQualifier}}DesktopModules dm ON dm.DesktopModuleId = tm.DesktopModuleId @@ -136,7 +136,7 @@ public static string GetTabPath(string tabPath) public static int GetTabModuleId(int tabId, int moduledId) { return DatabaseHelper.ExecuteScalar( - string.Format( + string.Format( @" SELECT TOP(1) TabModuleID FROM {{objectQualifier}}TabModules WHERE TabID = {0} AND ModuleID = {1};", tabId, moduledId)); @@ -144,7 +144,7 @@ SELECT TOP(1) TabModuleID FROM {{objectQualifier}}TabModules /// /// Returns all the tab urls. - /// + ///
    /// public static IList GetTabUrls(int tabId) { @@ -166,7 +166,7 @@ public static void SaveTabSetting(int tabId, string settingName, string settingV ///
    public static void AddTabSetting(int tabId, string settingName, string settingValue) { - DatabaseHelper.ExecuteStoredProcedure( + DatabaseHelper.ExecuteStoredProcedure( "UpdateTabSetting", tabId, settingName, 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 73f972aa41e..da594bbcbd8 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Controllers/UserController.cs @@ -16,8 +16,7 @@ public static class UserController { 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]'"; @@ -25,7 +24,8 @@ public static class UserController private const string UserIdMarker = @"'$[user_id]'"; private const string CreateFriendsMarker = @"'$[CreateFriends]'"; private const string CreateFollowersMarker = @"'$[CreateFollowers]'"; - + private static readonly string UserToCopy = AppConfigHelper.HostUserName; + /// /// Creates a new user with Registered User Role and with the same password as the host user. /// @@ -34,7 +34,7 @@ public static class UserController /// PortalID to create the user under. /// Id of the created user. /// Username created is firstname.lastname. - public static int CreateRegisteredUser( + public static int CreateRegisteredUser( string firstName = IntegrationConstants.RuFirstName, string lastName = IntegrationConstants.RuLastName, int portalId = 0) { @@ -62,7 +62,7 @@ public static int CreateSuperUser(string firstName, string lastName, int portalI /// PortalID to create the user under. /// Id of the created user. /// Username created is firstname.lastname. - public static int CreateAdministratorUser( + public static int CreateAdministratorUser( string firstName = IntegrationConstants.AdminFirstName, string lastName = IntegrationConstants.AdminLastName, int portalId = 0) { @@ -106,12 +106,12 @@ private static int CreateUser(CreateUserParams parms) parms.LastName = parms.LastName.Replace("'", "''"); var username = parms.FirstName + "." + parms.LastName; var uid = GetUserId(username); - if (uid > 0) - { - return uid; - } - - // create role if not present + if (uid > 0) + { + return uid; + } + + // create role if not present RoleController.CreateRoleIfNotPresent(parms.Role); var fileContent = SqlScripts.SingleUserCreation; @@ -137,17 +137,17 @@ private static int CreateUser(CreateUserParams parms) public class CreateUserParams { public string FirstName { get; set; } - + public string LastName { get; set; } - + public int PortalId { get; set; } - + public bool SuperUser { get; set; } - + public string Role { get; set; } - + public bool AutoCreateFriends { get; set; } - + public bool AutoCreateFollowersAndFollowings { 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 01813db46c1..97ab56736d5 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/FileParameter.cs @@ -5,7 +5,7 @@ namespace DNN.Integration.Test.Framework { public class FileParameter - { + { public FileParameter(byte[] file) : this(file, null) { @@ -16,17 +16,17 @@ public FileParameter(byte[] file, string filename) { } - public FileParameter(byte[] file, string filename, string contenttype) - { - this.File = file; - this.FileName = filename; - this.ContentType = contenttype; - } + public FileParameter(byte[] file, string filename, string contenttype) + { + this.File = file; + this.FileName = filename; + this.ContentType = contenttype; + } - public byte[] File { get; set; } + public byte[] File { get; set; } - public string FileName { get; set; } + public string FileName { get; set; } - public string ContentType { 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 2c4168364c2..e00ae62e00b 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/AppConfigHelper.cs @@ -29,6 +29,15 @@ public static class AppConfigHelper public static string SiteUrl => _siteUrl ?? (_siteUrl = GetAppSetting("siteUrl") ?? DefaultWebsiteName); + public static string HostUserName => + _hostUserName ?? (_hostUserName = GetAppSetting("hostUserName") ?? DefaultHostName); + + public static string HostPassword => + _hostPassword ?? (_hostPassword = GetAppSetting("hostPassword") ?? DefaultHostPwd); + + public static string LoginCookie => + _loginCookieString ?? (_loginCookieString = GetAppSetting("loginCookie") ?? DefaultLoginCookie); + public static string GetAppSetting(string key) { return ConfigurationManager.AppSettings[key]; @@ -45,14 +54,5 @@ public static int GetAppSettingAsInt(string key, int defaultValue) int value; return int.TryParse(GetAppSetting(key), out value) ? value : defaultValue; } - - public static string HostUserName => - _hostUserName ?? (_hostUserName = GetAppSetting("hostUserName") ?? DefaultHostName); - - public static string HostPassword => - _hostPassword ?? (_hostPassword = GetAppSetting("hostPassword") ?? DefaultHostPwd); - - public static string LoginCookie => - _loginCookieString ?? (_loginCookieString = GetAppSetting("loginCookie") ?? DefaultLoginCookie); } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs index 47db24e083a..e1721cf0982 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/ContentItemHelper.cs @@ -31,7 +31,7 @@ public static string[] GetTags(int contentItemId) /// the ContentItemId of the create content item. public static int AddContentItem(int tabId) { - var query = string.Format( + var query = string.Format( @"INSERT {{objectQualifier}}ContentItems(Content, ContentTypeID, TabID, ModuleID) VALUES ('test', (SELECT TOP 1 ContentTypeID FROM {{objectQualifier}}ContentTypes),{0}, -1); SELECT SCOPE_IDENTITY()", tabId); @@ -45,7 +45,7 @@ public static int AddContentItem(int tabId) /// The id of the content item to remove. public static void RemoveContentItem(int contentItemId) { - var query = string.Format( + var query = string.Format( @"DELETE FROM {{objectQualifier}}ContentItems WHERE ContentItemId = '{0}'", contentItemId); 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 4e3ef150bb3..cd9cc7936c7 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DatabaseHelper.cs @@ -43,11 +43,6 @@ 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)) @@ -84,13 +79,13 @@ public static IList> ExecuteQuery(string queryString { values.Add(reader.GetName(i), reader.GetValue(i)); } - + results.Add(values); } } } } - + return results; } @@ -116,17 +111,17 @@ public static IList ExecuteDynamicQuery(string queryString) for (var i = 0; i < reader.FieldCount; i++) { values.Add(reader.GetName(i), reader.GetValue(i)); - + // values[reader.GetName(i)] = reader.GetValue(i); // values.Add(reader.GetName(i), reader.GetValue(i)); } - + results.Add(values); } } } } - + return results; } @@ -147,7 +142,7 @@ public static int ExecuteNonQuery(string queryString) /// /// Executes a specific STORED PROCEDURE. /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed. - /// + ///
    /// public static IList> ExecuteStoredProcedure(string procedureName, params object[] sqlParameters) { @@ -162,18 +157,18 @@ public static IList> ExecuteStoredProcedure(string p { values.Add(reader.GetName(i), reader.GetValue(i)); } - + results.Add(values); } } - + return results; } /// /// Executes a specific STORED PROCEDURE. /// The SP passed must not have the ObjectQualifier in its name; otherwise duplicate qualifier will be prefixed. - /// + ///
    /// public static IEnumerable ExecuteStoredProcedure(string procedureName, params object[] sqlParameters) { @@ -184,7 +179,7 @@ public static IEnumerable ExecuteStoredProcedure(string procedureN /// /// Retrieves the total count of records of a table or view in the database. /// - /// DO NOT perfix the table/view name with a qualifier. + /// DO NOT perfix the table/view name with a qualifier. /// public static int GetRecordsCount(string tableOrViewName, string whereCondition = null) { @@ -202,11 +197,11 @@ public static int GetRecordsCount(string tableOrViewName, string whereCondition /// Retrieves the maximum ID of a column of a table or view in the database. ///
    /// DO NOT perfix the table/view name with a qualifier. - /// If no record exists in the table, -1 is returned. + /// If no record exists in the table, -1 is returned. /// public static int GetLastRecordId(string tableOrViewName, string columnName, string whereCondition = null) { - var query = string.Format( + var query = string.Format( "SELECT COALESCE(MAX([{0}]), -1) FROM [{1}{2}]", columnName, QualifierPrefix, tableOrViewName); @@ -234,12 +229,17 @@ public static IDictionary GetRecordById(string tableOrViewName, { values.Add(reader.GetName(i), reader.GetValue(i)); } - + break; // get the first record only } } - + return values; } + + private static string ReplaceQueryQualifier(string input) + { + return input.Replace(QualifierPrefix, AppConfigHelper.ObjectQualifier); + } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs index df520f9b41a..4c1441552b9 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/DnnDataHelper.cs @@ -15,17 +15,17 @@ public static int PortalId if (!_portalId.HasValue) { var alias = AppConfigHelper.SiteUrl.Replace("http://", string.Empty).Replace("https://", string.Empty); - if (alias.EndsWith("/")) - { - alias = alias.Substring(0, alias.Length - 1); - } - + if (alias.EndsWith("/")) + { + alias = alias.Substring(0, alias.Length - 1); + } + var query = string.Format( "SELECT TOP(1) PortalID FROM {{objectQualifier}}PortalAlias WHERE HTTPAlias='{0}'", alias); var id = DatabaseHelper.ExecuteScalar(query); _portalId = id; } - + return _portalId.Value; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs index 3d9969c0a47..a9df6b79f7e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/FileHelper.cs @@ -11,11 +11,11 @@ public static class FileHelper { public static string GetAbsoluteDir(string relativePathIn) { - if (!relativePathIn.StartsWith("\\")) - { - relativePathIn = "\\" + relativePathIn; - } - + if (!relativePathIn.StartsWith("\\")) + { + relativePathIn = "\\" + relativePathIn; + } + var rootDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var pathOut = rootDirectory + relativePathIn; diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs index b84c6309e3e..2c0cbfad61b 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/HostSettingsHelper.cs @@ -27,11 +27,11 @@ public static bool AddSettingIfMissing(string settingName, string settingValue, bool recycleAppIfAdded = false) { var currentValue = GetHostSettingValue(settingName); - if (!string.IsNullOrEmpty(currentValue)) - { - return false; - } - + if (!string.IsNullOrEmpty(currentValue)) + { + return false; + } + var query = string.Format( @"INSERT INTO {{objectQualifier}}HostSettings (SettingName, SettingValue, SettingIsSecure, CreatedOnDate) " + @"VALUES(N'{0}', N'{1}', '0', {{ts: '{2:yyyy-MM-dd HH:mm.ss.fff}'}})", diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs index 96ae1ba1059..7b9c7927388 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/MockComponentHelper.cs @@ -20,8 +20,8 @@ public static Mock CreateDataCacheProvider() return CreateNew(); } - public static Mock CreateNew() - where T : class + public static Mock CreateNew() + where T : class { if (ComponentFactory.Container == null) { diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs index e29c16c3e5b..dda57ceb69e 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalAliasHelper.cs @@ -28,7 +28,7 @@ public static IEnumerable GetAllPortalAliaes() public static void AddPortalAlias(PortalAliasInfo portal) { - DatabaseHelper.ExecuteStoredProcedure( + DatabaseHelper.ExecuteStoredProcedure( "AddPortalAlias", portal.PortalID, portal.HTTPAlias, diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs index 69c305fd22e..53de88c332b 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalInfoHelper.cs @@ -18,7 +18,7 @@ public static PortalInfo GetPortalInfo(int portalId) public static void UpdatePortalInfo(PortalInfo portal) { - DatabaseHelper.ExecuteStoredProcedure( + DatabaseHelper.ExecuteStoredProcedure( "UpdatePortalInfo", portal.PortalID, portal.PortalGroupID, diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs index a3af620095a..5fae0345b88 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/PortalSettingsHelper.cs @@ -14,7 +14,7 @@ public static class PortalSettingsHelper /// The string value of the setting. public static string GetPortalSetting(string settingName, int portalId = 0) { - var query = string.Format( + var query = string.Format( @"SELECT SettingValue FROM {{objectQualifier}}PortalSettings WHERE SettingName = '{0}' @@ -32,7 +32,7 @@ public static string GetPortalSetting(string settingName, int portalId = 0) /// This flag specifies whether the value is encrypted or not, defaults to false. public static void SetPortalSetting(string settingName, string settingValue, int portalId = 0, bool isSecure = false) { - var query = string.Format( + var query = string.Format( @"MERGE INTO {{objectQualifier}}PortalSettings s USING (SELECT {2} PortalId, '{0}' SettingName, '{1}' SettingValue, {3} Sec) AS v ON s.SettingName = v.SettingName 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 670ea9b8371..741cd4a2489 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Helpers/WebApiTestHelper.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.Integration.Test.Framework.Helpers { using System; @@ -15,11 +14,10 @@ namespace DNN.Integration.Test.Framework.Helpers public static class WebApiTestHelper { - private static IWebApiConnector _anonymousConnector; private static readonly Dictionary CachedConnections = new Dictionary(); private static readonly Random Rnd = new Random(); - private static readonly string HostGuid = HostSettingsHelper.GetHostSettingValue("GUID"); + private static IWebApiConnector _anonymousConnector; /// /// Returns a coonector to access the default site annonymously. @@ -49,12 +47,6 @@ 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)}"; @@ -81,7 +73,7 @@ public static IWebApiConnector PrepareNewUser(out int userId, out string usernam /// /// Register a user by using the Registration form. - /// + /// /// public static HttpWebResponse Register(string userName, string password, string displayName, string email, string url = null, bool encriptFieldsNames = true) @@ -113,38 +105,13 @@ public static string GenerateSha256Hash(this string str) } /// 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; - return "$" + transformedId + "$" + transformedId + "_" + sufix; - } - - private static string CodifyString(string originalString) - { - return GenerateHash(HostGuid.Substring(0, 7) + originalString + DateTime.Now.Day); - } - - private static string GenerateHash(string str) - { - try - { - return CryptoConfig.AllowOnlyFipsAlgorithms - ? str.GenerateSha256Hash() - : str.GenerateMd5(); - } - catch (Exception) - { - return str.GenerateMd5(); - } - } - /// /// 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. @@ -202,37 +169,6 @@ 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. /// @@ -278,7 +214,7 @@ public static int GetPortalFromUrl(string url) public static IWebApiConnector ClearHostCache() { var connector = LoginUser(AppConfigHelper.HostUserName); - + // connector.PostJson("API/internalservices/controlbar/ClearHostCache", null); connector.PostJson("API/PersonaBar/Server/ClearCache", null); return connector; @@ -327,5 +263,67 @@ public static Dictionary GetTabModuleHeaders(string moduleFriend { "ModuleID", moduleId.ToString("D") }, }; } + + internal static void ClearCachedConnections() + { + _anonymousConnector = null; + CachedConnections.Clear(); + } + + private static string CodifyInputName(string originalId, string sufix, bool encriptName) + { + var transformedId = encriptName ? CodifyString(originalId) : originalId; + return "$" + transformedId + "$" + transformedId + "_" + sufix; + } + + private static string CodifyString(string originalString) + { + return GenerateHash(HostGuid.Substring(0, 7) + originalString + DateTime.Now.Day); + } + + private static string GenerateHash(string str) + { + try + { + return CryptoConfig.AllowOnlyFipsAlgorithms + ? str.GenerateSha256Hash() + : str.GenerateMd5(); + } + catch (Exception) + { + return str.GenerateMd5(); + } + } + + 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(); + } + } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs index 35f127df5d5..654bf8bbf06 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IWebApiConnector.cs @@ -12,34 +12,34 @@ namespace DNN.Integration.Test.Framework public interface IWebApiConnector { int UserId { get; } - + string UserName { get; } - + bool IsLoggedIn { get; } - + CookieContainer SessionCookies { get; } - + DateTime LoggedInAtTime { get; } - - TimeSpan Timeout { get; set; } - + Uri Domain { get; } - + + TimeSpan Timeout { get; set; } + string UserAgentValue { get; set; } bool AvoidCaching { get; set; } void Logout(); - + bool Login(string password); HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1); - + HttpResponseMessage ActivityStreamUploadUserFile(IDictionary headers, string fileName); bool UploadCmsFile(string fileName, string portalFolder); - HttpResponseMessage PostJson( + HttpResponseMessage PostJson( string relativeUrl, object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false); @@ -52,7 +52,7 @@ HttpWebResponse MultipartFormDataPost( HttpResponseMessage GetContent( string relativeUrl, object parameters, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true); - HttpResponseMessage GetContent( + HttpResponseMessage GetContent( string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true); } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs index afb9b84ee85..1c14c03c8c8 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/IntegrationTestBase.cs @@ -14,33 +14,33 @@ namespace DNN.Integration.Test.Framework public abstract class IntegrationTestBase { - // public static string DatabaseName { get; } + // public static string DatabaseName { get; } static IntegrationTestBase() { ServicePointManager.Expect100Continue = false; - + // setup of the whole system: take a snapshot and keep using it for all tests Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); ConnectionString = AppConfigHelper.ConnectionString; - + // DatabaseName = GetDbNameFromConnectionString(ConnectionString); // SchedulerController.DisableAllSchedulers(false); // SchedulerController.DisableAppStartDelay(false); - } - - public static string ConnectionString { get; } + } + + 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); - } + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + Console.WriteLine(text); + } } - + [TestFixtureSetUp] public virtual void TestFixtureSetUp() { 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 18eebb13c0e..03ea061101c 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/Scripts/SqlScripts.cs @@ -601,6 +601,13 @@ 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 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 + ELSE + SELECT 0 + ;"; + public static string UserGetPreferredTimeZone = @" DECLARE @UserId INT DECLARE @PortalID INT @@ -615,12 +622,5 @@ FROM [dbo].[{objectQualifier}ProfilePropertyDefinition] 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 - ELSE - SELECT 0 - ;"; } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs index f4b014e6b25..682da175a3f 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiConnector.cs @@ -28,45 +28,48 @@ 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) - { - return new WebApiConnector(siteUrl) - { - UserName = (userName ?? string.Empty).Replace("'", string.Empty), - }; - } 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; - - public string UserAgentValue - { - get { return this._userAgentValue ?? (this._userAgentValue = ConfigurationManager.AppSettings["HttpUserAgent"] ?? DefaultUserAgent); } - set { this._userAgentValue = value; } - } private const string ActivityStreamUploadFilePath = "API/DNNCorp/ActivityStream/FileUpload/UploadFile"; - private static readonly Regex HtmlFormInuts = new Regex( + private static readonly Dictionary CachedPages = new Dictionary(); + + private static readonly Regex HtmlFormInuts = new Regex( @"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); + private static readonly Encoding Encoding = Encoding.UTF8; + + private string _userAgentValue; private int _userId; - public bool AvoidCaching { get; set; } + private CookieContainer _sessionCookiesContainer; + private Cookie _cookieVerificationToken; + private string _inputFieldVerificationToken; + private string _currentTabId; + + private WebApiConnector(string siteUrl) + { + this.Timeout = TimeSpan.FromMinutes(1); + this.Domain = new Uri(siteUrl); + this.IsLoggedIn = false; + this.ResetUserId(); + this._sessionCookiesContainer = new CookieContainer(); + this._cookieVerificationToken = new Cookie(RqVerifTokenName, string.Empty, "/", this.Domain.Host); + this.AvoidCaching = false; + } /// /// Gets the userID will be available only if the user is logged in. @@ -85,37 +88,6 @@ public int UserId } } - public string UserName { get; private set; } - - public bool IsLoggedIn { get; private set; } - - 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; - - private WebApiConnector(string siteUrl) - { - this.Timeout = TimeSpan.FromMinutes(1); - this.Domain = new Uri(siteUrl); - this.IsLoggedIn = false; - this.ResetUserId(); - this._sessionCookiesContainer = new CookieContainer(); - this._cookieVerificationToken = new Cookie(RqVerifTokenName, string.Empty, "/", this.Domain.Host); - this.AvoidCaching = false; - } - - public TimeSpan Timeout { get; set; } - public Uri Domain { get; } public CookieContainer SessionCookies @@ -127,8 +99,33 @@ public CookieContainer SessionCookies } } + public string UserAgentValue + { + get { return this._userAgentValue ?? (this._userAgentValue = ConfigurationManager.AppSettings["HttpUserAgent"] ?? DefaultUserAgent); } + set { this._userAgentValue = value; } + } + + public bool AvoidCaching { get; set; } + + public string UserName { get; private set; } + + public bool IsLoggedIn { get; private set; } + + // ============================================================================== + // Adapted from http://www.briangrinstead.com/blog/multipart-form-post-in-c# + + public TimeSpan Timeout { get; set; } + public DateTime LoggedInAtTime { get; private set; } + public static WebApiConnector GetWebConnector(string siteUrl, string userName) + { + return new WebApiConnector(siteUrl) + { + UserName = (userName ?? string.Empty).Replace("'", string.Empty), + }; + } + public void Dispose() { this.Logout(); @@ -167,36 +164,25 @@ public void Logout() { this._inputFieldVerificationToken = cachedPage.VerificationToken; } - else - { - this._inputFieldVerificationToken = null; - } + else + { + this._inputFieldVerificationToken = null; + } } } } - private void EnsureLoggedIn() + public bool Login(string password) { - if (!this.IsLoggedIn) + if (this.IsLoggedIn) { - Console.WriteLine(@"User not logged in yet"); - throw new WebApiException( - new HttpRequestException("User not logged in yet."), - new HttpResponseMessage(HttpStatusCode.Unauthorized)); + return true; } - } - public bool Login(string password) - { - if (this.IsLoggedIn) - { - return true; - } - - // This method uses multi-part parameters in the post body - // the response is similar to this: - // code => HTTP/1.1 302 Found - // body => Object moved

    Object moved to here.

    + // This method uses multi-part parameters in the post body + // the response is similar to this: + // code => HTTP/1.1 302 Found + // body => Object moved

    Object moved to here.

    const string fieldsPrefix = "dnn$ctr$Login$Login_DNN"; var postData = new Dictionary { @@ -227,7 +213,7 @@ public bool Login(string password) return this.IsLoggedIn; } - + public HttpResponseMessage UploadUserFile(string fileName, bool waitHttpResponse = true, int userId = -1) { this.EnsureLoggedIn(); @@ -249,107 +235,22 @@ public HttpResponseMessage ActivityStreamUploadUserFile(IDictionary= 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) - { - var cookie = AppConfigHelper.LoginCookie; - var loginCookie = httpResponse.Cookies[cookie]; - if (loginCookie != null) - { - this.IsLoggedIn = true; - this.ExtractVerificationCookie(httpResponse.Headers["Set-Cookie"] ?? string.Empty); - using (var rs = httpResponse.GetResponseStream()) - { - if (rs != null && httpResponse.StatusCode == HttpStatusCode.OK) - { - using (var sr = new StreamReader(rs, Encoding.UTF8)) - { - var data = sr.ReadToEnd(); - var token = GetVerificationToken(data); - if (!string.IsNullOrEmpty(token)) - { - this._inputFieldVerificationToken = token; - } - } - } - } - } - } - - private void ExtractVerificationCookie(string cookiesString) - { - var parts1 = cookiesString.Split(','); - foreach (var part1 in parts1) - { - if (part1.Contains(RqVerifTokenName)) - { - var parts2 = part1.Split(';'); - foreach (var part2 in parts2) - { - if (part2.Contains(RqVerifTokenName)) - { - this._cookieVerificationToken.Value = part2.Split('=')[1]; - } - else if (part2.Contains("path")) - { - this._cookieVerificationToken.Path = part2.Split('=')[1]; - } - else if (part2.Contains("HttpOnly")) - { - this._cookieVerificationToken.HttpOnly = true; - } - } - - break; - } - } - } - public bool UploadCmsFile(string fileName, string portalFolder) { this.EnsureLoggedIn(); var result = this.UploadFile(fileName, portalFolder); return result.IsSuccessStatusCode; } - - public HttpResponseMessage PostJson( + + public HttpResponseMessage PostJson( string relativeUrl, object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - if (!ignoreLoggedIn) - { - this.EnsureLoggedIn(); - } - + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + using (var client = this.CreateHttpClient("/", true)) { var rqHeaders = client.DefaultRequestHeaders; @@ -380,15 +281,15 @@ public HttpResponseMessage PostJson( } } - public HttpResponseMessage PutJson( + public HttpResponseMessage PutJson( string relativeUrl, object content, IDictionary contentHeaders = null, bool waitHttpResponse = true, bool ignoreLoggedIn = false) { - if (!ignoreLoggedIn) - { - this.EnsureLoggedIn(); - } - + if (!ignoreLoggedIn) + { + this.EnsureLoggedIn(); + } + using (var client = this.CreateHttpClient("/", true)) { var rqHeaders = client.DefaultRequestHeaders; @@ -409,13 +310,406 @@ public HttpResponseMessage PutJson( 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); + } + } + + public HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, + List excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) + { + if (checkUserLoggedIn) + { + this.EnsureLoggedIn(); + } + + var clientHandler = new HttpClientHandler + { + CookieContainer = this._sessionCookiesContainer, + }; + + var postParameters = new Dictionary(); + string[] inputFields; + using (var client = new HttpClient(clientHandler) + { + BaseAddress = this.Domain, + Timeout = this.Timeout, + }) + { + inputFields = this.GetPageInputFields(client, relativeUrl); + } + + var firstField = formFields.First().Key; + if (!inputFields.Any(f => f.Contains(firstField))) + { + // the form doesn't have the proper input fields + Console.WriteLine( + @"Either User '{0}' has no rights to post to this page {1} or " + + @"this page does not contain correct form ", this.UserName, relativeUrl); + + // return null; + } + + foreach (var field in inputFields) + { + XElement xe = null; + try + { + // fixes the error in HTML file input fields; e.g.: + // + // but should work with XHTML file input fields; e.g.: + // + var text = field.Contains(" multiple") && !field.Contains(" multiple=") + ? field.Replace(" multiple", string.Empty) + : field; + + xe = XElement.Parse(text); + } + catch (XmlException ex) + { + Console.WriteLine(@"XmlException: cannot parse input fields: {0}. Ex: {1}", field, ex.Message); + } + + var attrs = xe == null + ? new XAttribute[0] + : xe.Attributes().ToArray(); + + var inputType = attrs.FirstOrDefault(a => a.Name == "type"); + var inputName = attrs.FirstOrDefault(a => a.Name == "name"); + var inputValue = attrs.FirstOrDefault(a => a.Name == "value"); + + if (inputType != null && inputName != null) + { + switch (inputType.Value) + { + case "hidden": + { + if (!postParameters.ContainsKey(inputName.Value)) + { + var value = inputValue == null ? string.Empty : inputValue.Value; + if (formFields.ContainsKey(inputName.Value)) + { + value = formFields[inputName.Value].ToString(); + } + + postParameters.Add(inputName.Value, value); + } + } + + break; + case "text": + case "checkbox": + case "radio": + if (formFields.ContainsKey(inputName.Value) && + !postParameters.ContainsKey(inputName.Value)) + { + postParameters.Add(inputName.Value, formFields[inputName.Value]); + } + + break; + + // other types as "submit", etc. are ignored/discarded + } + } + } + + foreach (var field in formFields) + { + if (!postParameters.ContainsKey(field.Key)) + { + postParameters.Add(field.Key, field.Value); + } + } + + if (excludedInputPrefixes != null) + { + var keys = postParameters.Keys.ToArray(); + + var filteredKeys = from prefix in excludedInputPrefixes + from key in keys + where key.StartsWith(prefix) + select key; + + foreach (var key in filteredKeys) + { + postParameters.Remove(key); + } + } + + if (postParameters.Count > 0) + { + var url = CombineUrlPath(this.Domain, relativeUrl); + return this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, null, followRedirect); + } + + return null; + } + + 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); + } + + 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); + } + + public HttpResponseMessage GetContent( + string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) + { + using (var client = this.CreateHttpClient("/", autoRedirect)) + { + 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); + } + } + + 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 static byte[] GetMultipartFormData(IEnumerable> postParameters, string boundary) + { + Stream formDataStream = new MemoryStream(); + var needsClrf = false; + + foreach (var param in postParameters) + { + // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. + // Skip it on the first parameter, add it to subsequent parameters. + if (needsClrf) + { + formDataStream.Write(Encoding.GetBytes("\r\n"), 0, Encoding.GetByteCount("\r\n")); + } + + needsClrf = true; + + var value = param.Value as FileParameter; + if (value != null) + { + var fileToUpload = value; + + // Add just the first part of this param, since we will write the file data directly to the Stream + var header = string.Format( + "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", + boundary, + param.Key, + fileToUpload.FileName ?? param.Key, + fileToUpload.ContentType ?? "application/octet-stream"); + + formDataStream.Write(Encoding.GetBytes(header), 0, Encoding.GetByteCount(header)); + + // Write the file data directly to the Stream, rather than serializing it to a string. + formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); + } + else + { + var postData = string.Format( + "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", + boundary, + param.Key, + param.Value); + formDataStream.Write(Encoding.GetBytes(postData), 0, Encoding.GetByteCount(postData)); + } + } + + // Add the end of the request. Start with a newline + var footer = "\r\n--" + boundary + "--\r\n"; + formDataStream.Write(Encoding.GetBytes(footer), 0, Encoding.GetByteCount(footer)); + + // Dump the Stream into a byte[] + formDataStream.Position = 0; + var formData = new byte[formDataStream.Length]; + var len = formDataStream.Read(formData, 0, formData.Length); + if (len != formDataStream.Length) + { + Console.WriteLine( + @"ERROR: not all form data was read from the stream. " + + @"Requested to read {0} bytes, but was read {1} bytes", formDataStream.Length, len); + } + + formDataStream.Close(); + return formData; + } + + private static string CombineUrlPath(Uri domain, string path) + { + if (path.StartsWith("http")) + { + return path; + } + + var url = domain.AbsoluteUri; + if (!url.EndsWith("/")) + { + url += "/"; + } + + if (string.IsNullOrEmpty(path)) + { + path = string.Empty; + } + + if (path.StartsWith("/")) + { + return url + path.Substring(1); + } + + return new Uri(url + path).AbsoluteUri; + } + + 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; + + try + { + body = result.Content.ReadAsStringAsync().Result; + return result.EnsureSuccessStatusCode(); + } + catch (HttpRequestException ex) + { + Console.WriteLine(@"{0} failed for [{1}] {2}\n{3}", source, url, ex.Message, body); + throw new WebApiException(ex, result, body); + } + catch (Exception ex) + { + Console.WriteLine(@"{0} failed for [{1}] {2}", source, url, ex.Message); + throw; + } + } + + private void ResetUserId() + { + this._userId = -1; + } + + 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)); + } + } + + private void VerifyLogInCookie(HttpWebResponse httpResponse) + { + var cookie = AppConfigHelper.LoginCookie; + var loginCookie = httpResponse.Cookies[cookie]; + if (loginCookie != null) + { + this.IsLoggedIn = true; + this.ExtractVerificationCookie(httpResponse.Headers["Set-Cookie"] ?? string.Empty); + using (var rs = httpResponse.GetResponseStream()) + { + if (rs != null && httpResponse.StatusCode == HttpStatusCode.OK) + { + using (var sr = new StreamReader(rs, Encoding.UTF8)) + { + var data = sr.ReadToEnd(); + var token = GetVerificationToken(data); + if (!string.IsNullOrEmpty(token)) + { + this._inputFieldVerificationToken = token; + } + } + } + } + } + } + + private void ExtractVerificationCookie(string cookiesString) + { + var parts1 = cookiesString.Split(','); + foreach (var part1 in parts1) + { + if (part1.Contains(RqVerifTokenName)) + { + var parts2 = part1.Split(';'); + foreach (var part2 in parts2) + { + if (part2.Contains(RqVerifTokenName)) + { + this._cookieVerificationToken.Value = part2.Split('=')[1]; + } + else if (part2.Contains("path")) + { + this._cookieVerificationToken.Path = part2.Split('=')[1]; + } + else if (part2.Contains("HttpOnly")) + { + this._cookieVerificationToken.HttpOnly = true; + } + } - var requestUriString = CombineUrlPath(this.Domain, relativeUrl); - var result = client.PutAsJsonAsync(requestUriString, content).Result; - return !waitHttpResponse - ? result - : EnsureSuccessResponse(result, "PutJson", requestUriString); + break; + } } } @@ -524,142 +818,6 @@ private HttpResponseMessage ActivityStreamUploadFile( ? result : EnsureSuccessResponse(result, "ActivityStreamUploadFile", ActivityStreamUploadFilePath); } - } - - public HttpWebResponse PostUserForm(string relativeUrl, IDictionary formFields, - List excludedInputPrefixes, bool checkUserLoggedIn = true, bool followRedirect = false) - { - if (checkUserLoggedIn) - { - this.EnsureLoggedIn(); - } - - var clientHandler = new HttpClientHandler - { - CookieContainer = this._sessionCookiesContainer, - }; - - var postParameters = new Dictionary(); - string[] inputFields; - using (var client = new HttpClient(clientHandler) - { - BaseAddress = this.Domain, - Timeout = this.Timeout, - }) - { - inputFields = this.GetPageInputFields(client, relativeUrl); - } - - var firstField = formFields.First().Key; - if (!inputFields.Any(f => f.Contains(firstField))) - { - // the form doesn't have the proper input fields - Console.WriteLine( - @"Either User '{0}' has no rights to post to this page {1} or " + - @"this page does not contain correct form ", this.UserName, relativeUrl); - - // return null; - } - - foreach (var field in inputFields) - { - XElement xe = null; - try - { - // fixes the error in HTML file input fields; e.g.: - // - // but should work with XHTML file input fields; e.g.: - // - var text = field.Contains(" multiple") && !field.Contains(" multiple=") - ? field.Replace(" multiple", string.Empty) - : field; - - xe = XElement.Parse(text); - } - catch (XmlException ex) - { - Console.WriteLine(@"XmlException: cannot parse input fields: {0}. Ex: {1}", field, ex.Message); - } - - var attrs = xe == null - ? new XAttribute[0] - : xe.Attributes().ToArray(); - - var inputType = attrs.FirstOrDefault(a => a.Name == "type"); - var inputName = attrs.FirstOrDefault(a => a.Name == "name"); - var inputValue = attrs.FirstOrDefault(a => a.Name == "value"); - - if (inputType != null && inputName != null) - { - switch (inputType.Value) - { - case "hidden": - { - if (!postParameters.ContainsKey(inputName.Value)) - { - var value = inputValue == null ? string.Empty : inputValue.Value; - if (formFields.ContainsKey(inputName.Value)) - { - value = formFields[inputName.Value].ToString(); - } - - postParameters.Add(inputName.Value, value); - } - } - - break; - case "text": - case "checkbox": - case "radio": - if (formFields.ContainsKey(inputName.Value) && - !postParameters.ContainsKey(inputName.Value)) - { - postParameters.Add(inputName.Value, formFields[inputName.Value]); - } - - break; - - // other types as "submit", etc. are ignored/discarded - } - } - } - - foreach (var field in formFields) - { - if (!postParameters.ContainsKey(field.Key)) - { - postParameters.Add(field.Key, field.Value); - } - } - - if (excludedInputPrefixes != null) - { - var keys = postParameters.Keys.ToArray(); - - var filteredKeys = from prefix in excludedInputPrefixes - from key in keys - where key.StartsWith(prefix) - select key; - - foreach (var key in filteredKeys) - { - postParameters.Remove(key); - } - } - - if (postParameters.Count > 0) - { - var url = CombineUrlPath(this.Domain, relativeUrl); - return this.MultipartFormDataPost(url, this.UserAgentValue, postParameters, null, followRedirect); - } - - return null; - } - - 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 HttpClient CreateHttpClient(string path, bool autoRedirect) @@ -703,7 +861,7 @@ private string[] GetPageInputFields(HttpClient client, string path) var url = CombineUrlPath(this.Domain, path); if (!this.IsLoggedIn || this.AvoidCaching || (!CachedPages.TryGetValue(url, out cachedPage) || - cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5))) + cachedPage.FetchDateTime < DateTime.Now.AddMinutes(-19.5))) { try { @@ -741,132 +899,6 @@ private string[] GetPageInputFields(HttpClient client, string path) } return cachedPage != null ? cachedPage.InputFields : new string[0]; - } - - 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); - } - - public HttpResponseMessage GetContent( - string relativeUrl, Dictionary contentHeaders = null, bool waitHttpResponse = true, bool autoRedirect = true) - { - using (var client = this.CreateHttpClient("/", autoRedirect)) - { - 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); - } - } - - private static byte[] GetMultipartFormData(IEnumerable> postParameters, string boundary) - { - Stream formDataStream = new MemoryStream(); - var needsClrf = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsClrf) - { - formDataStream.Write(Encoding.GetBytes("\r\n"), 0, Encoding.GetByteCount("\r\n")); - } - - needsClrf = true; - - var value = param.Value as FileParameter; - if (value != null) - { - var fileToUpload = value; - - // Add just the first part of this param, since we will write the file data directly to the Stream - var header = string.Format( - "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", - boundary, - param.Key, - fileToUpload.FileName ?? param.Key, - fileToUpload.ContentType ?? "application/octet-stream"); - - formDataStream.Write(Encoding.GetBytes(header), 0, Encoding.GetByteCount(header)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length); - } - else - { - var postData = string.Format( - "--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.GetBytes(postData), 0, Encoding.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - var footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.GetBytes(footer), 0, Encoding.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - var formData = new byte[formDataStream.Length]; - var len = formDataStream.Read(formData, 0, formData.Length); - if (len != formDataStream.Length) - { - Console.WriteLine( - @"ERROR: not all form data was read from the stream. " + - @"Requested to read {0} bytes, but was read {1} bytes", formDataStream.Length, len); - } - - formDataStream.Close(); - return formData; - } - - private static string CombineUrlPath(Uri domain, string path) - { - if (path.StartsWith("http")) - { - return path; - } - - var url = domain.AbsoluteUri; - if (!url.EndsWith("/")) - { - url += "/"; - } - - if (string.IsNullOrEmpty(path)) - { - path = string.Empty; - } - - if (path.StartsWith("/")) - { - return url + path.Substring(1); - } - - return new Uri(url + path).AbsoluteUri; } private HttpWebResponse MultipartFormDataPost( @@ -921,35 +953,5 @@ private HttpWebResponse PostForm(string postUrl, string userAgent, string conten 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; - - try - { - body = result.Content.ReadAsStringAsync().Result; - return result.EnsureSuccessStatusCode(); - } - catch (HttpRequestException ex) - { - Console.WriteLine(@"{0} failed for [{1}] {2}\n{3}", source, url, ex.Message, body); - throw new WebApiException(ex, result, body); - } - catch (Exception ex) - { - Console.WriteLine(@"{0} failed for [{1}] {2}", source, url, ex.Message); - throw; - } - } } } diff --git a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs index 881b6926954..71ba8b468eb 100644 --- a/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs +++ b/DNN Platform/Tests/DNN.Integration.Test.Framework/WebApiException.cs @@ -14,8 +14,8 @@ namespace DNN.Integration.Test.Framework /// Represents a non successful response while executing a WebApi call. ///
    public class WebApiException : Exception - { - /// + { + /// /// Initializes a new instance of the class, with the specified inner exception and response. /// message that caused the exception. /// diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs index a731448dfd2..11534f75655 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityProviderTest.cs @@ -16,10 +16,10 @@ namespace DotNetNuke.Tests.AspNetClientCapabilityProvider [TestFixture] public class AspNetClientCapabilityProviderTest - { - 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; - + { + 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() { @@ -42,8 +42,8 @@ public void Setup() [TearDown] public void TearDown() { - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void AspNetClientCapabilityProvider_GetClientCapabilityById_ThrowsException_For_Empty_ClientCapabilityId() @@ -60,6 +60,6 @@ public void AspNetClientCapabilityProvider_GetClientCapabilityById_ThrowsExcepti // Act string nullClientCapabilityId = null; var clientCapabilitiesByEmptyId = this._clientCapabilityProvider.GetClientCapabilityById(nullClientCapabilityId); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs index a39bc7abf0e..b4c57078e83 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.AspNetCCP/AspNetClientCapabilityTest.cs @@ -16,11 +16,9 @@ namespace DotNetNuke.Tests.AspNetClientCapabilityProviderTest [TestFixture] public class AspNetClientCapabilityTest - { + { 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)"; @@ -32,10 +30,12 @@ public class AspNetClientCapabilityTest public const string samsungGalaxyTablet = "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; SAMSUNG GT-P1000 Tablet Build/MASTER) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; public const string winTabletPC = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705; Tablet PC 2.0)"; - + public const string htcDesireVer1Sub22UserAgent = "Mozilla/5.0 (Linux; U; Android 2.2; sv-se; Desire_A8181 Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"; - public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; - + public const string blackBerry9105V1 = "BlackBerry9105/5.0.0.696 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/133"; + + private Providers.AspNetClientCapabilityProvider.AspNetClientCapabilityProvider _clientCapabilityProvider; + [SetUp] public void Setup() { @@ -51,8 +51,8 @@ public void Setup() [TearDown] public void TearDown() { - } - + } + [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_BlackBerry9105V1() { @@ -65,7 +65,7 @@ public void AspNetClientCapability_IsMobile_Returns_True_For_BlackBerry9105V1() // Assert Assert.IsTrue(bIsMobile); } - + [Test] public void AspNetClientCapability_IsMobile_Returns_True_For_IPhone() { @@ -161,8 +161,8 @@ public void AspNetClientCapability_IsMobile_Returns_True_For_HTCDesireVer1Sub22( // Assert Assert.IsTrue(bIsMobile); - } - + } + [Test] public void AspNetClientCapability_IsMobile_Returns_False_For_InternetExplorer8() { @@ -213,8 +213,8 @@ public void AspNetClientCapability_IsMobile_Returns_False_For_FireFox() // Assert Assert.IsFalse(bIsMobile); - } - + } + [Test] public void AspNetClientCapability_IsTablet_Returns_False_For_IPhone() { @@ -239,8 +239,8 @@ public void AspNetClientCapability_IsTablet_Returns_True_For_PCTablet() // Assert Assert.IsTrue(bIsTablet); - } - + } + [Test] public void AspNetClientCapability_SupportsFlash_Returns_True_For_HTCDesireVer1Sub22() { @@ -252,8 +252,8 @@ public void AspNetClientCapability_SupportsFlash_Returns_True_For_HTCDesireVer1S // Assert Assert.IsFalse(bSupportsFlash); - } - + } + [Test] public void AspNetClientCapability_SupportsFlash_Returns_False_For_WindowsPhone7() { @@ -265,6 +265,6 @@ public void AspNetClientCapability_SupportsFlash_Returns_False_For_WindowsPhone7 // Assert Assert.IsFalse(bIsTablet); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs index 62f40288699..1aef2da49e7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/AttachmentControllerTests.cs @@ -42,8 +42,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void Test_Add_File_To_Content_Item_Without_Metadata() { @@ -104,50 +104,6 @@ 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() @@ -282,7 +238,7 @@ public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() // Should be a no-op since no real data changed dataService.Verify(ds => ds.AddMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Once()); dataService.Verify(ds => ds.DeleteMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Never()); - + // Really update contentItem.ContentTitle = "SNAFU"; @@ -290,6 +246,50 @@ public void Set_MetaData_To_Same_Value_Doesnt_Update_Database_Entry() dataService.Verify(ds => ds.AddMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Exactly(2)); dataService.Verify(ds => ds.DeleteMetaData(contentItem, FileController.TitleKey, It.IsAny()), Times.Once()); - } + } + + 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; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs index ddad1ef1213..eba6e40c52e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentControllerTests.cs @@ -32,8 +32,8 @@ public class ContentControllerTests private Mock _mockCache; private Mock _mockDataProvider; - private Mock _mockSearchHelper; - + private Mock _mockSearchHelper; + [SetUp] public void SetUp() { @@ -51,8 +51,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void ContentController_AddContentItem_Throws_On_Null_ContentItem() { @@ -122,8 +122,8 @@ public void ContentController_AddContentItem_Sets_ContentItemId_Property_On_Vali // Assert Assert.AreEqual(Constants.CONTENT_AddContentItemId, content.ContentItemId); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ContentController_DeleteContentItem_Throws_On_Null_ContentItem() @@ -131,7 +131,7 @@ public void ContentController_DeleteContentItem_Throws_On_Null_ContentItem() // Arrange Mock mockDataService = new Mock(); ContentController controller = new ContentController(mockDataService.Object); - + // Act, Arrange controller.DeleteContentItem(null); } @@ -165,8 +165,8 @@ public void ContentController_DeleteContentItem_Calls_DataService_On_Valid_Conte // Assert mockDataService.Verify(ds => ds.DeleteContentItem(content.ContentItemId)); - } - + } + [Test] public void ContentController_GetContentItem_Throws_On_Negative_ContentItemId() { @@ -223,8 +223,8 @@ public void ContentController_GetContentItem_Returns_ContentItem_On_Valid_Conten Assert.AreEqual(Constants.CONTENT_ValidContentItemId, content.ContentItemId); Assert.AreEqual(ContentTestHelper.GetContent(Constants.CONTENT_ValidContentItemId), content.Content); Assert.AreEqual(ContentTestHelper.GetContentKey(Constants.CONTENT_ValidContentItemId), content.ContentKey); - } - + } + [Test] public void ContentController_GetContentItemsByTerm_Throws_On_Null_Term() { @@ -271,7 +271,7 @@ public void ContentController_GetContentItemsByTerm_Returns_List_Of_ContentItems { // Arrange Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)).Returns(MockHelper.CreateValidContentItemsReader( + mockDataService.Setup(ds => ds.GetContentItemsByTerm(Constants.TERM_ValidName)).Returns(MockHelper.CreateValidContentItemsReader( Constants.CONTENT_TaggedItemCount, Constants.CONTENT_IndexedFalse, Null.NullInteger, @@ -283,8 +283,8 @@ public void ContentController_GetContentItemsByTerm_Returns_List_Of_ContentItems // Assert Assert.AreEqual(Constants.CONTENT_TaggedItemCount, contentItems.Count()); - } - + } + [Test] public void ContentController_GetContentItemsByContentType_Returns_Results() { @@ -310,8 +310,8 @@ public void ContentController_GetContentItemsByContentType_Invalid_Id_Returns_No var items = controller.GetContentItemsByContentType(-1).ToArray(); Assert.IsEmpty(items); - } - + } + [Test] public void GetContentItemsByModuleId_With_Negative_ModuleId_Returns_ContentItems() { @@ -326,8 +326,8 @@ public void GetContentItemsByModuleId_With_Negative_ModuleId_Returns_ContentItem Assert.AreEqual(negative.Length, 10); Assert.AreEqual(positive.Length, 1); - } - + } + [Test] public void ContentController_GetUnIndexedContentItems_Calls_DataService() { @@ -364,7 +364,7 @@ public void ContentController_GetUnIndexedContentItems_Returns_List_Of_UnIndexed { // Arrange Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateValidContentItemsReader( + mockDataService.Setup(ds => ds.GetUnIndexedContentItems()).Returns(MockHelper.CreateValidContentItemsReader( Constants.CONTENT_IndexedFalseItemCount, Constants.CONTENT_IndexedFalse, Null.NullInteger, @@ -381,8 +381,8 @@ public void ContentController_GetUnIndexedContentItems_Returns_List_Of_UnIndexed { Assert.IsFalse(content.Indexed); } - } - + } + [Test] public void ContentController_UpdateContentItem_Throws_On_Null_ContentItem() { @@ -426,8 +426,8 @@ public void ContentController_UpdateContentItem_Calls_DataService_On_Valid_Conte // Assert mockDataService.Verify(ds => ds.UpdateContentItem(content, It.IsAny())); - } - + } + [Test] public void ContentController_AddMetaData_Throws_On_Null_ContentItem() { @@ -481,8 +481,8 @@ public void ContentController_AddMetaData_Calls_DataService_On_Valid_Arguments() // Assert mockDataService.Verify(ds => ds.AddMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); - } - + } + [Test] public void ContentController_DeleteMetaData_Throws_On_Null_ContentItem() { @@ -536,8 +536,8 @@ public void ContentController_DeleteMetaData_Calls_DataService_On_Valid_Argument // Assert mockDataService.Verify(ds => ds.DeleteMetaData(content, Constants.CONTENT_ValidMetaDataName, Constants.CONTENT_ValidMetaDataValue)); - } - + } + [Test] public void ContentController_GetMetaData_Throws_On_Negative_ContentItemId() { @@ -593,8 +593,8 @@ public void ContentController_GetMetaData_Returns_NameValueCollection_Of_MetaDat // Assert Assert.AreEqual(Constants.CONTENT_MetaDataCount, metaData.Count); - } - + } + [Test] public void ContentController_Title_Is_Saved_On_Add() { @@ -685,6 +685,6 @@ public void ContentController_Title_Is_Saved_On_Update() // Assert mockDataService.Verify(ds => ds.AddMetaData(content, AttachmentController.TitleKey, Constants.CONTENT_ValidTitle)); mockDataService.Verify(ds => ds.AddMetaData(content, AttachmentController.TitleKey, Constants.CONTENT_ValidTitle2)); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs index 9c6795d39e9..44f600e3935 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ContentTypeControllerTests.cs @@ -23,8 +23,8 @@ namespace DotNetNuke.Tests.Content [TestFixture] public class ContentTypeControllerTests { - private Mock mockCache; - + private Mock mockCache; + [SetUp] public void SetUp() { @@ -37,8 +37,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void ContentTypeController_AddContentType_Throws_On_Null_ContentType() { @@ -98,8 +98,8 @@ public void ContentTypeController_AddContentType_Sets_ValidId_On_Valid_ContentTy // Assert Assert.AreEqual(Constants.CONTENTTYPE_AddContentTypeId, contentType.ContentTypeId); - } - + } + [Test] public void ContentTypeController_DeleteContentType_Throws_On_Null_ContentType() { @@ -140,8 +140,8 @@ public void ContentTypeController_DeleteContentType_Calls_DataService_On_Valid_C // Assert mockDataService.Verify(ds => ds.DeleteContentType(contentType)); - } - + } + [Test] public void ContentTypeController_GetContentTypes_Calls_DataService() { @@ -186,8 +186,8 @@ public void ContentTypeController_GetContentTypes_Returns_List_Of_ContentTypes() // Assert Assert.AreEqual(Constants.CONTENTTYPE_ValidContentTypeCount, contentTypes.Count()); - } - + } + [Test] public void ContentTypeController_UpdateContentType_Throws_On_Null_ContentType() { @@ -228,6 +228,6 @@ public void ContentTypeController_UpdateContentType_Calls_DataService_On_Valid_C // Assert mockDataService.Verify(ds => ds.UpdateContentType(contentType)); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs index 41c34cfeecb..05b1c8fea36 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/Mocks/MockHelper.cs @@ -48,7 +48,7 @@ internal static IQueryable TestVocabularies return vocabularies.AsQueryable(); } } - + internal static IDataReader CreateEmptyContentItemReader() { return CreateContentItemTable().CreateDataReader(); @@ -59,163 +59,6 @@ internal static IDataReader CreateEmptyContentTypeReader() return CreateContentTypeTable().CreateDataReader(); } - private static void AddBaseEntityColumns(DataTable table) - { - table.Columns.Add("CreatedByUserID", typeof(int)); - table.Columns.Add("CreatedOnDate", typeof(DateTime)); - table.Columns.Add("LastModifiedByUserID", typeof(int)); - table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - } - - private static void AddContentItemToTable(DataTable table, int id, string content, string contentKey, bool indexed, int userId, string term) - { - table.Rows.Add(new object[] { id, content, Null.NullInteger, Null.NullInteger, Null.NullInteger, contentKey, indexed, userId, term }); - } - - private static void AddContentTypeToTable(DataTable table, int id, string contentType) - { - table.Rows.Add(new object[] { id, contentType }); - } - - private static void AddScopeTypeToTable(DataTable table, int id, string scopeType) - { - table.Rows.Add(new object[] { id, scopeType }); - } - - private static void AddTermToTable(DataTable table, int id, int contentItemId, int vocabularyId, string name, string description, int weight, int parentId) - { - table.Rows.Add(new object[] { id, contentItemId, vocabularyId, name, description, weight, parentId }); - } - - private static void AddVocabularyToTable(DataTable table, int id, int typeId, string name, string description, int scopeId, int scopeTypeId, int weight) - { - table.Rows.Add(new object[] { id, typeId, false, name, description, scopeId, scopeTypeId, weight }); - } - - private static DataTable CreateContentItemTable() - { - // Create Categories table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("ContentItemID", typeof(int)); - table.Columns.Add("Content", typeof(string)); - table.Columns.Add("ContentTypeID", typeof(int)); - table.Columns.Add("TabID", typeof(int)); - table.Columns.Add("ModuleID", typeof(int)); - table.Columns.Add("ContentKey", typeof(string)); - table.Columns.Add("Indexed", typeof(bool)); - table.Columns.Add("UserID", typeof(int)); - table.Columns.Add("Term", typeof(string)); - table.Columns.Add("StateID", typeof(int)); - AddBaseEntityColumns(table); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static DataTable CreateContentTypeTable() - { - // Create ContentTypes table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("ContentTypeID", typeof(int)); - table.Columns.Add("ContentType", typeof(string)); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static DataTable CreateScopeTypeTable() - { - // Create ScopeTypes table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("ScopeTypeID", typeof(int)); - table.Columns.Add("ScopeType", typeof(string)); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static DataTable CreateTermTable() - { - // Create Vocabulary table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("TermID", typeof(int)); - table.Columns.Add("ContentItemID", typeof(int)); - table.Columns.Add("VocabularyID", typeof(int)); - table.Columns.Add("Name", typeof(string)); - table.Columns.Add("Description", typeof(string)); - table.Columns.Add("Weight", typeof(int)); - table.Columns.Add("ParentTermID", typeof(int)); - table.Columns.Add("TermLeft", typeof(int)); - table.Columns.Add("TermRight", typeof(int)); - AddBaseEntityColumns(table); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static DataTable CreateVocabularyTable() - { - // Create Vocabulary table. - DataTable table = new DataTable(); - - // Create columns, ID and Name. - DataColumn idColumn = table.Columns.Add("VocabularyID", typeof(int)); - table.Columns.Add("VocabularyTypeID", typeof(int)); - table.Columns.Add("IsSystem", typeof(bool)); - table.Columns.Add("Name", typeof(string)); - table.Columns.Add("Description", typeof(string)); - table.Columns.Add("ScopeID", typeof(int)); - table.Columns.Add("ScopeTypeID", typeof(int)); - table.Columns.Add("Weight", typeof(int)); - AddBaseEntityColumns(table); - - // Set the ID column as the primary key column. - table.PrimaryKey = new[] { idColumn }; - - return table; - } - - private static Mock RegisterMockController(Mock mock) - where TMock : class - { - if (ComponentFactory.Container == null) - { - // Create a Container - ComponentFactory.Container = new SimpleContainer(); - } - - // Try and get mock - var getMock = ComponentFactory.GetComponent>(); - - if (getMock == null) - { - // Create the mock - getMock = mock; - - // Add both mock and mock.Object to Container - ComponentFactory.RegisterComponentInstance>(getMock); - ComponentFactory.RegisterComponentInstance(getMock.Object); - } - - return getMock; - } - internal static IDataReader CreateEmptyScopeTypeReader() { return CreateScopeTypeTable().CreateDataReader(); @@ -248,7 +91,7 @@ internal static Mock CreateMockVocabularyController() internal static IDataReader CreateValidContentItemReader() { DataTable table = CreateContentItemTable(); - AddContentItemToTable( + AddContentItemToTable( table, Constants.CONTENT_ValidContentItemId, ContentTestHelper.GetContent(Constants.CONTENT_ValidContentItemId), @@ -264,7 +107,7 @@ internal static IDataReader CreateValidContentItemReader(ContentItem contentItem { DataTable table = CreateContentItemTable(); - AddContentItemToTable( + AddContentItemToTable( table, contentItem.ContentItemId, ContentTestHelper.GetContent(contentItem.ContentItemId), @@ -387,7 +230,7 @@ internal static IDataReader CreateEmptyMetaDataReader() internal static IDataReader CreateValidTermReader() { DataTable table = CreateTermTable(); - AddTermToTable( + AddTermToTable( table, Constants.TERM_ValidTermId, Constants.TERM_ValidContent1, @@ -396,7 +239,7 @@ internal static IDataReader CreateValidTermReader() Constants.TERM_ValidName, Constants.TERM_ValidWeight, Constants.TERM_ValidParentTermId); - + return table.CreateDataReader(); } @@ -463,5 +306,162 @@ internal static Mock CreateMockFileManager() fm.Setup(f => f.GetFile(It.IsAny())).Returns((int fileId) => CreateRandomFile(fileId)); return fm; } + + private static void AddBaseEntityColumns(DataTable table) + { + table.Columns.Add("CreatedByUserID", typeof(int)); + table.Columns.Add("CreatedOnDate", typeof(DateTime)); + table.Columns.Add("LastModifiedByUserID", typeof(int)); + table.Columns.Add("LastModifiedOnDate", typeof(DateTime)); + } + + private static void AddContentItemToTable(DataTable table, int id, string content, string contentKey, bool indexed, int userId, string term) + { + table.Rows.Add(new object[] { id, content, Null.NullInteger, Null.NullInteger, Null.NullInteger, contentKey, indexed, userId, term }); + } + + private static void AddContentTypeToTable(DataTable table, int id, string contentType) + { + table.Rows.Add(new object[] { id, contentType }); + } + + private static void AddScopeTypeToTable(DataTable table, int id, string scopeType) + { + table.Rows.Add(new object[] { id, scopeType }); + } + + private static void AddTermToTable(DataTable table, int id, int contentItemId, int vocabularyId, string name, string description, int weight, int parentId) + { + table.Rows.Add(new object[] { id, contentItemId, vocabularyId, name, description, weight, parentId }); + } + + private static void AddVocabularyToTable(DataTable table, int id, int typeId, string name, string description, int scopeId, int scopeTypeId, int weight) + { + table.Rows.Add(new object[] { id, typeId, false, name, description, scopeId, scopeTypeId, weight }); + } + + private static DataTable CreateContentItemTable() + { + // Create Categories table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("ContentItemID", typeof(int)); + table.Columns.Add("Content", typeof(string)); + table.Columns.Add("ContentTypeID", typeof(int)); + table.Columns.Add("TabID", typeof(int)); + table.Columns.Add("ModuleID", typeof(int)); + table.Columns.Add("ContentKey", typeof(string)); + table.Columns.Add("Indexed", typeof(bool)); + table.Columns.Add("UserID", typeof(int)); + table.Columns.Add("Term", typeof(string)); + table.Columns.Add("StateID", typeof(int)); + AddBaseEntityColumns(table); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static DataTable CreateContentTypeTable() + { + // Create ContentTypes table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("ContentTypeID", typeof(int)); + table.Columns.Add("ContentType", typeof(string)); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static DataTable CreateScopeTypeTable() + { + // Create ScopeTypes table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("ScopeTypeID", typeof(int)); + table.Columns.Add("ScopeType", typeof(string)); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static DataTable CreateTermTable() + { + // Create Vocabulary table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("TermID", typeof(int)); + table.Columns.Add("ContentItemID", typeof(int)); + table.Columns.Add("VocabularyID", typeof(int)); + table.Columns.Add("Name", typeof(string)); + table.Columns.Add("Description", typeof(string)); + table.Columns.Add("Weight", typeof(int)); + table.Columns.Add("ParentTermID", typeof(int)); + table.Columns.Add("TermLeft", typeof(int)); + table.Columns.Add("TermRight", typeof(int)); + AddBaseEntityColumns(table); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static DataTable CreateVocabularyTable() + { + // Create Vocabulary table. + DataTable table = new DataTable(); + + // Create columns, ID and Name. + DataColumn idColumn = table.Columns.Add("VocabularyID", typeof(int)); + table.Columns.Add("VocabularyTypeID", typeof(int)); + table.Columns.Add("IsSystem", typeof(bool)); + table.Columns.Add("Name", typeof(string)); + table.Columns.Add("Description", typeof(string)); + table.Columns.Add("ScopeID", typeof(int)); + table.Columns.Add("ScopeTypeID", typeof(int)); + table.Columns.Add("Weight", typeof(int)); + AddBaseEntityColumns(table); + + // Set the ID column as the primary key column. + table.PrimaryKey = new[] { idColumn }; + + return table; + } + + private static Mock RegisterMockController(Mock mock) + where TMock : class + { + if (ComponentFactory.Container == null) + { + // Create a Container + ComponentFactory.Container = new SimpleContainer(); + } + + // Try and get mock + var getMock = ComponentFactory.GetComponent>(); + + if (getMock == null) + { + // Create the mock + getMock = mock; + + // Add both mock and mock.Object to Container + ComponentFactory.RegisterComponentInstance>(getMock); + ComponentFactory.RegisterComponentInstance(getMock.Object); + } + + return getMock; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs index f69499e287f..e7b5f87d385 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/ScopeTypeControllerTests.cs @@ -23,8 +23,8 @@ namespace DotNetNuke.Tests.Content [TestFixture] public class ScopeTypeControllerTests { - private Mock mockCache; - + private Mock mockCache; + [SetUp] public void SetUp() { @@ -37,8 +37,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void ScopeTypeController_AddScopeType_Throws_On_Null_ScopeType() { @@ -96,8 +96,8 @@ public void ScopeTypeController_AddScopeType_Sets_ValidId_On_Valid_ScopeType() // Assert Assert.AreEqual(Constants.SCOPETYPE_AddScopeTypeId, scopeType.ScopeTypeId); - } - + } + [Test] public void ScopeTypeController_DeleteScopeType_Throws_On_Null_ScopeType() { @@ -137,8 +137,8 @@ public void ScopeTypeController_DeleteScopeType_Calls_DataService_On_Valid_Conte // Assert mockDataService.Verify(ds => ds.DeleteScopeType(scopeType)); - } - + } + [Test] public void ScopeTypeController_GetScopeTypes_Calls_DataService() { @@ -183,8 +183,8 @@ public void ScopeTypeController_GetScopeTypes_Returns_List_Of_ScopeTypes() // Assert Assert.AreEqual(Constants.SCOPETYPE_ValidScopeTypeCount, scopeTypes.Count()); - } - + } + [Test] public void ScopeTypeController_UpdateScopeType_Throws_On_Null_ScopeType() { @@ -225,6 +225,6 @@ public void ScopeTypeController_UpdateScopeType_Calls_DataService_On_Valid_Conte // Assert mockDataService.Verify(ds => ds.UpdateScopeType(scopeType)); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs index ea47617e103..32a80100d0e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/TermControllerTests.cs @@ -25,14 +25,14 @@ namespace DotNetNuke.Tests.Content [TestFixture] public class TermControllerTests { - private Mock mockCache; - + private Mock mockCache; + [SetUp] public void SetUp() { Mock vocabularyController = MockHelper.CreateMockVocabularyController(); MockComponentProvider.CreateDataProvider().Setup(c => c.GetProviderPath()).Returns(string.Empty); - + // Register MockCachingProvider this.mockCache = MockComponentProvider.CreateNew(); } @@ -41,8 +41,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void TermController_AddTerm_Throws_On_Null_Term() { @@ -195,8 +195,8 @@ public void TermController_AddTerm_Clears_Term_Cache_On_Valid_Term() // Assert this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - + } + [Test] public void TermController_AddTermToContent_Throws_On_Null_Term() { @@ -238,8 +238,8 @@ public void TermController_AddTermToContent_Should_Call_DataService_If_Valid_Par // Assert mockDataService.Verify(ds => ds.AddTermToContent(term, content)); - } - + } + [Test] public void TermController_DeleteTerm_Throws_On_Null_Term() { @@ -313,8 +313,8 @@ public void TermController_DeleteTerm_Clears_Term_Cache_On_Valid_Term() // Assert this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } - + } + [Test] public void TermController_GetTerm_Throws_On_Negative_TermId() { @@ -372,8 +372,8 @@ public void TermController_GetTerm_Returns_Term_On_Valid_TermId() // Assert Assert.AreEqual(Constants.TERM_ValidTermId, term.TermId); Assert.AreEqual(Constants.TERM_ValidName, term.Name); - } - + } + [Test] public void TermController_GetTermsByContent_Throws_On_Invalid_ContentItemId() { @@ -390,7 +390,7 @@ public void TermController_GetTermsByContent_Calls_DataService() { // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( Constants.TERM_ValidCountForContent1, v => Constants.TERM_ValidVocabularyId, c => Constants.TERM_ValidContent1)); @@ -408,7 +408,7 @@ public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemI { // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( + mockDataService.Setup(ds => ds.GetTermsByContent(Constants.TERM_ValidContent1)).Returns(MockHelper.CreateValidTermsReader( Constants.TERM_ValidCountForContent1, v => Constants.TERM_ValidVocabularyId, c => Constants.TERM_ValidContent1)); @@ -426,8 +426,8 @@ public void TermController_GetTermsByContent_Returns_Terms_On_Valid_ContentItemI Assert.AreEqual(i + Constants.TERM_ValidTermId, terms[i].TermId); Assert.AreEqual(ContentTestHelper.GetTermName(i + Constants.TERM_ValidTermId), terms[i].Name); } - } - + } + [Test] public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyId() { @@ -445,7 +445,7 @@ public void TermController_GetTermsByVocabulary_Returns_Terms_On_Valid_Vocabular { // Arrange var mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader( + mockDataService.Setup(ds => ds.GetTermsByVocabulary(Constants.TERM_ValidVocabulary1)).Returns(MockHelper.CreateValidTermsReader( Constants.TERM_ValidCountForVocabulary1, v => Constants.TERM_ValidVocabulary1, c => Constants.TERM_ValidContent1)); @@ -475,8 +475,8 @@ public void TermController_GetTermsByVocabulary_Throws_On_Invalid_VocabularyName // Act, Arrange Assert.Throws(() => termController.GetTermsByVocabulary(Null.NullString)); - } - + } + [Test] public void TermController_RemoveTermsFromContent_Throws_On_Null_ContentItem() { @@ -502,8 +502,8 @@ public void TermController_RemoveTermsFromContent_Should_Call_DataService_If_Val // Assert mockDataService.Verify(ds => ds.RemoveTermsFromContent(content)); - } - + } + [Test] public void TermController_UpdateTerm_Throws_On_Null_Term() { @@ -610,6 +610,6 @@ public void TermController_UpdateTerm_Clears_Term_Cache_On_Valid_Term() // Assert this.mockCache.Verify(cache => cache.Remove(string.Format(Constants.TERM_CacheKey, Constants.VOCABULARY_ValidVocabularyId))); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs index aa595198f06..86a1ad450f9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Content/VocabularyControllerTests.cs @@ -23,8 +23,8 @@ namespace DotNetNuke.Tests.Content [TestFixture] public class VocabularyControllerTests { - private Mock mockCache; - + private Mock mockCache; + [SetUp] public void SetUp() { @@ -37,8 +37,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void VocabularyController_AddVocabulary_Throws_On_Null_Vocabulary() { @@ -142,8 +142,8 @@ public void VocabularyController_AddVocabulary_Clears_Vocabulary_Cache_On_Valid_ // Assert this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - + } + [Test] public void VocabularyController_DeleteVocabulary_Throws_On_Null_Vocabulary() { @@ -201,8 +201,8 @@ public void VocabularyController_DeleteVocabulary_Clears_Vocabulary_Cache_On_Val // Assert this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } - + } + [Test] public void VocabularyController_GetVocabularies_Calls_DataService() { @@ -231,8 +231,8 @@ public void VocabularyController_GetVocabularies_Returns_List_Of_Vocabularies() // Assert Assert.AreEqual(Constants.VOCABULARY_ValidCount, vocabularys.Count()); - } - + } + [Test] public void VocabularyController_UpdateVocabulary_Throws_On_Null_Vocabulary() { @@ -318,6 +318,6 @@ public void VocabularyController__UpdateVocabulary_Clears_Vocabulary_Cache_On_Va // Assert this.mockCache.Verify(cache => cache.Remove(Constants.VOCABULARY_CacheKey)); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs index 5336aa828fc..e8518e6dae1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/CBOTest.cs @@ -26,7 +26,7 @@ public void SetUp() ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.CreateDataCacheProvider(); } - + [Test] public void CBO_FillObject_int() { @@ -42,7 +42,7 @@ public void CBO_FillObject_int() Assert.IsNotNull(result); Assert.AreEqual(colValue, result.IntProp); } - + [Test] public void CBO_FillObject_string() { @@ -77,7 +77,7 @@ public void CBO_FillObject_datetime() } [Test] - + // DNNPRO-13404 - Object does not implement IConvertible public void CBO_FillObject_binary() { @@ -86,7 +86,7 @@ public void CBO_FillObject_binary() cboTable.Columns.Add("ByteArrayProp", typeof(byte[])); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -102,7 +102,7 @@ public void CBO_FillObject_binary_to_Array() cboTable.Columns.Add("ArrayProp", typeof(byte[])); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -118,7 +118,7 @@ public void CBO_FillObject_bit() cboTable.Columns.Add("BitProp", typeof(bool)); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -134,7 +134,7 @@ public void CBO_FillObject_decimal() cboTable.Columns.Add("DecimalProp", typeof(decimal)); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -150,7 +150,7 @@ public void CBO_FillObject_int_to_boolean_true() cboTable.Columns.Add("BitProp", typeof(int)); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -166,7 +166,7 @@ public void CBO_FillObject_int_to_boolean_false() cboTable.Columns.Add("BitProp", typeof(int)); cboTable.Rows.Add(colValue); - + var result = CBO.FillObject(cboTable.CreateDataReader()); Assert.IsInstanceOf(result); @@ -178,17 +178,17 @@ public void CBO_FillObject_int_to_boolean_false() public class IntPoco { public int IntProp { get; set; } - + public string StringProp { get; set; } - + public DateTime DateTimeProp { get; set; } - + public byte[] ByteArrayProp { get; set; } - + public Array ArrayProp { get; set; } - + public bool BitProp { get; set; } - + public decimal DecimalProp { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs index b0797887759..f5f034fd3d1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/LockStrategyTests.cs @@ -20,11 +20,11 @@ public void DoubleDisposeAllowed() strategy.Dispose(); strategy.Dispose(); - + // no exception on 2nd dispose } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public virtual void DoubleReadLockThrows() { @@ -39,10 +39,8 @@ public virtual void DoubleReadLockThrows() } } } - - internal abstract ILockStrategy GetLockStrategy(); - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public void ReadAndWriteLockOnSameThreadThrows() { @@ -58,7 +56,7 @@ public void ReadAndWriteLockOnSameThreadThrows() } } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public void WriteAndReadLockOnSameThreadThrows() { @@ -122,7 +120,7 @@ public void DoubleWriteLockOnDifferentThreadsWaits() } } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public virtual void DoubleWriteLockThrows() { @@ -138,7 +136,7 @@ public virtual void DoubleWriteLockThrows() } } - [Test] + [Test] [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action methodCall) @@ -167,14 +165,14 @@ public void ReadLockPreventsWriteLock() // assert that write thread is still waiting Assert.IsTrue(t.IsAlive); } - + // release read lock // sleep and let write thread finish up Thread.Sleep(100); Assert.IsFalse(t.IsAlive); } - + // release controller } @@ -196,7 +194,7 @@ public void OnlyOneWriteLockAllowed() // assert that write thread is still waiting Assert.IsTrue(t.IsAlive); } - + // release write lock // sleep and let write thread finish up Thread.Sleep(100); @@ -231,7 +229,9 @@ public void MultipleReadLocksAllowed() } } } - + + internal abstract ILockStrategy GetLockStrategy(); + protected virtual IEnumerable> GetObjectDisposedExceptionMethods() { var l = new List>(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs index f14d50771b4..0b387564649 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/NaiveLockingListTests.cs @@ -115,7 +115,7 @@ public void IndexOperator() Assert.AreEqual(999, list[2]); } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public void NoWritesWhileEnumerating() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs index 2f581fee789..25d34c8b821 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PageSelectorTests.cs @@ -12,14 +12,14 @@ namespace DotNetNuke.Tests.Core.Collections [TestFixture] public class PageSelectorTests - { + { private IEnumerable list; - + [SetUp] public void SetUp() { this.list = Util.CreateIntegerList(Constants.PAGE_TotalCount); - } + } [Test] [TestCase(0)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs index eb4105b6f8a..3ca2279a0b7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/PagedListTests.cs @@ -47,7 +47,7 @@ public void PagedList_Constructor_Overload_Succeeds_When_Given_Valid_Index(int t // Assert // asserted by no exception :) } - + [Test] [TestCase(0, 1)] [TestCase(5, 1)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs index 38264958a19..c90345d1ac5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterLockStrategyTests.cs @@ -21,7 +21,7 @@ public override void DoubleWriteLockThrows() { base.DoubleWriteLockThrows(); } - + internal override ILockStrategy GetLockStrategy() { return new ReaderWriterLockStrategy(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs index a80075c5986..3940b339f65 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/ReaderWriterSlimLockTests.cs @@ -21,7 +21,7 @@ public void DoubleDisposeAllowed() scl.Dispose(); scl.Dispose(); - + // no exception on 2nd dispose } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs index 2e5dad8037f..216c78d0b80 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedDictionaryTests.cs @@ -47,23 +47,23 @@ public void TryAdd() CollectionAssert.AreEqual(new Dictionary { { KEY, VALUE } }, sharedDictionary.BackingDictionary); } - [Test] - [ExpectedException(typeof(WriteLockRequiredException))] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] [TestCaseSource("GetWriteMethods")] public void WriteRequiresLock(Action> writeAction) { writeAction.Invoke(this.InitSharedDictionary("key", "value")); } - [Test] - [ExpectedException(typeof(ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] [TestCaseSource("GetReadMethods")] public void ReadRequiresLock(Action> readAction) { readAction.Invoke(this.InitSharedDictionary("key", "value")); } - [Test] + [Test] [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedReadLockDeniesRead() { @@ -75,7 +75,7 @@ public void DisposedReadLockDeniesRead() d.ContainsKey("foo"); } - [Test] + [Test] [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedWriteLockDeniesRead() { @@ -87,7 +87,7 @@ public void DisposedWriteLockDeniesRead() d.ContainsKey("foo"); } - [Test] + [Test] [ExpectedException(typeof(WriteLockRequiredException))] public void DisposedWriteLockDeniesWrite() { @@ -133,7 +133,7 @@ public void DoubleDispose() d.Dispose(); } - [Test] + [Test] [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action> methodCall) @@ -144,7 +144,7 @@ public void MethodsThrowAfterDisposed(Action> m methodCall.Invoke(d); } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public void TwoDictsShareALockWriteTest() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs index b2d1de1de16..a006b9763dc 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Collections/SharedListTests.cs @@ -45,23 +45,23 @@ public void TryAdd() CollectionAssert.AreEqual(new List { value }, sharedList.BackingList); } - [Test] - [ExpectedException(typeof(WriteLockRequiredException))] + [Test] + [ExpectedException(typeof(WriteLockRequiredException))] [TestCaseSource("GetWriteMethods")] public void WriteRequiresLock(Action> writeAction) { writeAction.Invoke(this.InitSharedList("value")); } - [Test] - [ExpectedException(typeof(ReadLockRequiredException))] + [Test] + [ExpectedException(typeof(ReadLockRequiredException))] [TestCaseSource("GetReadMethods")] public void ReadRequiresLock(Action> readAction) { readAction.Invoke(this.InitSharedList("value")); } - [Test] + [Test] [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedReadLockDeniesRead() { @@ -73,7 +73,7 @@ public void DisposedReadLockDeniesRead() d.Contains("foo"); } - [Test] + [Test] [ExpectedException(typeof(ReadLockRequiredException))] public void DisposedWriteLockDeniesRead() { @@ -85,7 +85,7 @@ public void DisposedWriteLockDeniesRead() d.Contains("foo"); } - [Test] + [Test] [ExpectedException(typeof(WriteLockRequiredException))] public void DisposedWriteLockDeniesWrite() { @@ -131,7 +131,7 @@ public void DoubleDispose() d.Dispose(); } - [Test] + [Test] [ExpectedException(typeof(ObjectDisposedException))] [TestCaseSource("GetObjectDisposedExceptionMethods")] public void MethodsThrowAfterDisposed(Action> methodCall) @@ -142,7 +142,7 @@ public void MethodsThrowAfterDisposed(Action> methodCall) methodCall.Invoke(d); } - [Test] + [Test] [ExpectedException(typeof(LockRecursionException))] public void TwoDictsShareALockWriteTest() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs index 74fa0cf825d..b8a9326f001 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Common/NavigationManagerTests.cs @@ -22,11 +22,11 @@ public class NavigationManagerTests { 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}"; private const string LanguagePattern = "&language={0}"; + private INavigationManager _navigationManager; [TestFixtureSetUp] public void Setup() @@ -61,7 +61,7 @@ PortalSettings PortalSettingsMock() return portalSettings; } } - + ITabController TabControllerMock() { var mockTabController = new Mock(); @@ -77,7 +77,7 @@ ITabController TabControllerMock() return mockTabController.Object; } - + ILocaleController LocaleControllerMock() { var mockLocaleController = new Mock(); @@ -221,11 +221,11 @@ public void NavigateUrl_ControlKey_SingleAdditionalParameter() public void NavigateUrl_ControlKey_MultipleAdditionalParameter(int count) { string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - { - parameters[index] = $"My-Parameter{index}"; - } - + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + var controlKey = "My-Control-Key"; var expected = string.Format(DefaultURLPattern, TabID) + string.Format(ControlKeyPattern, controlKey) + @@ -311,20 +311,20 @@ public void NavigateUrl_TabID_NullControlKey(int tabId) public void NavigateUrl_TabID_ControlKey_Parameter(int count, string controlKey) { string[] parameters = new string[count]; - for (int index = 0; index < count; index++) - { - parameters[index] = $"My-Parameter{index}"; - } - + for (int index = 0; index < count; index++) + { + parameters[index] = $"My-Parameter{index}"; + } + var customTabId = 51; var expected = string.Format(DefaultURLPattern, customTabId) + string.Format(ControlKeyPattern, controlKey); - if (parameters.Length > 0) - { - expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); - } - + if (parameters.Length > 0) + { + expected += parameters.Select(s => $"&{s}").Aggregate((x, y) => $"{x}{y}"); + } + var actual = this._navigationManager.NavigateURL(customTabId, controlKey, parameters); Assert.IsNotNull(actual); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs index e8d0ba1acf1..b71aa75c253 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/ComponentFactoryTests.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Tests.Core.ComponentModel /// [TestFixture] public class ComponentFactoryTests - { + { public static IContainer CreateMockContainer() { var mockContainer = new Mock(); @@ -25,7 +25,7 @@ public static IContainer CreateMockContainer() ComponentFactory.Container = container; return container; } - + [TearDown] public void TearDown() { @@ -76,6 +76,6 @@ public void DNNPRO_13443_ComponentFactory_DuplicatedInsert() // Assert var retreivedComponent = ComponentFactory.GetComponent(); Assert.AreEqual(testComp1, retreivedComponent); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs index 7374e438abc..aec54c96dad 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/Helpers/Service2Impl.cs @@ -11,11 +11,11 @@ public class Service2Impl : IService2 public Service2Impl(IService service) { this._service = service; - } - + } + public IService Service { get { return this._service; } - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs index 7e362bdfe71..a1744b1bf84 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/ComponentModel/SimpleContainerTests.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Tests.Core.ComponentModel public class SimpleContainerTests { [Test] - + // DNN-17622 http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=17622&PROJID=2 public void GetComponenetListSupportsInterfaces() { 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 73d4bdbaeab..8e4f59968bf 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Host/HostControllerTest.cs @@ -24,13 +24,13 @@ public class HostControllerTest private DataTable _hostSettingsTable; private Mock _mockCache; private Mock _mockData; - + [SetUp] public void SetUp() { this._mockCache = MockComponentProvider.CreateDataCacheProvider(); MockComponentProvider.CreateEventLogController(); - + this._hostSettingsTable = new DataTable("HostSettings"); var nameCol = this._hostSettingsTable.Columns.Add("SettingName"); @@ -48,11 +48,11 @@ public void SetUp() this._hostSettingsTable.Rows.Add("Double_8_U", "8", false); this._hostSettingsTable.Rows.Add("Bool_9_U", false, false); this._hostSettingsTable.Rows.Add("Bool_10_S", false, true); - + this._mockData = MockComponentProvider.CreateDataProvider(); this._mockData.Setup(c => c.GetHostSettings()).Returns(this._hostSettingsTable.CreateDataReader()); this._mockData.Setup(c => c.GetProviderPath()).Returns(string.Empty); - + DataCache.ClearCache(); } @@ -61,7 +61,7 @@ public void TearDown() { MockComponentProvider.ResetContainer(); } - + [Test] public void HostController_GetSettings_GetList() { @@ -100,16 +100,11 @@ public void HostController_GetSettingsDictionary_GetList() // Act var settingsDic = HostController.Instance.GetSettingsDictionary(); - + // 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() { @@ -171,7 +166,7 @@ public void HostController_Update_ExistingValue_Dont_Reset_Cache() // Assert this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); - + // Clear was not called a second time this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); } @@ -191,8 +186,8 @@ public void HostController_Update_Dictionary() // Assert this._mockData.Verify(c => c.UpdateHostSetting("String_1_S", "MyValue", false, It.IsAny()), Times.Exactly(1)); this._mockCache.Verify(c => c.Clear("Host", string.Empty), Times.Exactly(1)); - } - + } + [Test] public void HostController_Update_NewValue() { @@ -255,8 +250,8 @@ public void HostController_Update_NewValue_Dont_Reset_Cache() // Assert this._mockData.Verify(c => c.UpdateHostSetting(key, value, false, It.IsAny())); this._mockCache.Verify(c => c.Remove("DNN_HostSettings"), Times.Never); - } - + } + [Test] [TestCase("String_1_S")] [TestCase("String_2_S")] @@ -267,7 +262,7 @@ public void HostController_GetString_If_Key_Exists(string key) Assert.AreEqual(HostController.Instance.GetString(key), this.GetValue(key)); Assert.AreEqual(HostController.Instance.GetString(key, "Hello Default"), this.GetValue(key)); } - + [Test] [TestCase("BadKey1")] [TestCase("AAAAAAA")] @@ -291,8 +286,8 @@ public void HostController_GetString_InvalidKey_Returns_Default_Value(string key public void HostController_GetString_NullEmpty(string key) { HostController.Instance.GetString(key); - } - + } + [Test] [TestCase("Int_5_U")] [TestCase("Int_6_S")] @@ -326,8 +321,8 @@ public void HostController_GetInteger_InvalidKey_Returns_Default_Value(string ke public void HostController_GetInteger_NullEmpty(string key) { HostController.Instance.GetInteger(key); - } - + } + [Test] [TestCase("Bool_9_U")] [TestCase("Bool_10_S")] @@ -337,7 +332,7 @@ public void HostController_GetBoolean_If_Key_Exists(string key) Assert.AreEqual(HostController.Instance.GetBoolean(key, false).ToString(), this.GetValue(key)); Assert.AreEqual(HostController.Instance.GetBoolean(key, true).ToString(), this.GetValue(key)); } - + [Test] [TestCase("BadKey1")] [TestCase("AAAAAAA")] @@ -354,7 +349,7 @@ public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string ke Assert.AreEqual(HostController.Instance.GetBoolean(key, true), true); Assert.AreEqual(HostController.Instance.GetBoolean(key, false), false); } - + [Test] [TestCase("")] [TestCase(null)] @@ -362,8 +357,8 @@ public void HostController_GetBoolean_InvalidKey_Returns_Default_Value(string ke public void HostController_GetBoolean_NullEmpty(string key) { HostController.Instance.GetBoolean(key); - } - + } + [Test] [TestCase("Double_7_S")] [TestCase("Double_8_U")] @@ -397,6 +392,11 @@ public void HostController_GetDouble_InvalidKey_Returns_Default_Value(string key public void HostController_GetDouble_NullEmpty(string key) { HostController.Instance.GetDouble(key); - } + } + + private string GetValue(string key) + { + return this._hostSettingsTable.Rows.Find(key)["SettingValue"].ToString(); + } } } 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 18efe757c04..5808ed995b2 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,18 +85,18 @@ 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 94ff287619a..2f553cac519 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,12 +36,12 @@ 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/Helpers/SetupCachingProviderHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs index 8a54f80d94a..dd43155c5c6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Helpers/SetupCachingProviderHelper.cs @@ -23,7 +23,7 @@ public static void SetupCachingProvider(Mock mockCachingProvide return portals; } - + return key.Contains("PortalGroups") ? new List() : null; }); } 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 9851c0f78d9..5b7987e546c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/MessagingControllerTests.cs @@ -36,7 +36,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Messaging ///
    [TestFixture] public class MessagingControllerTests - { + { private Mock _mockDataService; private MessagingController _messagingController; private InternalMessagingControllerImpl _internalMessagingController; @@ -61,8 +61,8 @@ public class MessagingControllerTests private UserInfo _adminUserInfo; private UserInfo _hostUserInfo; private UserInfo _user12UserInfo; - private UserInfo _groupOwnerUserInfo; - + private UserInfo _groupOwnerUserInfo; + [SetUp] public void SetUp() { @@ -112,7 +112,7 @@ public void TearDown() ComponentFactory.Container = null; PortalController.ClearInstance(); } - + [Test] public void MessagingController_Constructor_Throws_On_Null_DataService() { @@ -120,8 +120,8 @@ public void MessagingController_Constructor_Throws_On_Null_DataService() // Act, Assert Assert.Throws(() => new MessagingController(null)); - } - + } + [Test] public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setting_Is_YES() { @@ -130,83 +130,6 @@ public void AttachmentsAllowed_Returns_True_When_MessagingAllowAttachments_Setti Assert.IsTrue(result); } - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - var dataTable = new DataTable("Languages"); - var pkId = dataTable.Columns.Add("LanguageID", typeof(int)); - dataTable.Columns.Add("CultureCode", typeof(string)); - dataTable.Columns.Add("CultureName", typeof(string)); - dataTable.Columns.Add("FallbackCulture", typeof(string)); - 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.PrimaryKey = new[] { pkId }; - dataTable.Rows.Add(1, "en-US", "English (United States)", null, -1, "2011-05-04 09:42:11.530", -1, "2011-05-04 09:42:11.530"); - - this._dataProvider.Setup(x => x.GetLanguages()).Returns(dataTable.CreateDataReader()); - } - - private void SetupUsers() - { - this._adminUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Admin, UserID = Constants.UserID_Admin, Roles = new[] { Constants.RoleName_Administrators } }; - this._hostUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Host, UserID = Constants.UserID_Host, IsSuperUser = true }; - this._user12UserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_User12, UserID = Constants.UserID_User12 }; - this._groupOwnerUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_FirstSocialGroupOwner, UserID = Constants.UserID_FirstSocialGroupOwner }; - } - - private void SetupPortalSettings() - { - var portalSettings = new PortalSettings - { - AdministratorRoleName = Constants.RoleName_Administrators, - }; - - this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); - } - - private void SetupCachingProvider() - { - this._mockCacheProvider.Setup(c => c.GetItem(It.IsAny())).Returns(key => - { - if (key.Contains("Portal-1_")) - { - var portals = new List(); - portals.Add(new PortalInfo() { PortalID = 0 }); - - return portals; - } - else if (key.Contains("PortalGroups")) - { - return new List(); - } - - return null; - }); - } - - private void SetupRoleProvider() - { - var adminRoleInfoForAdministrators = new UserRoleInfo { RoleName = Constants.RoleName_Administrators, RoleID = Constants.RoleID_Administrators, UserID = Constants.UserID_Admin }; - var adminRoleInfoforRegisteredUsers = new UserRoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers, UserID = Constants.UserID_User12 }; - var user12RoleInfoforRegisteredUsers = new UserRoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers, UserID = Constants.UserID_User12 }; - var userFirstSocialGroupOwner = new UserRoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup, UserID = Constants.UserID_FirstSocialGroupOwner, IsOwner = true }; - - this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_Admin), It.IsAny())).Returns(new List { adminRoleInfoForAdministrators, adminRoleInfoforRegisteredUsers }); - this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_User12), It.IsAny())).Returns(new List { user12RoleInfoforRegisteredUsers }); - this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_FirstSocialGroupOwner), It.IsAny())).Returns(new List { userFirstSocialGroupOwner }); - } - - private void SetupFileControllers() - { - this._folderManager.Setup(f => f.GetFolder(It.IsAny())).Returns(new FolderInfo()); - this._fileManager.Setup(f => f.GetFile(It.IsAny())).Returns(new FileInfo()); - this._folderPermissionController.Setup(f => f.CanViewFolder(It.IsAny())).Returns(true); - } - [Test] public void IncludeAttachments_Returns_True_When_MessagingIncludeAttachments_Setting_Is_YES() { @@ -221,8 +144,8 @@ public void AttachmentsAllowed_Returns_False_When_MessagingAllowAttachments_Sett this._mockInternalMessagingController.Setup(mc => mc.GetPortalSetting("MessagingAllowAttachments", Constants.CONTENT_ValidPortalId, "YES")).Returns("NO"); var result = this._mockInternalMessagingController.Object.AttachmentsAllowed(Constants.CONTENT_ValidPortalId); Assert.IsFalse(result); - } - + } + [Test] public void GetArchivedMessages_Calls_DataService_GetArchiveBoxView_With_Default_Values() { @@ -248,8 +171,8 @@ public void GetArchivedMessages_Calls_DataService_GetArchiveBoxView_With_Default this._mockInternalMessagingController.Object.GetArchivedMessages(Constants.UserID_User12, 0, 0); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void GetMessageThread_Calls_DataService_GetMessageThread() { @@ -275,8 +198,8 @@ public void GetMessageThread_Calls_Overload_With_Default_Values() this._mockInternalMessagingController.Object.GetMessageThread(0, 0, 0, 0, ref totalRecords[0]); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void GetRecentSentbox_Calls_Overload_With_Default_Values() { @@ -299,8 +222,8 @@ public void GetRecentSentbox_Calls_GetSentbox_With_Default_Values() this._mockInternalMessagingController.Object.GetRecentSentbox(Constants.UserID_User12); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void GetSentbox_Calls_DataService_GetSentBoxView_With_Default_Values() { @@ -345,8 +268,8 @@ public void GetSentbox_Calls_Overload_With_Default_Values() this._mockInternalMessagingController.Object.GetSentbox(Constants.UserID_User12, 0, 0, string.Empty, false); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void RecipientLimit_Returns_MessagingRecipientLimit_Setting() { @@ -358,8 +281,8 @@ public void RecipientLimit_Returns_MessagingRecipientLimit_Setting() var actual = this._mockInternalMessagingController.Object.RecipientLimit(Constants.CONTENT_ValidPortalId); Assert.AreEqual(expected, actual); - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_CreateMessage_Throws_On_Null_Message() @@ -542,7 +465,7 @@ public void MessagingController_CreateMessage_Calls_DataService_SaveSocialMessag this._mockMessagingController.Object.SendMessage(message, new List { role }, new List { user }, null, this._adminUserInfo); // Assert - this._mockDataService.Verify(ds => ds.SaveMessage( + this._mockDataService.Verify(ds => ds.SaveMessage( It.Is(v => v.PortalID == Constants.PORTAL_Zero && v.Subject == "subject" && v.Body == "body" && v.To == "role1,user1" @@ -661,7 +584,7 @@ public void MessagingController_CreateMessage_Trims_Comma_For_Two_Users() this._dtMessageRecipients.Clear(); var recipientId = 0; - + // _dtMessageRecipients.Rows.Add(Constants.Messaging_RecipientId_2, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage); mockDataService.Setup(md => md.GetMessageRecipientByMessageAndUser(It.IsAny(), It.IsAny())) .Callback(() => this._dtMessageRecipients.Rows.Add(recipientId++, Constants.USER_Null, Constants.Messaging_UnReadMessage, Constants.Messaging_UnArchivedMessage)) @@ -1024,8 +947,8 @@ public void MessagingController_CreateMessage_Does_Not_Mark_Message_As_Dispatche // Assert this._mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1), Times.Never()); - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void MessagingController_ReplyMessage_Throws_On_Null_Sender() @@ -1168,8 +1091,8 @@ public void MessagingController_ReplyMessage_Marks_Message_As_Dispatched_For_Sen this._mockInternalMessagingController.Object.ReplyMessage(0, "body", null, sender); this._mockInternalMessagingController.Verify(imc => imc.MarkMessageAsDispatched(It.IsAny(), Constants.Messaging_RecipientId_1)); - } - + } + [Test] public void MessagingController_SetReadMessage_Calls_DataService_UpdateSocialMessageReadStatus() { @@ -1224,8 +1147,8 @@ public void MessagingController_SetUnArchivedMessage_Calls_DataService_UpdateSoc // Assert this._mockDataService.Verify(ds => ds.UpdateMessageArchivedStatus(messageInstance.ConversationId, user.UserID, false)); - } - + } + [Test] public void GetSocialMessageRecipient_Calls_DataService_GetSocialMessageRecipientByMessageAndUser() { @@ -1238,8 +1161,8 @@ public void GetSocialMessageRecipient_Calls_DataService_GetSocialMessageRecipien this._internalMessagingController.GetMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); this._mockDataService.Verify(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void WaitTimeForNextMessage_Throws_On_Null_Sender() @@ -1307,8 +1230,8 @@ public void WaitTimeForNextMessage_Returns_The_Number_Of_Seconds_Since_Last_Mess var result = this._mockInternalMessagingController.Object.WaitTimeForNextMessage(this._user12UserInfo); Assert.AreEqual(expected, result); - } - + } + [Test] public void GetInbox_Calls_DataService_GetMessageBoxView() { @@ -1334,8 +1257,8 @@ public void GetInbox_Calls_Overload_With_Default_Values() this._mockInternalMessagingController.Object.GetInbox(Constants.UserID_User12, 0, 0, string.Empty, false); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void GetRecentInbox_Calls_GetInbox_With_Default_Values() { @@ -1358,64 +1281,64 @@ public void GetRecentInbox_Calls_Overload_With_Default_Values() this._mockInternalMessagingController.Object.GetRecentInbox(Constants.UserID_User12); this._mockInternalMessagingController.Verify(); - } - + } + [Test] public void CountArchivedMessagesByConversation_Calls_DataService_CountArchivedMessagesByConversation() { this._mockDataService.Setup(ds => ds.CountArchivedMessagesByConversation(It.IsAny())).Verifiable(); this._internalMessagingController.CountArchivedMessagesByConversation(1); this._mockDataService.Verify(); - } - + } + [Test] public void CountMessagesByConversation_Calls_DataService_CountMessagesByConversation() { this._mockDataService.Setup(ds => ds.CountMessagesByConversation(It.IsAny())).Verifiable(); this._internalMessagingController.CountMessagesByConversation(1); this._mockDataService.Verify(); - } - + } + [Test] public void CountConversations_Calls_DataService_CountTotalConversations() { this._mockDataService.Setup(ds => ds.CountTotalConversations(It.IsAny(), It.IsAny())).Verifiable(); this._internalMessagingController.CountConversations(Constants.UserID_User12, Constants.PORTAL_Zero); this._mockDataService.Verify(); - } - + } + [Test] public void CountUnreadMessages_Calls_DataService_CountNewThreads() { this._mockDataService.Setup(ds => ds.CountNewThreads(It.IsAny(), It.IsAny())).Verifiable(); this._internalMessagingController.CountUnreadMessages(Constants.UserID_User12, Constants.PORTAL_Zero); this._mockDataService.Verify(); - } - + } + [Test] public void CountSentMessages_Calls_DataService_CountSentMessages() { this._mockDataService.Setup(ds => ds.CountSentMessages(It.IsAny(), It.IsAny())).Verifiable(); this._internalMessagingController.CountSentMessages(Constants.UserID_User12, Constants.PORTAL_Zero); this._mockDataService.Verify(); - } - + } + [Test] public void CountArchivedMessages_Calls_DataService_CountArchivedMessages() { this._mockDataService.Setup(ds => ds.CountArchivedMessages(It.IsAny(), It.IsAny())).Verifiable(); this._internalMessagingController.CountArchivedMessages(Constants.UserID_User12, Constants.PORTAL_Zero); this._mockDataService.Verify(); - } - + } + [Test] public void DeleteMessageRecipient_Calls_DataService_DeleteMessageRecipientByMessageAndUser() { this._mockDataService.Setup(ds => ds.DeleteMessageRecipientByMessageAndUser(Constants.Messaging_MessageId_1, Constants.UserID_User12)).Verifiable(); this._internalMessagingController.DeleteMessageRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); this._mockDataService.Verify(); - } - + } + [Test] public void GetMessageRecipients_Calls_DataService_GetMessageRecipientsByMessage() { @@ -1427,8 +1350,8 @@ public void GetMessageRecipients_Calls_DataService_GetMessageRecipientsByMessage .Verifiable(); this._internalMessagingController.GetMessageRecipients(Constants.Messaging_MessageId_1); this._mockDataService.Verify(); - } - + } + private static Message CreateValidMessage() { var message = new Message @@ -1444,6 +1367,83 @@ private static Message CreateValidMessage() return message; } + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + var dataTable = new DataTable("Languages"); + var pkId = dataTable.Columns.Add("LanguageID", typeof(int)); + dataTable.Columns.Add("CultureCode", typeof(string)); + dataTable.Columns.Add("CultureName", typeof(string)); + dataTable.Columns.Add("FallbackCulture", typeof(string)); + 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.PrimaryKey = new[] { pkId }; + dataTable.Rows.Add(1, "en-US", "English (United States)", null, -1, "2011-05-04 09:42:11.530", -1, "2011-05-04 09:42:11.530"); + + this._dataProvider.Setup(x => x.GetLanguages()).Returns(dataTable.CreateDataReader()); + } + + private void SetupUsers() + { + this._adminUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Admin, UserID = Constants.UserID_Admin, Roles = new[] { Constants.RoleName_Administrators } }; + this._hostUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_Host, UserID = Constants.UserID_Host, IsSuperUser = true }; + this._user12UserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_User12, UserID = Constants.UserID_User12 }; + this._groupOwnerUserInfo = new UserInfo { DisplayName = Constants.UserDisplayName_FirstSocialGroupOwner, UserID = Constants.UserID_FirstSocialGroupOwner }; + } + + private void SetupPortalSettings() + { + var portalSettings = new PortalSettings + { + AdministratorRoleName = Constants.RoleName_Administrators, + }; + + this._portalController.Setup(pc => pc.GetCurrentPortalSettings()).Returns(portalSettings); + } + + private void SetupCachingProvider() + { + this._mockCacheProvider.Setup(c => c.GetItem(It.IsAny())).Returns(key => + { + if (key.Contains("Portal-1_")) + { + var portals = new List(); + portals.Add(new PortalInfo() { PortalID = 0 }); + + return portals; + } + else if (key.Contains("PortalGroups")) + { + return new List(); + } + + return null; + }); + } + + private void SetupRoleProvider() + { + var adminRoleInfoForAdministrators = new UserRoleInfo { RoleName = Constants.RoleName_Administrators, RoleID = Constants.RoleID_Administrators, UserID = Constants.UserID_Admin }; + var adminRoleInfoforRegisteredUsers = new UserRoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers, UserID = Constants.UserID_User12 }; + var user12RoleInfoforRegisteredUsers = new UserRoleInfo { RoleName = Constants.RoleName_RegisteredUsers, RoleID = Constants.RoleID_RegisteredUsers, UserID = Constants.UserID_User12 }; + var userFirstSocialGroupOwner = new UserRoleInfo { RoleName = Constants.RoleName_FirstSocialGroup, RoleID = Constants.RoleID_FirstSocialGroup, UserID = Constants.UserID_FirstSocialGroupOwner, IsOwner = true }; + + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_Admin), It.IsAny())).Returns(new List { adminRoleInfoForAdministrators, adminRoleInfoforRegisteredUsers }); + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_User12), It.IsAny())).Returns(new List { user12RoleInfoforRegisteredUsers }); + this._mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == Constants.UserID_FirstSocialGroupOwner), It.IsAny())).Returns(new List { userFirstSocialGroupOwner }); + } + + private void SetupFileControllers() + { + this._folderManager.Setup(f => f.GetFolder(It.IsAny())).Returns(new FolderInfo()); + this._fileManager.Setup(f => f.GetFile(It.IsAny())).Returns(new FileInfo()); + this._folderPermissionController.Setup(f => f.CanViewFolder(It.IsAny())).Returns(true); + } + private void SetupDataTables() { // Messages @@ -1522,7 +1522,7 @@ private void SetupDataTables() this._dtMessageThreadsView.Columns.Add("TotalThreads", typeof(int)); this._dtMessageThreadsView.Columns.Add("TotalNewThreads", typeof(int)); this._dtMessageThreadsView.Columns.Add("TotalArchivedThreads", typeof(int)); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs index 56207233b5d..36d815acd16 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/SubscriptionDataReaderMockHelper.cs @@ -24,7 +24,7 @@ internal static IDataReader CreateSubscriptionReader(IEnumerable s { AddSubscriptionToTable(datatable, subscription); } - + return datatable.CreateDataReader(); } @@ -49,7 +49,7 @@ private static DataTable CreateSubscriptionTable() private static void AddSubscriptionToTable(DataTable table, Subscription subscription) { - table.Rows.Add(new object[] + table.Rows.Add(new object[] { subscription.SubscriptionId, subscription.UserId, diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs index f81aeba8127..878f9f33fc9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/Mocks/UserPreferenceDataReaderMockHelper.cs @@ -39,7 +39,7 @@ private static DataTable CreateUserPreferenceTable() private static void AddUserPreferenceToTable(DataTable table, UserPreference userPreference) { - table.Rows.Add(new object[] + table.Rows.Add(new object[] { 1, userPreference.PortalId, 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 c463bfc183d..e7a78e589a3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/NotificationsControllerTests.cs @@ -30,7 +30,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Messaging [TestFixture] public class NotificationsControllerTests - { + { private Mock _mockDataService; private Mock _portalController; private Mock _portalGroupController; @@ -43,8 +43,8 @@ public class NotificationsControllerTests private Mock _cachingProvider; private DataTable _dtNotificationTypes; private DataTable _dtNotificationTypeActions; - private DataTable _dtNotificationActions; - + private DataTable _dtNotificationActions; + [SetUp] public void SetUp() { @@ -83,8 +83,8 @@ public void TearDown() MessagingController.ClearInstance(); PortalController.ClearInstance(); InternalMessagingController.ClearInstance(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void CreateNotificationType_Throws_On_Null_NotificationType() @@ -92,12 +92,6 @@ 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)] @@ -159,8 +153,8 @@ public void CreateNotificationType_Makes_Valid_Object() this._mockNotificationsController.Object.CreateNotificationType(actualNotificationType); Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - + } + [Test] public void DeleteNotificationType_Calls_DataService_DeleteNotificationType() { @@ -177,8 +171,8 @@ public void DeleteNotificationType_Removes_Cache_Object() this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeCache()).Verifiable(); this._mockNotificationsController.Object.DeleteNotificationType(Constants.Messaging_NotificationTypeId); this._mockNotificationsController.Verify(); - } - + } + [Test] public void GetNotificationType_By_Id_Gets_Object_From_Cache() { @@ -286,8 +280,8 @@ public void GetNotificationType_By_Name_Returns_Valid_Object() var actualNotificationType = this._notificationsController.GetNotificationType(Constants.Messaging_NotificationTypeName); Assert.IsTrue(new NotificationTypeComparer().Equals(expectedNotificationType, actualNotificationType)); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetNotificationTypeActions_Throws_On_Null() @@ -327,25 +321,25 @@ 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( new[] { CreateNewNotificationTypeAction(), CreateNewNotificationTypeAction() }, Constants.Messaging_NotificationTypeId); - this._mockDataService.Verify( - x => x.AddNotificationTypeAction( + this._mockDataService.Verify( + x => x.AddNotificationTypeAction( Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey, Constants.Messaging_NotificationTypeActionDescriptionResourceKey, @@ -379,8 +373,8 @@ public void SetNotificationTypeActions_Sets_NotificationTypeActionId_And_Notific this._mockNotificationsController.Object.SetNotificationTypeActions(new[] { action }, expectedNotificationTypeAction.NotificationTypeId); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, action)); - } - + } + [Test] public void DeleteNotificationTypeAction_Calls_DataService_DeleteNotificationTypeAction() { @@ -397,8 +391,8 @@ public void DeleteNotificationTypeAction_Removes_Cache_Object() this._mockNotificationsController.Setup(nc => nc.RemoveNotificationTypeActionCache()).Verifiable(); this._mockNotificationsController.Object.DeleteNotificationTypeAction(Constants.Messaging_NotificationTypeActionId); this._mockNotificationsController.Verify(); - } - + } + [Test] public void GetNotificationTypeAction_By_Id_Gets_Object_From_Cache() { @@ -512,8 +506,8 @@ public void GetNotificationTypeAction_By_Name_Returns_Valid_Object() var actualNotificationTypeAction = this._notificationsController.GetNotificationTypeAction(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationTypeActionNameResourceKey); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeAction)); - } - + } + [Test] public void GetNotificationTypeActions_Calls_DataService_GetNotificationTypeActions() { @@ -549,8 +543,8 @@ public void GetNotificationTypeActions_Returns_Valid_Object() Assert.AreEqual(1, actualNotificationTypeActions.Count); Assert.IsTrue(new NotificationTypeActionComparer().Equals(expectedNotificationTypeAction, actualNotificationTypeActions[0])); - } - + } + [Test] public void SendNotification_Sets_Empty_SenderUserId_With_Admin() { @@ -627,7 +621,7 @@ public void SendNotification_Throws_On_Large_Subject() { subject.Append("1234567890"); } - + notification.Subject = subject.ToString(); var mockPortalInfo = CreatePortalInfo(Constants.PORTAL_Zero, Null.NullInteger); @@ -680,11 +674,11 @@ 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); @@ -770,7 +764,7 @@ public void SendNotification_Calls_DataService_On_Valid_Notification_When_Portal this._mockDataService.Verify(); } - + [Test] public void SendNotification_Calls_Messaging_DataService_CreateSocialMessageRecipientsForRole_When_Passing_Roles() { @@ -951,8 +945,8 @@ public void SendNotification_Returns_Valid_Object() users); Assert.IsTrue(new NotificationComparer().Equals(expectedNotification, notification)); - } - + } + [Test] public void DeleteNotification_Calls_DataService_DeleteNotification() { @@ -966,8 +960,8 @@ public void DeleteNotification_Calls_DataService_DeleteNotification() this._mockDataService.Setup(ds => ds.DeleteNotification(Constants.Messaging_MessageId_1)).Verifiable(); this._notificationsController.DeleteNotification(Constants.Messaging_MessageId_1); this._mockDataService.Verify(); - } - + } + [Test] public void GetNotifications_Calls_DataService_GetNotifications() { @@ -1011,16 +1005,16 @@ public void GetNotifications_Calls_DataService_GetNotificationByContext() this._notificationsController.GetNotificationByContext(Constants.Messaging_NotificationTypeId, Constants.Messaging_NotificationContext); this._mockDataService.Verify(); - } - + } + [Test] public void CountNotifications_Calls_DataService_CountNotifications() { this._mockDataService.Setup(ds => ds.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero)).Verifiable(); this._notificationsController.CountNotifications(Constants.UserID_User12, Constants.PORTAL_Zero); this._mockDataService.Verify(); - } - + } + [Test] public void DeleteNotificationRecipient_Calls_MessagingController_DeleteMessageRecipient() { @@ -1062,8 +1056,8 @@ public void DeleteNotificationRecipient_Deletes_Notification_When_There_Are_No_M this._mockInternalMessagingController.Setup(mc => mc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); this._mockNotificationsController.Object.DeleteNotificationRecipient(Constants.Messaging_MessageId_1, Constants.UserID_User12); this._mockNotificationsController.Verify(nc => nc.DeleteNotification(Constants.Messaging_MessageId_1)); - } - + } + [Test] public void DeleteAllNotificationRecipients_Calls_DeleteNotificationRecipient_For_Each_Recipient() { @@ -1086,20 +1080,20 @@ public void DeleteAllNotificationRecipients_Does_Not_Call_DeleteNotificationReci this._mockInternalMessagingController.Setup(imc => imc.GetMessageRecipients(Constants.Messaging_MessageId_1)).Returns(new List()); this._mockNotificationsController.Object.DeleteAllNotificationRecipients(Constants.Messaging_MessageId_1); this._mockNotificationsController.Verify(nc => nc.DeleteNotificationRecipient(It.IsAny(), It.IsAny()), Times.Never()); - } - + } + 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, }; } @@ -1142,12 +1136,12 @@ 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, }; } @@ -1170,6 +1164,12 @@ private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int mast return mockPortalGroupInfo; } + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + } + private void SetupDataTables() { this._dtNotificationTypes = new DataTable(); @@ -1206,22 +1206,22 @@ private void SetupDataTables() this._dtNotificationActions.Columns.Add("CreatedOnDate", typeof(DateTime)); this._dtNotificationActions.Columns.Add("LastModifiedByUserID", typeof(int)); this._dtNotificationActions.Columns.Add("LastModifiedOnDate", typeof(DateTime)); - } - + } + private class NotificationTypeComparer : IEqualityComparer { public bool Equals(NotificationType x, NotificationType y) { - if (x == null) - { - return y == null; - } - - if (y == null) - { - return false; - } - + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + return x.NotificationTypeId == y.NotificationTypeId && x.Name == y.Name && @@ -1241,16 +1241,16 @@ private class NotificationTypeActionComparer : IEqualityComparer { public bool Equals(Notification x, Notification y) { - if (x == null) - { - return y == null; - } - - if (y == null) - { - return false; - } - + if (x == null) + { + return y == null; + } + + if (y == null) + { + return false; + } + return x.NotificationID == y.NotificationID && x.NotificationTypeID == y.NotificationTypeID && @@ -1296,7 +1296,7 @@ public int GetHashCode(Notification obj) { throw new NotImplementedException(); } - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs index 18650a19510..b5b6b91e4bd 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionControllerTests.cs @@ -46,8 +46,8 @@ public void TearDown() DataService.ClearInstance(); SubscriptionSecurityController.ClearInstance(); MockComponentProvider.ResetContainer(); - } - + } + [Test] public void IsSubscribed_ShouldReturnFalse_IfUserIsNotSubscribed() { @@ -143,7 +143,7 @@ public void IsSubscribed_ShouldCallDataService_WhenNoError() this.subscriptionController.IsSubscribed(subscription); // Assert - this.mockDataService.Verify( + this.mockDataService.Verify( ds => ds.IsSubscribed( subscription.PortalId, subscription.UserId, @@ -151,8 +151,8 @@ public void IsSubscribed_ShouldCallDataService_WhenNoError() subscription.ObjectKey, subscription.ModuleId, subscription.TabId), Times.Once); - } - + } + [Test] public void AddSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { @@ -217,7 +217,7 @@ public void AddSubscription_ShouldCallDataService_WhenNoError() this.subscriptionController.AddSubscription(subscription); // Assert - this.mockDataService.Verify( + this.mockDataService.Verify( ds => ds.AddSubscription( subscription.UserId, subscription.PortalId, @@ -253,8 +253,8 @@ public void AddSubscription_ShouldFilledUpTheSubscriptionIdPropertyOfTheInputSub // Assert Assert.AreEqual(expectedSubscriptionId, subscription.SubscriptionId); - } - + } + [Test] public void DeleteSubscription_ShouldThrowArgumentNullException_WhenSubscriptionIsNull() { @@ -306,6 +306,6 @@ public void DeleteSubscriptionType_ShouldNotCallDeleteSubscriptionDataService_Wh // Assert this.mockDataService.Verify(ds => ds.DeleteSubscription(It.IsAny()), Times.Never); - } + } } } 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 96e2ce0974e..81022007ee8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/SubscriptionTypeControllerTests.cs @@ -21,7 +21,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Messaging public class SubscriptionTypeControllerTests { private const string SubscriptionTypesCacheKey = "DNN_" + DataCache.SubscriptionTypesCacheKey; - + private SubscriptionTypeController subscriptionTypeController; private Mock mockDataService; private Mock mockCacheProvider; @@ -37,8 +37,8 @@ public void SetUp() // Setup SUT this.subscriptionTypeController = new SubscriptionTypeController(); - } - + } + [Test] public void GetSubscriptionTypes_ShouldCallDataService_WhenNoError() { @@ -66,15 +66,15 @@ public void GetSubscriptionTypes_ShouldThrowArgumentNullException_WhenPredicateI { // Act, Arrange Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionTypes(null)); - } - + } + [Test] public void GetSubscriptionType_ShouldThrowArgumentNullException_WhenPredicateIsNull() { // Act, Assert Assert.Throws(() => this.subscriptionTypeController.GetSubscriptionType(null)); - } - + } + [Test] public void AddSubscriptionType_ShouldThrowArgumentNullException_WhenSubscriptionTypeIsNull() { @@ -117,8 +117,8 @@ public void AddSubscriptionType_ShouldCleanCache_WhenNoError() // Assert this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - + } + [Test] public void DeleteSubscriptionType_ShouldThrowArgumentOutOfRangeException_WhenSubscriptionTypeIdIsNegative() { @@ -169,8 +169,8 @@ public void DeleteSubscriptionType_ShouldCleanCache_WhenNoError() // Assert this.mockCacheProvider.Verify(cp => cp.Remove(SubscriptionTypesCacheKey), Times.Once()); - } - + } + [TearDown] public void TearDown() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs index 928b7a92a3e..8786dc9e865 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Messaging/UserPreferencesControllerTests.cs @@ -47,15 +47,15 @@ public void SetUp() public void TearDown() { ComponentFactory.Container = null; - } - + } + [Test] public void UserPreferencesController_ShouldThrowArgumentNullException_WhenNullDataServiceIsPassedInTheConstructor() { // Act, Assert Assert.Throws(() => new UserPreferencesController(null)); - } - + } + [Test] public void SetUserPreference_ShouldCallDataService_WhenNoError() { @@ -72,14 +72,14 @@ public void SetUserPreference_ShouldCallDataService_WhenNoError() this.userPrefencesController.SetUserPreference(userPreference); // Assert - this.mockDataService.Verify( + this.mockDataService.Verify( ds => ds.SetUserPreference( userPreference.PortalId, userPreference.UserId, (int)userPreference.MessagesEmailFrequency, (int)userPreference.NotificationsEmailFrequency), Times.Once); - } - + } + [Test] public void GetUserPreference_ShouldReturnNullObject_WhenUserDoesNotHavePreference() { @@ -118,8 +118,8 @@ public void GetUserPreference_ShouldReturnUserPreference_WhenUserHasPreference() Assert.AreEqual(expectedUserPreference.NotificationsEmailFrequency, userPreference.NotificationsEmailFrequency); Assert.AreEqual(user.PortalID, userPreference.PortalId); Assert.AreEqual(user.UserID, userPreference.UserId); - } - + } + private static UserInfo GetValidUser() { return new UserInfo 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 6f554a11169..ea74097cfe7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalControllerTests.cs @@ -18,20 +18,18 @@ public class PortalControllerTests { private const string HostMapPath = @"C:\path"; private const string DefaultName = "Default"; - - 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 string DefaultPath = MakePath(DefaultName); + private static readonly string DefaultDePath = MakePath(DefaultName, "de-DE"); + private static readonly Dictionary DefaultExpectationsDe = new Dictionary { { "Name", DefaultDeName }, @@ -42,6 +40,7 @@ public class PortalControllerTests }; private static readonly string DefaultUsPath = MakePath(DefaultName, "en-US"); + private static readonly Dictionary DefaultExpectationsUs = new Dictionary { { "Name", DefaultName }, @@ -49,8 +48,10 @@ public class PortalControllerTests { "LanguageFilePath", DefaultUsPath }, { "CultureCode", "en-US" }, }; + private static readonly string CultureCode = Thread.CurrentThread.CurrentCulture.Name; private static readonly string StaticPath = MakePath(StaticName); + private static readonly Dictionary StaticExpectations = new Dictionary { { "Name", StaticName }, @@ -58,8 +59,10 @@ public class PortalControllerTests { "Description", StaticDescription }, { "CultureCode", CultureCode }, }; + private static readonly string AlternatePath = MakePath(AlternateName); private static readonly string AlternateDePath = MakePath(AlternateName, "de-DE"); + private static readonly Dictionary AlternateExpectationsDe = new Dictionary { { "Name", AlternateDeName }, @@ -67,8 +70,10 @@ public class PortalControllerTests { "LanguageFilePath", AlternateDePath }, { "CultureCode", "de-DE" }, }; + private static readonly string ResourcePath = MakePath(ResourceName); private static readonly string ResourceFilePath = ResourcePath + ".resources"; + private static readonly Dictionary ResourceExpectations = new Dictionary { { "Name", ResourceName }, @@ -77,6 +82,8 @@ public class PortalControllerTests { "CultureCode", CultureCode }, }; + private Mock _mockPortalTemplateIO; + [SetUp] public void SetUp() { @@ -94,7 +101,7 @@ public void TearDown() public void NoTemplatesReturnsEmptyList() { // Arrange - + // Act var templates = PortalController.Instance.GetAvailablePortalTemplates(); @@ -129,7 +136,7 @@ public void TemplatesWithNoLanguageFilesAreLoaded() Assert.AreEqual(1, templates.Count); AssertTemplateInfo(StaticExpectations, templates[0]); } - + [Test] public void TemplateWith2Languages() { @@ -275,6 +282,17 @@ private static void AssertTemplateField(Dictionary expectations, } } + private static string MakePath(string name) + { + var fileName = name + ".template"; + return Path.Combine(HostMapPath, fileName); + } + + private static string MakePath(string name, string culture) + { + return string.Format(@"{0}.{1}.resx", MakePath(name), culture); + } + private TextReader CreateLanguageFileReader(string name) { return this.CreateLanguageFileReader(name, null); @@ -286,7 +304,7 @@ private TextReader CreateLanguageFileReader(string name, string description) { description = string.Format("{0}", description); } - + var xml = string.Format("{0}{1}", name, description); return new StringReader(xml); } @@ -297,17 +315,6 @@ private TextReader CreateTemplateFileReader(string description) return new StringReader(xml); } - private static string MakePath(string name) - { - var fileName = name + ".template"; - return Path.Combine(HostMapPath, fileName); - } - - 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 2828e16f7af..824af839ab3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Portal/PortalGroupControllerTests.cs @@ -25,9 +25,9 @@ public class PortalGroupControllerTests { private Mock _mockData; #pragma warning disable 649 - private UserCopiedCallback userCopied; + private UserCopiedCallback userCopied; #pragma warning restore 649 - + [SetUp] public void SetUp() { @@ -47,8 +47,8 @@ public void SetUp() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_Constructor_Throws_On_Null_DataService() @@ -69,8 +69,8 @@ public void PortalGroupController_Constructor_Throws_On_Null_PortalController() // Act, Assert new PortalGroupController(mockDataService.Object, null); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_AddPortalToGroup_Throws_On_Null_PortalGroup() @@ -94,7 +94,7 @@ public void PortalGroupController_AddPortalToGroup_Throws_On_Null_Portal() var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - + // Act, Assert controller.AddPortalToGroup(null, portalGroup, this.userCopied); } @@ -131,8 +131,8 @@ public void PortalGroupController_AddPortalToGroup_Throws_On_Negative_PortalId() // Act, Assert controller.AddPortalToGroup(portal, portalGroup, this.userCopied); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_AddPortalGroup_Throws_On_Null_PortalGroup() @@ -226,8 +226,8 @@ public void PortalGroupController_AddPortalGroup_Sets_PortalGroupId_Property_On_ // Assert Assert.AreEqual(Constants.PORTALGROUP_AddPortalGroupId, portalGroup.PortalGroupId); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_DeletePortalGroup_Throws_On_Null_PortalGroup() @@ -274,8 +274,8 @@ public void PortalGroupController_DeletePortalGroup_Calls_DataService_On_Valid_P // Assert mockDataService.Verify(ds => ds.DeletePortalGroup(portalGroup)); - } - + } + [Test] public void PortalGroupController_GetPortalGroups_Calls_DataService() @@ -325,7 +325,7 @@ public void PortalGroupController_GetPortalGroups_Returns_List_Of_PortalGroups() mockCache.Setup(c => c.GetItem(CachingProvider.GetCacheKey(DataCache.PortalGroupsCacheKey))).Returns(null); Mock mockDataService = new Mock(); - mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader( + mockDataService.Setup(ds => ds.GetPortalGroups()).Returns(CreateValidPortalGroupsReader( Constants.PORTALGROUP_ValidPortalGroupCount, Constants.USER_ValidId)); @@ -337,8 +337,8 @@ public void PortalGroupController_GetPortalGroups_Returns_List_Of_PortalGroups() // Assert Assert.AreEqual(Constants.PORTALGROUP_ValidPortalGroupCount, portalGroups.Count()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_PortalGroup() @@ -362,7 +362,7 @@ public void PortalGroupController_RemovePortalFromGroup_Throws_On_Null_Portal() var mockPortalController = new Mock(); var controller = new PortalGroupController(mockDataService.Object, mockPortalController.Object); var portalGroup = new PortalGroupInfo { PortalGroupId = Constants.PORTALGROUP_ValidPortalGroupId }; - + // Act, Assert controller.RemovePortalFromGroup(null, portalGroup, false, this.userCopied); } @@ -399,8 +399,8 @@ public void PortalGroupController_RemovePortalFromGroup_Throws_On_Negative_Porta // Act, Assert controller.RemovePortalFromGroup(portal, portalGroup, false, this.userCopied); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void PortalGroupController_UpdatePortalGroup_Throws_On_Null_PortalGroup() @@ -447,8 +447,8 @@ public void PortalGroupController_UpdatePortalGroup_Calls_DataService_On_Valid_P // Assert mockDataService.Verify(ds => ds.UpdatePortalGroup(portalGroup, It.IsAny())); - } - + } + private static DataTable CreatePortalGroupTable() { // Create Categories table. @@ -483,11 +483,11 @@ 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 288665d2fb4..6a3ce265d2e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/FakeModuleCrawlerController.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Search ///
    /// public class FakeResultController : BaseResultController - { + { public override bool HasViewPermission(SearchResult searchResult) { return true; @@ -21,9 +21,9 @@ 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"; - } + } } public class NoPermissionFakeResultController : FakeResultController 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 bb227586b68..5066e44103b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/InternalSearchControllerTests.cs @@ -31,16 +31,7 @@ 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, - TabSearchTypeId, - DocumentSearchTypeId, - UrlSearchTypeId, - OtherSearchTypeId, - UnknownSearchTypeId, - } + private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; @@ -86,8 +77,18 @@ public enum SearchTypeIds private Mock _mockUserController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - + private LuceneControllerImpl _luceneController; + + public enum SearchTypeIds + { + ModuleSearchTypeId = 1, + TabSearchTypeId, + DocumentSearchTypeId, + UrlSearchTypeId, + OtherSearchTypeId, + UnknownSearchTypeId, + } + [SetUp] public void SetUp() { @@ -143,228 +144,6 @@ public void SearchController_Add_Throws_On_Null_Or_Empty_UniqueuKey() // Act, Assert Assert.Throws(() => this._internalSearchController.AddSearchDocument(new SearchDocument())); } - - private void CreateNewLuceneControllerInstance() - { - this.DeleteIndexFolder(); - InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - this._internalSearchController = InternalSearchController.Instance; - - if (this._luceneController != null) - { - LuceneController.ClearInstance(); - this._luceneController.Dispose(); - } - - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); - } - - private void SetupHostController() - { - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) - .Returns(Constants.DefaultSearchDescriptionBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - HostController.RegisterInstance(this._mockHostController.Object); - } - - private void SetupLocaleController() - { - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - } - - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - DataTableReader searchTypes = null; - this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) - .Returns(() => searchTypes); - - this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(PortalId0, CultureEnUs); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - var table = new DataTable("Portal"); - - var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", - "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", - "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", - "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", - "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - const int homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, - "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, - "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", - null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", "7", null, null, "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - - private void SetupSearchHelper() - { - this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(this.GetSynonymsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) - .Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); - this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); - this._mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(this.GetSynonymsGroupsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEsEs, - StopWords = "los,de,el", - }); - this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) - .Returns(new SearchHelperImpl().RephraseSearchText); - this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); - } - - private IList GetSynonymsGroupsCallBack() - { - var groups = new List - { - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke) }, - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook) }, - new SynonymsGroup { PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop) }, - }; - - return groups; - } - - private SearchType GetSearchTypeByNameCallback(string searchTypeName) - { - var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; - switch (searchTypeName) - { - case ModuleSearchTypeName: - searchType.SearchTypeId = ModuleSearchTypeId; - break; - case TabSearchTypeName: - searchType.SearchTypeId = TabSearchTypeId; - break; - case OtherSearchTypeName: - searchType.SearchTypeId = OtherSearchTypeId; - break; - case DocumentSearchTypeName: - searchType.SearchTypeId = DocumentSearchTypeId; - break; - case UrlSearchTypeName: - searchType.SearchTypeId = UrlSearchTypeId; - break; - } - - return searchType; - } - - private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) - { - var synonyms = new List(); - if (term == "fox") - { - synonyms.Add("wolf"); - } - - return synonyms; - } - - private UserInfo GetUserByIdCallback(int portalId, int userId) - { - return new UserInfo { UserID = userId, DisplayName = "User" + userId, PortalID = portalId }; - } - - private DataTable GetAllSearchTypes() - { - var dtSearchTypes = new DataTable("SearchTypes"); - var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); - dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); - dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); - dtSearchTypes.PrimaryKey = new[] { pkId }; - - // Create default Crawler - dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); - dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); - - return dtSearchTypes; - } - - private IEnumerable GetSearchTypes() - { - var searchTypes = new List - { - new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType - { - SearchTypeId = DocumentSearchTypeId, - SearchTypeName = DocumentSearchTypeName, - SearchResultClass = NoPermissionFakeResultControllerClass, - }, - new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, - }; - - return searchTypes; - } - - private void DeleteIndexFolder() - { - try - { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } - } - catch (Exception ex) - { - Console.WriteLine(ex); - } - } [Test] public void SearchController_Add_Throws_On_Null_OrEmpty_Title() @@ -375,7 +154,7 @@ public void SearchController_Add_Throws_On_Null_OrEmpty_Title() Assert.Throws( () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString() })); } - + [Test] public void SearchController_AddSearchDcoumets_Does_Not_Throw_On_Null_OrEmpty_Title() { @@ -425,8 +204,8 @@ public void SearchController_Add_Throws_On_DateTimeMin_ModifiedTimeUtc() // Act, Assert Assert.Throws( () => this._internalSearchController.AddSearchDocument(new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "title", SearchTypeId = 1 })); - } - + } + [Test] public void SearchController_Add_Then_Delete_ModuleDefinition_WorksAsExpected() { @@ -695,6 +474,228 @@ public void SearchController_Add_Then_Delete_Users_WorksAsExpected() Assert.AreEqual(2, stats.TotalDeletedDocuments); } + private void CreateNewLuceneControllerInstance() + { + this.DeleteIndexFolder(); + InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); + this._internalSearchController = InternalSearchController.Instance; + + if (this._luceneController != null) + { + LuceneController.ClearInstance(); + this._luceneController.Dispose(); + } + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); + } + + private void SetupHostController() + { + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())) + .Returns(Constants.DefaultSearchDescriptionBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + HostController.RegisterInstance(this._mockHostController.Object); + } + + private void SetupLocaleController() + { + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + DataTableReader searchTypes = null; + this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) + .Returns(() => searchTypes); + + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + var table = new DataTable("Portal"); + + var cols = new[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", + "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", + "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", + "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", + "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + const int homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, + "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, + "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", + null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", "7", null, null, "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private void SetupSearchHelper() + { + this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(this.GetSynonymsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())) + .Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this._mockSearchHelper.Setup(c => c.GetSynonymsGroups(It.IsAny(), It.IsAny())).Returns(this.GetSynonymsGroupsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEsEs, + StopWords = "los,de,el", + }); + this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns(new SearchHelperImpl().RephraseSearchText); + this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); + } + + private IList GetSynonymsGroupsCallBack() + { + var groups = new List + { + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 1, SynonymsTags = string.Join(",", TermDNN, TermDotNetNuke) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 2, SynonymsTags = string.Join(",", TermLaptop, TermNotebook) }, + new SynonymsGroup { PortalId = 0, SynonymsGroupId = 3, SynonymsTags = string.Join(",", TermJump, TermLeap, TermHop) }, + }; + + return groups; + } + + private SearchType GetSearchTypeByNameCallback(string searchTypeName) + { + var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; + switch (searchTypeName) + { + case ModuleSearchTypeName: + searchType.SearchTypeId = ModuleSearchTypeId; + break; + case TabSearchTypeName: + searchType.SearchTypeId = TabSearchTypeId; + break; + case OtherSearchTypeName: + searchType.SearchTypeId = OtherSearchTypeId; + break; + case DocumentSearchTypeName: + searchType.SearchTypeId = DocumentSearchTypeId; + break; + case UrlSearchTypeName: + searchType.SearchTypeId = UrlSearchTypeId; + break; + } + + return searchType; + } + + private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) + { + var synonyms = new List(); + if (term == "fox") + { + synonyms.Add("wolf"); + } + + return synonyms; + } + + private UserInfo GetUserByIdCallback(int portalId, int userId) + { + return new UserInfo { UserID = userId, DisplayName = "User" + userId, PortalID = portalId }; + } + + private DataTable GetAllSearchTypes() + { + var dtSearchTypes = new DataTable("SearchTypes"); + var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); + dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); + dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); + dtSearchTypes.PrimaryKey = new[] { pkId }; + + // Create default Crawler + dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); + dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); + + return dtSearchTypes; + } + + private IEnumerable GetSearchTypes() + { + var searchTypes = new List + { + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType + { + SearchTypeId = DocumentSearchTypeId, + SearchTypeName = DocumentSearchTypeName, + SearchResultClass = NoPermissionFakeResultControllerClass, + }, + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, + }; + + return searchTypes; + } + + private void DeleteIndexFolder() + { + try + { + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + private SearchStatistics GetSearchStatistics() { this._internalSearchController.Commit(); 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 0e8ea3fd40f..5b26371f73f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/LuceneControllerTests.cs @@ -34,7 +34,6 @@ public class LuceneControllerTests { 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"; @@ -52,6 +51,7 @@ public class LuceneControllerTests // Arrange private const int TotalTestDocs2Create = 5; private const string ContentFieldName = "content"; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockHostController; private LuceneControllerImpl _luceneController; @@ -111,70 +111,6 @@ public void LuceneController_Add_Throws_On_Null_Document() Assert.Throws(() => this._luceneController.Add(null)); } - private void CreateNewLuceneControllerInstance() - { - if (this._luceneController != null) - { - LuceneController.ClearInstance(); - this._luceneController.Dispose(); - } - - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); - } - - private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) - { - var synonyms = new List(); - if (term == "fox") - { - synonyms.Add("wolf"); - } - - return synonyms; - } - - private void DeleteIndexFolder() - { - try - { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } - } - catch (Exception ex) - { - Console.WriteLine(ex); - } - } - - /// - /// Adds standarad SearchDocs in Lucene Index. - /// - private void AddStandardDocs() - { - string[] lines = - { - Line1, Line2, Line3, Line4, - }; - - this.AddLinesAsSearchDocs(lines); - } - - 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(); - } - public void LuceneController_Add_Throws_On_Null_Query() { // Arrange @@ -719,38 +655,6 @@ public void LuceneController_TestDeleteBeforeOptimize() Assert.AreEqual(TotalTestDocs2Create - delCount, this._luceneController.SearchbleDocsCount()); } - private int AddTestDocs() - { - // Act - for (var i = 0; i < TotalTestDocs2Create; i++) - { - var doc = new Document(); - - // format to "D#" because LengthFilter will not consider words of length < 3 or > 255 characters in length (defaults) - doc.Add(new Field(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen), Field.Store.YES, Field.Index.ANALYZED)); - this._luceneController.Add(doc); - } - - this._luceneController.Commit(); - return TotalTestDocs2Create; - } - - private int DeleteTestDocs() - { - // Act - // delete odd docs => [1, 3] - var delCount = 0; - for (var i = 1; i < TotalTestDocs2Create; i += 2) - { - // format to "D#" because LengthFilter will not consider the defaults for these values - this._luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); - delCount++; - } - - this._luceneController.Commit(); - return delCount; - } - [Test] public void LuceneController_TestDeleteAfterOptimize() { @@ -788,6 +692,102 @@ public void SearchController_LuceneControllerReaderIsNotNullWhenWriterIsNull() Assert.IsNotNull(this._luceneController.GetSearcher()); } + private void CreateNewLuceneControllerInstance() + { + if (this._luceneController != null) + { + LuceneController.ClearInstance(); + this._luceneController.Dispose(); + } + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); + } + + private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) + { + var synonyms = new List(); + if (term == "fox") + { + synonyms.Add("wolf"); + } + + return synonyms; + } + + private void DeleteIndexFolder() + { + try + { + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + + /// + /// Adds standarad SearchDocs in Lucene Index. + /// + private void AddStandardDocs() + { + string[] lines = + { + Line1, Line2, Line3, Line4, + }; + + this.AddLinesAsSearchDocs(lines); + } + + 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(); + } + + private int AddTestDocs() + { + // Act + for (var i = 0; i < TotalTestDocs2Create; i++) + { + var doc = new Document(); + + // format to "D#" because LengthFilter will not consider words of length < 3 or > 255 characters in length (defaults) + doc.Add(new Field(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen), Field.Store.YES, Field.Index.ANALYZED)); + this._luceneController.Add(doc); + } + + this._luceneController.Commit(); + return TotalTestDocs2Create; + } + + private int DeleteTestDocs() + { + // Act + // delete odd docs => [1, 3] + var delCount = 0; + for (var i = 1; i < TotalTestDocs2Create; i += 2) + { + // format to "D#" because LengthFilter will not consider the defaults for these values + this._luceneController.Delete(new TermQuery(new Term(ContentFieldName, i.ToString("D" + Constants.DefaultMinLen)))); + delCount++; + } + + this._luceneController.Commit(); + return delCount; + } + private LuceneSearchContext CreateSearchContext(LuceneQuery luceneQuery) { return new LuceneSearchContext { LuceneQuery = luceneQuery, SearchQuery = this._mockSearchQuery.Object }; 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 366b311530f..c01cf4703ac 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchControllerTests.cs @@ -32,20 +32,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, - TabSearchTypeId, - DocumentSearchTypeId, - UrlSearchTypeId, - OtherSearchTypeId, - UnknownSearchTypeId, - } private const int UrlSearchTypeId = (int)SearchTypeIds.UrlSearchTypeId; private const int OtherSearchTypeId = (int)SearchTypeIds.OtherSearchTypeId; private const int UnknownSearchTypeId = (int)SearchTypeIds.UnknownSearchTypeId; @@ -120,7 +110,7 @@ public enum SearchTypeIds private const int CustomBoost = 80; private const string SearchIndexFolder = @"App_Data\SearchTests"; - private const int DefaultSearchRetryTimes = 5; + private const int DefaultSearchRetryTimes = 5; private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockHostController; private Mock _mockCachingProvider; @@ -131,8 +121,18 @@ public enum SearchTypeIds private SearchControllerImpl _searchController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - + private LuceneControllerImpl _luceneController; + + public enum SearchTypeIds + { + ModuleSearchTypeId = 1, + TabSearchTypeId, + DocumentSearchTypeId, + UrlSearchTypeId, + OtherSearchTypeId, + UnknownSearchTypeId, + } + [SetUp] public void SetUp() { @@ -154,7 +154,7 @@ public void SetUp() this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns((int portalId, int userId) => this.GetUserByIdCallback(portalId, userId)); UserController.SetTestableInstance(this._mockUserController.Object); - + this.CreateNewLuceneControllerInstance(); } @@ -168,8 +168,8 @@ public void TearDown() SearchHelper.ClearInstance(); LuceneController.ClearInstance(); this._luceneController = null; - } - + } + [Test] public void SearchController_Search_Throws_On_Null_Query() { @@ -188,754 +188,440 @@ public void SearchController_Search_Throws_On_Empty_TypeId_Collection() 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) + [Test] + public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() { - var r = default(R); // init default return value - Exception ex = null; // records inter-thread exception + // Arrange + var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< - { - try - { - r = proc(); - } - catch (Exception e) - { - // this can get set to ThreadAbortException - ex = e; + // Act, Assert + this._internalSearchController.AddSearchDocument(document); + } - Console.WriteLine("Exception hit"); - } - }); + [Test] + public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing2() + { + // Arrange + var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "<= 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"); - } - } + // Act, Assert + Assert.DoesNotThrow(() => ExecuteWithTimeout( + () => + { + this._internalSearchController.AddSearchDocument(document); + return false; + }, TimeSpan.FromSeconds(1))); + } - if (ex != null) - { - throw ex; // oops - } - - return r; // ah! - } - - private void CreateNewLuceneControllerInstance(bool reCreate = false) + [Test] + public void SearchController_Added_Item_IsRetrieved() { - InternalSearchController.SetTestableInstance(new InternalSearchControllerImpl()); - this._internalSearchController = InternalSearchController.Instance; - this._searchController = new SearchControllerImpl(); + // Arrange + var doc = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - if (!reCreate) - { - this.DeleteIndexFolder(); + // Act + this._internalSearchController.AddSearchDocument(doc); - if (this._luceneController != null) - { - LuceneController.ClearInstance(); - this._luceneController.Dispose(); - } - - this._luceneController = new LuceneControllerImpl(); - LuceneController.SetTestableInstance(this._luceneController); - } - } + var result = this.SearchForKeyword("hello"); - private void SetupHostController() - { - this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); - this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); - this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); - HostController.RegisterInstance(this._mockHostController.Object); + // Assert + Assert.AreEqual(1, result.Results.Count); + Assert.AreEqual(result.Results[0].UniqueKey, doc.UniqueKey); + Assert.AreEqual(result.Results[0].Title, doc.Title); } - private void SetupLocaleController() + [Test] + public void SearchController_EnsureIndexIsAppended_When_Index_Is_NotDeleted_InBetween() { - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + // Arrange + string[] docs = + { + Line1, + Line2, + }; - this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); - this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); - } + // Act - private void SetupDataProvider() - { - // Standard DataProvider Path for Logging - this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + // Add first document + var doc1 = new SearchDocument { Title = docs[0], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this._internalSearchController.AddSearchDocument(doc1); - DataTableReader searchTypes = null; - this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) - .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) - .Returns(() => searchTypes); + // first luceneQuery + var query1 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; + var search1 = this._searchController.SiteSearch(query1); - this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + // Assert + Assert.AreEqual(1, search1.Results.Count); + + // Add second document + var doc2 = new SearchDocument { Title = docs[1], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; + this._internalSearchController.AddSearchDocument(doc2); + this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion + + // second luceneQuery + var query2 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; + var search2 = this._searchController.SiteSearch(query2); + + // Assert + Assert.AreEqual(2, search2.Results.Count); } - private IDataReader GetPortalsCallBack(string culture) + [Test] + public void SearchController_Getsearch_TwoTermsSearch() { - return this.GetPortalCallBack(PortalId0, CultureEnUs); + // Arrange + string[] docs = + { + Line1, + Line2, + Line3, + Line4, + Line5, + }; + + this.AddLinesAsSearchDocs(docs); + + // Act + var search = this.SearchForKeyword("fox jumps"); + + // Assert + Assert.AreEqual(docs.Length, search.Results.Count); + + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); } - private IDataReader GetPortalCallBack(int portalId, string culture) + [Test] + public void SearchController_GetResult_TwoTermsSearch() { - var table = new DataTable("Portal"); + // Arrange + string[] docs = + { + Line1, + Line2, + Line3, + Line4, + Line5, + }; - var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; + this.AddLinesAsSearchDocs(docs); - foreach (var col in cols) - { - table.Columns.Add(col); - } + // Act + var search = this.SearchForKeyword("fox jumps"); - const int homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, - "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, - "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", - null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + // Assert + Assert.AreEqual(docs.Length, search.Results.Count); - return table.CreateDataReader(); + // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); + // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); } - private void SetupSearchHelper() + [Test] + public void SearchController_GetResult_PortalIdSearch() { - this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); - this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); - this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); - this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEsEs, - StopWords = "los,de,el", - }); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEnUs, - StopWords = "the,over", - }); - this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( - new SearchStopWords - { - PortalId = 0, - CultureCode = CultureEnCa, - StopWords = "the,over", - }); + // Arrange + var added = this.AddStandardSearchDocs(); - this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); - this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); - SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, PortalIds = new List { PortalId0 } }; + var search = this._searchController.SiteSearch(query); + + // Assert + Assert.AreEqual(added, search.Results.Count); } - private SearchType GetSearchTypeByNameCallback(string searchTypeName) + [Test] + public void SearchController_GetResult_SearchTypeIdSearch() { - var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; - switch (searchTypeName) - { - case ModuleSearchTypeName: - searchType.SearchTypeId = ModuleSearchTypeId; - break; - case TabSearchTypeName: - searchType.SearchTypeId = TabSearchTypeId; - break; - case OtherSearchTypeName: - searchType.SearchTypeId = OtherSearchTypeId; - break; - case DocumentSearchTypeName: - searchType.SearchTypeId = DocumentSearchTypeId; - break; - case UrlSearchTypeName: - searchType.SearchTypeId = UrlSearchTypeId; - break; - } + // Arrange + var added = this.AddStandardSearchDocs(); - return searchType; - } + // Act + var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId } }; + var search = this._searchController.SiteSearch(query); - private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) - { - var synonyms = new List(); - if (term == "fox") - { - synonyms.Add("wolf"); - } - - return synonyms; + // Assert + Assert.AreEqual(added, search.Results.Count); } - private UserInfo GetUserByIdCallback(int portalId, int userId) + [Test] + public void SearchController_SearchFindsAnalyzedVeryLongWords() { - if (portalId == PortalId12 && userId == StandardAuthorId) - { - return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; - } - - return null; - } + // Arrange + // const string fieldName = Constants.ContentTag; + const string veryLongWord = // 107 characters + "NowIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountryalsoIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountry"; - private DataTable GetAllSearchTypes() - { - var dtSearchTypes = new DataTable("SearchTypes"); - var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); - dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); - dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); - dtSearchTypes.PrimaryKey = new[] { pkId }; + var doc = new SearchDocument + { + Title = veryLongWord, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = ModuleSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + ModuleId = 1, + ModuleDefId = 1, + }; + this._internalSearchController.AddSearchDocument(doc); - // Create default Crawler - dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); - dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); - dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); + // Act + var query = new SearchQuery { KeyWords = veryLongWord, SearchTypeIds = new List { ModuleSearchTypeId } }; + var search = this._searchController.SiteSearch(query); - return dtSearchTypes; + // Assert + Assert.AreEqual(1, search.Results.Count); + Assert.AreEqual("" + veryLongWord + "", this.StipEllipses(search.Results[0].Snippet).Trim()); } - private IEnumerable GetSearchTypes() + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPermission() { - var searchTypes = new List - { - new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, - new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass }, - new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, - }; + // Arrange + this.AddStandardSearchDocs(DocumentSearchTypeId); - return searchTypes; + // Act + var result = this.SearchForKeyword("fox", DocumentSearchTypeId); + + // Assert + // by default AuthorUserId = 0 which have no permission, so this passes + Assert.AreEqual(0, result.Results.Count); } - private void DeleteIndexFolder() + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() { - try - { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } - } - catch (Exception ex) + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery { - Console.WriteLine(ex); - } + PageIndex = 1, + PageSize = 4, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; + + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9 }, ids); } - /// - /// Returns few SearchDocs. - /// - private IEnumerable GetStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B() { - var searchDocs = new List + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery { - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag0, Tag1, TagOldest, Tag0WithSpace }, Title = Line1 }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag1, Tag2, TagNeutral }, Title = Line2, CultureCode = CultureEnUs }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line3, CultureCode = CultureItIt }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag3, Tag4, TagLatest }, Title = Line4, CultureCode = CultureEnCa }, - new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line5, CultureCode = CultureEsEs }, + PageIndex = 1, + PageSize = 6, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, }; - var now = DateTime.UtcNow.AddYears(-searchDocs.Count); - var i = 0; - - foreach (var searchDocument in searchDocs) - { - searchDocument.SearchTypeId = searchTypeId; - searchDocument.UniqueKey = Guid.NewGuid().ToString(); - searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; - searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; - searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest - } + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - return searchDocs; + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17 }, ids); } - private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() { - var searchDocs = new List + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery { - new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = { { "title", "Hello" } }, Body = "Hello1 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = { { "subject", "Hello" } }, Body = "Hello2 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = { { "comments", "Hello" } }, Body = "Hello3 World" }, - new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = { { "authorname", "Hello" } }, Body = "Hello4 World" }, + PageIndex = 1, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, }; - var now = DateTime.UtcNow.AddYears(-searchDocs.Count); - var i = 0; - - foreach (var searchDocument in searchDocs) - { - searchDocument.SearchTypeId = searchTypeId; - searchDocument.UniqueKey = Guid.NewGuid().ToString(); - searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; - searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; - searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest - } + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - return searchDocs; + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19 }, ids); } - /// - /// Adds standarad SearchDocs in Lucene Index. - /// - /// Number of dcuments added. - private int AddStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D() { - var docs = this.GetStandardSearchDocs(searchTypeId).ToArray(); - this._internalSearchController.AddSearchDocuments(docs); - return docs.Length; - } + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; // user should have access to some documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); - private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) - { - var docs = this.GetSearchDocsForCustomBoost(searchTypeId).ToArray(); - this._internalSearchController.AddSearchDocuments(docs); - return docs.Length; - } - - private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument - { - Title = "Title", - UniqueKey = "key1", - Body = "hello", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, - }; - var doc2 = new SearchDocument - { - Title = "Title", - UniqueKey = "key2", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, - }; - var doc3 = new SearchDocument - { - Title = "Title", - UniqueKey = "key3", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, - }; - var doc4 = new SearchDocument - { - Title = "Title", - UniqueKey = "key4", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, - }; - var doc5 = new SearchDocument - { - Title = "Title", - UniqueKey = "key5", - 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; - } - - private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) - { - var doc1 = new SearchDocument - { - Title = "Title", - UniqueKey = "key1", - Body = "hello", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, - }; - var doc2 = new SearchDocument - { - Title = "Title", - UniqueKey = "key2", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } }, - }; - var doc3 = new SearchDocument - { - Title = "Title", - UniqueKey = "key3", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } }, - }; - var doc4 = new SearchDocument - { - Title = "Title", - UniqueKey = "key4", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } }, - }; - var doc5 = new SearchDocument + // Act + var query = new SearchQuery { - Title = "Title", - UniqueKey = "key5", - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } }, + PageIndex = 1, + PageSize = 100, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, }; - var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; - - this._internalSearchController.AddSearchDocuments(docs); + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - return docs.Count; + // Assert + Assert.AreEqual(4 * 3, result.TotalHits); + Assert.AreEqual(4 * 3, result.Results.Count); + Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29 }, ids); } - private int AddDocuments(IList titles, string body, int searchTypeId = OtherSearchTypeId) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E() { - 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, - })) + // Arrange + const int maxDocs = 30; + const int stype = TabSearchTypeId; // user should have access to all documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); + + // Act + var query = new SearchQuery { - this._internalSearchController.AddSearchDocument(doc); - count++; - } + PageIndex = 1, + PageSize = 10, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; - return count; + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).Skip(1).ToArray(); + + // Assert + Assert.AreEqual(maxDocs, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(Enumerable.Range(1, 9).ToArray(), ids); } - private int AddDocumentsWithKeywords(IEnumerable keywords, string title, int searchTypeId = OtherSearchTypeId) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F() { - var count = 0; - foreach (var doc in keywords.Select(keyword => new SearchDocument - { - Title = title, - UniqueKey = Guid.NewGuid().ToString(), - Keywords = new Dictionary() { { KeyWord1Name, keyword } }, - SearchTypeId = OtherSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - PortalId = PortalId12, - })) - { - this._internalSearchController.AddSearchDocument(doc); - count++; - } + // Arrange + const int maxDocs = 100; + const int stype = TabSearchTypeId; // user should have access to all documnets here + this.SetupSecurityTrimmingDocs(maxDocs, stype); - return count; - } + // Act + var query = new SearchQuery + { + PageIndex = 10, + PageSize = 10, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; - private void AddLinesAsSearchDocs(IList lines, int searchTypeId = OtherSearchTypeId) - { - var now = DateTime.UtcNow - TimeSpan.FromSeconds(lines.Count()); - var i = 0; + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - this._internalSearchController.AddSearchDocuments( - lines.Select(line => - new SearchDocument - { - Title = line, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = searchTypeId, - ModifiedTimeUtc = now.AddSeconds(i++), - }).ToList()); + // Assert + Assert.AreEqual(maxDocs, result.TotalHits); + Assert.AreEqual(query.PageSize, result.Results.Count); + Assert.AreEqual(Enumerable.Range(90, 10).ToArray(), ids); } - private SearchResults SearchForKeyword(string keyword, int searchTypeId = OtherSearchTypeId, bool useWildcard = false, bool allowLeadingWildcard = false) + [Test] + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A() { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; - return this._searchController.SiteSearch(query); - } + // Arrange + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); - private SearchResults SearchForKeywordWithWildCard(string keyword, int searchTypeId = OtherSearchTypeId) - { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = true }; - return this._searchController.SiteSearch(query); - } + // Act + var query = new SearchQuery + { + PageIndex = 2, + PageSize = 5, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, + }; - private SearchResults SearchForKeywordInModule(string keyword, int searchTypeId = ModuleSearchTypeId) - { - var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId } }; - return this._searchController.SiteSearch(query); - } + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - private string StipEllipses(string text) - { - return text.Replace("...", string.Empty).Trim(); + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(5, result.Results.Count); + Assert.AreEqual(new[] { 17, 18, 19, 26, 27 }, ids); } [Test] - public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B() { // Arrange - var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< doc.AuthorUserId).ToArray(); + + // Assert + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(6, result.Results.Count); + Assert.AreEqual(new[] { 18, 19, 26, 27, 28, 29 }, ids); } [Test] - public void SearchController_AddSearchDcoumet_Regex_Does_Not_Sleep_On_Bad_Text_During_Alt_Text_Parsing2() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C() { // Arrange - var document = new SearchDocument { UniqueKey = Guid.NewGuid().ToString(), Title = "< ExecuteWithTimeout( - () => - { - this._internalSearchController.AddSearchDocument(document); - return false; - }, TimeSpan.FromSeconds(1))); - } - - [Test] - public void SearchController_Added_Item_IsRetrieved() - { - // Arrange - var doc = new SearchDocument { UniqueKey = "key01", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - - // Act - this._internalSearchController.AddSearchDocument(doc); - - var result = this.SearchForKeyword("hello"); - - // Assert - Assert.AreEqual(1, result.Results.Count); - Assert.AreEqual(result.Results[0].UniqueKey, doc.UniqueKey); - Assert.AreEqual(result.Results[0].Title, doc.Title); - } - - [Test] - public void SearchController_EnsureIndexIsAppended_When_Index_Is_NotDeleted_InBetween() - { - // Arrange - string[] docs = - { - Line1, - Line2, - }; - - // Act - - // Add first document - var doc1 = new SearchDocument { Title = docs[0], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc1); - - // first luceneQuery - var query1 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search1 = this._searchController.SiteSearch(query1); - - // Assert - Assert.AreEqual(1, search1.Results.Count); - - // Add second document - var doc2 = new SearchDocument { Title = docs[1], UniqueKey = Guid.NewGuid().ToString(), SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow }; - this._internalSearchController.AddSearchDocument(doc2); - this.CreateNewLuceneControllerInstance(); // to force a new reader for the next assertion - - // second luceneQuery - var query2 = new SearchQuery { KeyWords = "fox", SearchTypeIds = new List { OtherSearchTypeId } }; - var search2 = this._searchController.SiteSearch(query2); - - // Assert - Assert.AreEqual(2, search2.Results.Count); - } - - [Test] - public void SearchController_Getsearch_TwoTermsSearch() - { - // Arrange - string[] docs = - { - Line1, - Line2, - Line3, - Line4, - Line5, - }; - - this.AddLinesAsSearchDocs(docs); - - // Act - var search = this.SearchForKeyword("fox jumps"); - - // Assert - Assert.AreEqual(docs.Length, search.Results.Count); - - // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); - } - - [Test] - public void SearchController_GetResult_TwoTermsSearch() - { - // Arrange - string[] docs = - { - Line1, - Line2, - Line3, - Line4, - Line5, - }; - - this.AddLinesAsSearchDocs(docs); - - // Act - var search = this.SearchForKeyword("fox jumps"); - - // Assert - Assert.AreEqual(docs.Length, search.Results.Count); - - // Assert.AreEqual("brown fox jumps over the lazy dog ", search.Results[0].Snippet); - // Assert.AreEqual("quick fox jumps over the black dog ", search.Results[1].Snippet); - } - - [Test] - public void SearchController_GetResult_PortalIdSearch() - { - // Arrange - var added = this.AddStandardSearchDocs(); - - // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId }, PortalIds = new List { PortalId0 } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_GetResult_SearchTypeIdSearch() - { - // Arrange - var added = this.AddStandardSearchDocs(); + const int maxDocs = 30; + const int stype = DocumentSearchTypeId; + this.SetupSecurityTrimmingDocs(maxDocs, stype); // Act - var query = new SearchQuery { SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(added, search.Results.Count); - } - - [Test] - public void SearchController_SearchFindsAnalyzedVeryLongWords() - { - // Arrange - // const string fieldName = Constants.ContentTag; - const string veryLongWord = // 107 characters - "NowIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountryalsoIsTheTimeForAllGoodMenToComeToTheAidOfTheirCountry"; - - var doc = new SearchDocument + var query = new SearchQuery { - Title = veryLongWord, - UniqueKey = Guid.NewGuid().ToString(), - SearchTypeId = ModuleSearchTypeId, - ModifiedTimeUtc = DateTime.UtcNow, - ModuleId = 1, - ModuleDefId = 1, + PageIndex = 2, + PageSize = 8, + KeyWords = "fox", + SearchTypeIds = new[] { stype }, }; - this._internalSearchController.AddSearchDocument(doc); - - // Act - var query = new SearchQuery { KeyWords = veryLongWord, SearchTypeIds = new List { ModuleSearchTypeId } }; - var search = this._searchController.SiteSearch(query); - - // Assert - Assert.AreEqual(1, search.Results.Count); - Assert.AreEqual("" + veryLongWord + "", this.StipEllipses(search.Results[0].Snippet).Trim()); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsNoResultsWhenHavingNoPermission() - { - // Arrange - this.AddStandardSearchDocs(DocumentSearchTypeId); - // Act - var result = this.SearchForKeyword("fox", DocumentSearchTypeId); + var result = this._searchController.SiteSearch(query); + var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); // Assert - // by default AuthorUserId = 0 which have no permission, so this passes - Assert.AreEqual(0, result.Results.Count); + Assert.AreEqual(maxDocs - 18, result.TotalHits); + Assert.AreEqual(4, result.Results.Count); + Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); } [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A() { // Arrange const int maxDocs = 30; @@ -943,25 +629,25 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1A this.SetupSecurityTrimmingDocs(maxDocs, stype); // Act - var query = new SearchQuery + var queryPg3 = new SearchQuery { - PageIndex = 1, + PageIndex = 3, PageSize = 4, KeyWords = "fox", SearchTypeIds = new[] { stype }, }; - var result = this._searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9 }, ids); + Assert.AreEqual(queryPg3.PageSize, result.Results.Count); + Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); } [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B() { // Arrange const int maxDocs = 30; @@ -969,49 +655,25 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1B this.SetupSecurityTrimmingDocs(maxDocs, stype); // Act - var query = new SearchQuery + var queryPg3 = new SearchQuery { - PageIndex = 1, - PageSize = 6, + PageIndex = 3, + PageSize = 5, KeyWords = "fox", SearchTypeIds = new[] { stype }, }; - var result = this._searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - 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), - }); - } + Assert.AreEqual(2, result.Results.Count); + Assert.AreEqual(new[] { 28, 29 }, ids); } [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C() { // Arrange const int maxDocs = 30; @@ -1019,270 +681,36 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1C this.SetupSecurityTrimmingDocs(maxDocs, stype); // Act - var query = new SearchQuery + var queryPg3 = new SearchQuery { - PageIndex = 1, + PageIndex = 3, PageSize = 8, KeyWords = "fox", SearchTypeIds = new[] { stype }, }; - var result = this._searchController.SiteSearch(query); + var result = this._searchController.SiteSearch(queryPg3); var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); // Assert Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19 }, ids); + Assert.AreEqual(0, result.Results.Count); + Assert.AreEqual(new int[] { }, ids); } [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1D() + public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5() { // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; // user should have access to some documnets here + const int maxDocs = 100; + const int stype = DocumentSearchTypeId; this.SetupSecurityTrimmingDocs(maxDocs, stype); // Act - var query = new SearchQuery + var queryPg3 = new SearchQuery { - PageIndex = 1, - PageSize = 100, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(4 * 3, result.TotalHits); - Assert.AreEqual(4 * 3, result.Results.Count); - Assert.AreEqual(new[] { 6, 7, 8, 9, 16, 17, 18, 19, 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1E() - { - // Arrange - const int maxDocs = 30; - const int stype = TabSearchTypeId; // user should have access to all documnets here - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 1, - PageSize = 10, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).Skip(1).ToArray(); - - // Assert - Assert.AreEqual(maxDocs, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(Enumerable.Range(1, 9).ToArray(), ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage1F() - { - // Arrange - const int maxDocs = 100; - const int stype = TabSearchTypeId; // user should have access to all documnets here - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 10, - PageSize = 10, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs, result.TotalHits); - Assert.AreEqual(query.PageSize, result.Results.Count); - Assert.AreEqual(Enumerable.Range(90, 10).ToArray(), ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2A() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 5, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(5, result.Results.Count); - Assert.AreEqual(new[] { 17, 18, 19, 26, 27 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2B() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 6, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(6, result.Results.Count); - Assert.AreEqual(new[] { 18, 19, 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage2C() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var query = new SearchQuery - { - PageIndex = 2, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(query); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(4, result.Results.Count); - Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3A() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 4, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(queryPg3.PageSize, result.Results.Count); - Assert.AreEqual(new[] { 26, 27, 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3B() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 5, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(2, result.Results.Count); - Assert.AreEqual(new[] { 28, 29 }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage3C() - { - // Arrange - const int maxDocs = 30; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 3, - PageSize = 8, - KeyWords = "fox", - SearchTypeIds = new[] { stype }, - }; - - var result = this._searchController.SiteSearch(queryPg3); - var ids = result.Results.Select(doc => doc.AuthorUserId).ToArray(); - - // Assert - Assert.AreEqual(maxDocs - 18, result.TotalHits); - Assert.AreEqual(0, result.Results.Count); - Assert.AreEqual(new int[] { }, ids); - } - - [Test] - public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5() - { - // Arrange - const int maxDocs = 100; - const int stype = DocumentSearchTypeId; - this.SetupSecurityTrimmingDocs(maxDocs, stype); - - // Act - var queryPg3 = new SearchQuery - { - PageIndex = 5, - PageSize = 8, + PageIndex = 5, + PageSize = 8, KeyWords = "fox", SearchTypeIds = new[] { stype }, }; @@ -1294,8 +722,8 @@ public void SearchController_SecurityTrimmedTest_ReturnsExpectedResultsForPage5( Assert.AreEqual(maxDocs - (10 * 6), result.TotalHits); Assert.AreEqual(queryPg3.PageSize, result.Results.Count); Assert.AreEqual(new int[] { 86, 87, 88, 89, 96, 97, 98, 99 }, ids); - } - + } + [Test] public void SearchController_GetResult_Returns_Correct_SuppliedData_When_Optionals_Are_Supplied() { @@ -1396,7 +824,7 @@ public void SearchController_GetResult_Returns_EmptyData_When_Optionals_Are_Not_ public void SearchController_GetsHighlightedDesc() { // Arrange - string[] docs = + string[] docs = { Line1, Line2, @@ -1411,7 +839,7 @@ public void SearchController_GetsHighlightedDesc() // Assert Assert.AreEqual(docs.Length, search.Results.Count); - Assert.IsTrue( + Assert.IsTrue( new[] { "brown fox jumps over the lazy dog", @@ -1461,8 +889,8 @@ public void SearchController_CorrectDocumentCultureIsUsedAtIndexing() // Assert Assert.AreEqual(1, searches.TotalHits); Assert.AreEqual(cultureCode, searches.Results[0].CultureCode); - } - + } + [Test] public void SearchController_GetResult_TimeRangeSearch_Ignores_When_Only_BeginDate_Specified() { @@ -1545,8 +973,8 @@ public void SearchController_GetResult_TimeRangeSearch_Resturns_Scoped_Results_W search = this._searchController.SiteSearch(query); Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(Line2, search.Results[0].Title); - } - + } + [Test] public void SearchController_GetResult_TagSearch_Single_Tag_Returns_Single_Result() { @@ -1574,7 +1002,7 @@ public void SearchController_GetResult_TagSearch_Single_Tag_With_Space_Returns_S // Assert Assert.AreEqual(1, search.Results.Count); } - + [Test] public void SearchController_GetResult_TagSearch_Lowercase_Search_Returns_PropercaseTag_Single_Result() { @@ -1651,8 +1079,8 @@ public void SearchController_GetResult_TagSearch_With_Vowel_Tags_Returns_Data() // Assert Assert.AreEqual(1, search.Results.Count); - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specified_And_CustomSortField_Is_Not() @@ -1664,7 +1092,7 @@ public void SearchController_GetResult_Throws_When_CustomNumericField_Is_Specifi SortField = SortFields.CustomNumericField, }; - this._searchController.SiteSearch(query); + this._searchController.SiteSearch(query); } [Test] @@ -1716,10 +1144,10 @@ 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); @@ -1829,7 +1257,7 @@ 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] @@ -1931,7 +1359,7 @@ public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Descending }; this._searchController.SiteSearch(query); } - + [Test] public void SearchController_GetResult_Sort_By_Unknown_StringField_In_Ascending_Order_Does_Not_Throw() { @@ -1965,7 +1393,7 @@ public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Descendin }; this._searchController.SiteSearch(query); } - + [Test] public void SearchController_GetResult_Sort_By_Unknown_NumericField_In_Ascending_Order_Does_Not_Throw() { @@ -1990,11 +1418,11 @@ 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); @@ -2031,7 +1459,7 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndSubjectKeyword_Retur { this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(CustomBoost); this.CreateNewLuceneControllerInstance(true); - + // Arrange var added = this.AddSearchDocsForCustomBoost(); @@ -2054,7 +1482,7 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndCommentKeyword_Retur { this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(CustomBoost); this.CreateNewLuceneControllerInstance(true); - + // Arrange var added = this.AddSearchDocsForCustomBoost(); @@ -2077,7 +1505,7 @@ public void SearchController_GetResult_Sorty_By_RelevanceAndAuthorKeyword_Return { this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(CustomBoost); this.CreateNewLuceneControllerInstance(true); - + // Arrange var added = this.AddSearchDocsForCustomBoost(); @@ -2114,8 +1542,8 @@ public void SearchController_GetResult_Sorty_By_Relevance_Ascending_Does_Not_Cha // Assert Assert.AreEqual(added, search.Results.Count); Assert.AreEqual(true, search.Results[0].Snippet.Contains("brown") && search.Results[0].Snippet.Contains("dog")); - } - + } + [Test] public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Locales() { @@ -2123,11 +1551,11 @@ 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); @@ -2135,13 +1563,13 @@ public void SearchController_GetResult_By_Locale_Returns_Specific_And_Neutral_Lo Assert.AreEqual(2, search.Results.Count, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); Assert.AreEqual(Line3, search.Results[0].Title); Assert.AreEqual(Line1, search.Results[1].Title); - } - + } + [Test] public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_Content_With_Same_Key() { // Arrange - string[] docs = + string[] docs = { Line1, Line2, @@ -2192,13 +1620,13 @@ public void SearchController_Add_Does_Not_Throw_On_Empty_Title() }; Assert.DoesNotThrow(() => this._internalSearchController.AddSearchDocument(doc)); - } - + } + [Test] public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_When_IsActive_Is_False() { // Arrange - string[] docs = + string[] docs = { Line1, Line2, @@ -2220,15 +1648,15 @@ public void SearchController_EnsureOldDocument_Deleted_Upon_Second_Index_When_Is // Assert - there should not be any record. Assert.AreEqual(0, search.Results.Count); - } - - // Note: these tests needs to pass through the analyzer which is utilized - // in SearchControllerImpl but not LuceneControllerImpl. + } + + // Note: these tests needs to pass through the analyzer which is utilized + // in SearchControllerImpl but not LuceneControllerImpl. [Test] public void SearchController_SearchFindsAccentedAndNonAccentedWords() { // Arrange - string[] lines = + string[] lines = { "zèbre or panthère", "zebre without accent", @@ -2255,7 +1683,7 @@ public void SearchController_SearchFindsAccentedAndNonAccentedWords() public void SearchController_PorterFilterTest() { // Arrange - string[] lines = + string[] lines = { "field1_value", "field2_value", @@ -2279,7 +1707,7 @@ public void SearchController_PorterFilterTest() public void SearchController_SearchFindsStemmedWords() { // Arrange - string[] lines = + string[] lines = { "I ride my bike to work", "All team are riding their bikes", @@ -2297,8 +1725,8 @@ public void SearchController_SearchFindsStemmedWords() Assert.AreEqual("I ride my bike to work", this.StipEllipses(search.Results[0].Snippet)); Assert.AreEqual("m are riding their bikes", this.StipEllipses(search.Results[1].Snippet)); Assert.AreEqual("e boy rides his bike to school", this.StipEllipses(search.Results[2].Snippet)); - } - + } + [Test] public void SearchController_Search_Synonym_Works() { @@ -2316,8 +1744,8 @@ public void SearchController_Search_Synonym_Works() Assert.AreEqual("e red fox jumped over the lazy dark gray dog", snippets[1]); Assert.AreEqual("gold fox jumped over the lazy black dog", snippets[2]); Assert.AreEqual("quick fox jumps over the black dog - Italian", snippets[3]); - } - + } + [Test] public void SearchController_Title_Ranked_Higher_Than_Body() { @@ -2331,7 +1759,7 @@ public void SearchController_Title_Ranked_Higher_Than_Body() this._internalSearchController.AddSearchDocument(doc2); this._internalSearchController.AddSearchDocument(doc3); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("cow"); // Assert @@ -2353,7 +1781,7 @@ public void SearchController_Title_Ranked_Higher_Than_Body_Regardless_Of_Documen this._internalSearchController.AddSearchDocument(doc2); this._internalSearchController.AddSearchDocument(doc3); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("cow"); // Assert @@ -2394,7 +1822,7 @@ public void SearchController_RankingTest_With_Vowel() var doc3 = new SearchDocument { UniqueKey = "key03", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Keywords = new Dictionary() { { KeyWord1Name, "tootsie" } } }; var doc4 = new SearchDocument { UniqueKey = "key04", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Description = "tootsie" }; var doc5 = new SearchDocument { UniqueKey = "key05", Title = "Hello World", SearchTypeId = OtherSearchTypeId, ModifiedTimeUtc = DateTime.UtcNow, Body = "hello tootsie" }; - + // Act this._internalSearchController.AddSearchDocument(doc1); this._internalSearchController.AddSearchDocument(doc2); @@ -2403,7 +1831,7 @@ public void SearchController_RankingTest_With_Vowel() this._internalSearchController.AddSearchDocument(doc5); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("tootsie"); // Assert @@ -2417,8 +1845,8 @@ public void SearchController_RankingTest_With_Vowel() Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); Assert.AreEqual(doc3.UniqueKey, result.Results[2].UniqueKey); Assert.AreEqual(doc4.UniqueKey, result.Results[3].UniqueKey); - } - + } + [Test] public void SearchController_FileNameTest_With_WildCard() { @@ -2471,7 +1899,7 @@ public void SearchController_Full_FileNameTest_With_WildCard() // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - } + } [Test] public void SearchController_Scope_By_FolderName() @@ -2508,40 +1936,8 @@ public void SearchController_Scope_By_FolderName_With_Spaces() Assert.AreEqual(5, result1.TotalHits); Assert.AreEqual(5, result2.TotalHits); 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() { @@ -2558,8 +1954,8 @@ public void SearchController_EmailTest_With_WildCard() // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void SearchController_Add_Use_Of_Module_Search_Type_Requires_ModuleDefinitionId() @@ -2645,8 +2041,8 @@ public void SearchController_Search_For_Unknown_SearchTypeId_Does_Not_Throw_Exce var result = this._searchController.SiteSearch(query); Assert.AreEqual(0, result.TotalHits); // 0 due to security trimming Assert.AreEqual(0, result.Results.Count); - } - + } + [Test] public void SearchController_Search_For_GroupId_Zero_Ignores_GroupId() { @@ -2704,8 +2100,8 @@ public void SearchController_Search_For_GroupId_Returns_Records_With_GroupIds_On var result = this._searchController.SiteSearch(query); Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(RoleId731, result.Results[0].RoleId); - } - + } + [Test] public void SearchController_Search_For_Two_ModuleDefinitions_Returns_Two_Only() { @@ -2756,8 +2152,8 @@ public void SearchController_Search_For_ModuleId_Returns_from_that_module_Only() Assert.AreEqual(2, result.TotalHits); Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); - } - + } + [Test] public void SearchController_Search_For_Module_Search_Type_And_Multiple_ModuleDefIds_Should_Return_From_Those_ModuleDefinitions_Only() { @@ -2845,8 +2241,8 @@ public void SearchController_Search_For_ModuleSearchTypeId_With_Two_ModuleDefini Assert.AreEqual(doc1.UniqueKey, result.Results[0].UniqueKey); Assert.AreEqual(doc2.UniqueKey, result.Results[1].UniqueKey); Assert.AreEqual(doc5.UniqueKey, result.Results[2].UniqueKey); - } - + } + [Test] public void SearchController_GetResult_Works_With_Custom_Numeric_Querirs() { @@ -2883,8 +2279,8 @@ public void SearchController_GetResult_Works_With_CustomKeyword_Querirs() // Assert Assert.AreEqual(1, search.Results.Count); Assert.AreEqual(KeyWord1Value, search.Results[0].Keywords[KeyWord1Name]); - } - + } + [Test] public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_When_Property_Is_False() { @@ -2900,7 +2296,7 @@ public void SearchController_EnableLeadingWildcard_Should_Not_Return_Results_Whe this._internalSearchController.AddSearchDocument(doc2); this._internalSearchController.AddSearchDocument(doc3); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); // Assert @@ -2922,7 +2318,7 @@ public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Pr this._internalSearchController.AddSearchDocument(doc2); this._internalSearchController.AddSearchDocument(doc3); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, true); // Assert @@ -2945,14 +2341,14 @@ public void SearchController_EnableLeadingWildcard_Should_Return_Results_When_Pr this._internalSearchController.AddSearchDocument(doc2); this._internalSearchController.AddSearchDocument(doc3); this._internalSearchController.Commit(); - + var result = this.SearchForKeyword("rld", OtherSearchTypeId, true, false); // Assert Assert.AreEqual(1, result.TotalHits); Assert.AreEqual(doc2.UniqueKey, result.Results[0].UniqueKey); - } - + } + [Test] public void SearchController_Search_StopWords_Works() { @@ -2980,6 +2376,610 @@ public void SearchController_Search_StopWords_Works() // Assert // we won't find "los" in the es-ES document. Assert.AreEqual(0, search.TotalHits, "Found: " + string.Join(Environment.NewLine, search.Results.Select(r => r.Title))); - } + } + + /// + /// 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()); + this._internalSearchController = InternalSearchController.Instance; + this._searchController = new SearchControllerImpl(); + + if (!reCreate) + { + this.DeleteIndexFolder(); + + if (this._luceneController != null) + { + LuceneController.ClearInstance(); + this._luceneController.Dispose(); + } + + this._luceneController = new LuceneControllerImpl(); + LuceneController.SetTestableInstance(this._luceneController); + } + } + + private void SetupHostController() + { + this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns(SearchIndexFolder); + this._mockHostController.Setup(c => c.GetDouble(Constants.SearchReaderRefreshTimeKey, It.IsAny())).Returns(this._readerStaleTimeSpan); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTitleBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTitleBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchTagBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchTagBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchContentBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchKeywordBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchDescriptionBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchDescriptionBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchAuthorBoostSetting, It.IsAny())).Returns(Constants.DefaultSearchAuthorBoost); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMinLengthKey, It.IsAny())).Returns(Constants.DefaultMinLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchMaxLengthKey, It.IsAny())).Returns(Constants.DefaultMaxLen); + this._mockHostController.Setup(c => c.GetInteger(Constants.SearchRetryTimesKey, It.IsAny())).Returns(DefaultSearchRetryTimes); + HostController.RegisterInstance(this._mockHostController.Object); + } + + private void SetupLocaleController() + { + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = -1, Code = string.Empty }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEnCa)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(CultureEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + + this._mockLocaleController.Setup(l => l.GetLocale(It.IsAny())).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnUs)).Returns(new Locale { LanguageId = LanguageIdEnUs, Code = CultureEnUs }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEnFr)).Returns(new Locale { LanguageId = LanguageIdEnFr, Code = CultureEnCa }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdItIt)).Returns(new Locale { LanguageId = LanguageIdItIt, Code = CultureItIt }); + this._mockLocaleController.Setup(l => l.GetLocale(LanguageIdEsEs)).Returns(new Locale { LanguageId = LanguageIdEsEs, Code = CultureEsEs }); + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._mockDataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + DataTableReader searchTypes = null; + this._mockDataProvider.Setup(ds => ds.GetAllSearchTypes()) + .Callback(() => searchTypes = this.GetAllSearchTypes().CreateDataReader()) + .Returns(() => searchTypes); + + this._mockDataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + var table = new DataTable("Portal"); + + var cols = new[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + const int homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, + "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, + "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", + null, homePage.ToString("D"), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private void SetupSearchHelper() + { + this._mockSearchHelper.Setup(c => c.GetSearchMinMaxLength()).Returns(new Tuple(Constants.DefaultMinLen, Constants.DefaultMaxLen)); + this._mockSearchHelper.Setup(c => c.GetSynonyms(It.IsAny(), It.IsAny(), It.IsAny())).Returns(this.GetSynonymsCallBack); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns((string name) => new SearchType { SearchTypeId = 0, SearchTypeName = name }); + this._mockSearchHelper.Setup(x => x.GetSearchTypeByName(It.IsAny())).Returns(this.GetSearchTypeByNameCallback); + this._mockSearchHelper.Setup(x => x.GetSearchTypes()).Returns(this.GetSearchTypes()); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(It.IsAny(), It.IsAny())).Returns(new SearchStopWords()); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEsEs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEsEs, + StopWords = "los,de,el", + }); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnUs)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEnUs, + StopWords = "the,over", + }); + this._mockSearchHelper.Setup(x => x.GetSearchStopWords(0, CultureEnCa)).Returns( + new SearchStopWords + { + PortalId = 0, + CultureCode = CultureEnCa, + StopWords = "the,over", + }); + + this._mockSearchHelper.Setup(x => x.RephraseSearchText(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new SearchHelperImpl().RephraseSearchText); + this._mockSearchHelper.Setup(x => x.StripTagsNoAttributes(It.IsAny(), It.IsAny())).Returns((string html, bool retainSpace) => html); + SearchHelper.SetTestableInstance(this._mockSearchHelper.Object); + } + + private SearchType GetSearchTypeByNameCallback(string searchTypeName) + { + var searchType = new SearchType { SearchTypeName = searchTypeName, SearchTypeId = 0 }; + switch (searchTypeName) + { + case ModuleSearchTypeName: + searchType.SearchTypeId = ModuleSearchTypeId; + break; + case TabSearchTypeName: + searchType.SearchTypeId = TabSearchTypeId; + break; + case OtherSearchTypeName: + searchType.SearchTypeId = OtherSearchTypeId; + break; + case DocumentSearchTypeName: + searchType.SearchTypeId = DocumentSearchTypeId; + break; + case UrlSearchTypeName: + searchType.SearchTypeId = UrlSearchTypeId; + break; + } + + return searchType; + } + + private IList GetSynonymsCallBack(int portalId, string cultureCode, string term) + { + var synonyms = new List(); + if (term == "fox") + { + synonyms.Add("wolf"); + } + + return synonyms; + } + + private UserInfo GetUserByIdCallback(int portalId, int userId) + { + if (portalId == PortalId12 && userId == StandardAuthorId) + { + return new UserInfo { UserID = userId, DisplayName = StandardAuthorDisplayName }; + } + + return null; + } + + private DataTable GetAllSearchTypes() + { + var dtSearchTypes = new DataTable("SearchTypes"); + var pkId = dtSearchTypes.Columns.Add("SearchTypeId", typeof(int)); + dtSearchTypes.Columns.Add("SearchTypeName", typeof(string)); + dtSearchTypes.Columns.Add("SearchResultClass", typeof(string)); + dtSearchTypes.PrimaryKey = new[] { pkId }; + + // Create default Crawler + dtSearchTypes.Rows.Add(ModuleSearchTypeId, ModuleSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(TabSearchTypeId, TabSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(OtherSearchTypeId, OtherSearchTypeName, FakeResultControllerClass); + dtSearchTypes.Rows.Add(DocumentSearchTypeId, DocumentSearchTypeName, NoPermissionFakeResultControllerClass); + dtSearchTypes.Rows.Add(UrlSearchTypeId, UrlSearchTypeName, FakeResultControllerClass); + + return dtSearchTypes; + } + + private IEnumerable GetSearchTypes() + { + var searchTypes = new List + { + new SearchType { SearchTypeId = ModuleSearchTypeId, SearchTypeName = ModuleSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = TabSearchTypeId, SearchTypeName = TabSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = OtherSearchTypeId, SearchTypeName = OtherSearchTypeName, SearchResultClass = FakeResultControllerClass }, + new SearchType { SearchTypeId = DocumentSearchTypeId, SearchTypeName = DocumentSearchTypeName, SearchResultClass = NoPermissionFakeResultControllerClass }, + new SearchType { SearchTypeId = UrlSearchTypeId, SearchTypeName = UrlSearchTypeName, SearchResultClass = FakeResultControllerClass }, + }; + + return searchTypes; + } + + private void DeleteIndexFolder() + { + try + { + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + } + + /// + /// Returns few SearchDocs. + /// + private IEnumerable GetStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + { + var searchDocs = new List + { + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag0, Tag1, TagOldest, Tag0WithSpace }, Title = Line1 }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag1, Tag2, TagNeutral }, Title = Line2, CultureCode = CultureEnUs }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line3, CultureCode = CultureItIt }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag3, Tag4, TagLatest }, Title = Line4, CultureCode = CultureEnCa }, + new SearchDocument { PortalId = PortalId0, Tags = new List { Tag2, Tag3, TagIt }, Title = Line5, CultureCode = CultureEsEs }, + }; + + var now = DateTime.UtcNow.AddYears(-searchDocs.Count); + var i = 0; + + foreach (var searchDocument in searchDocs) + { + searchDocument.SearchTypeId = searchTypeId; + searchDocument.UniqueKey = Guid.NewGuid().ToString(); + searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; + searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; + searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest + } + + return searchDocs; + } + + private IEnumerable GetSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) + { + var searchDocs = new List + { + new SearchDocument { PortalId = PortalId0, Title = Line1, Keywords = { { "title", "Hello" } }, Body = "Hello1 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line2, Keywords = { { "subject", "Hello" } }, Body = "Hello2 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line3, Keywords = { { "comments", "Hello" } }, Body = "Hello3 World" }, + new SearchDocument { PortalId = PortalId0, Title = Line4, Keywords = { { "authorname", "Hello" } }, Body = "Hello4 World" }, + }; + + var now = DateTime.UtcNow.AddYears(-searchDocs.Count); + var i = 0; + + foreach (var searchDocument in searchDocs) + { + searchDocument.SearchTypeId = searchTypeId; + searchDocument.UniqueKey = Guid.NewGuid().ToString(); + searchDocument.ModuleId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleId : -1; + searchDocument.ModuleDefId = (searchTypeId == ModuleSearchTypeId) ? HtmlModuleDefId : -1; + searchDocument.ModifiedTimeUtc = now.AddYears(++i); // last added is the newest + } + + return searchDocs; + } + + /// + /// Adds standarad SearchDocs in Lucene Index. + /// + /// Number of dcuments added. + private int AddStandardSearchDocs(int searchTypeId = ModuleSearchTypeId) + { + var docs = this.GetStandardSearchDocs(searchTypeId).ToArray(); + this._internalSearchController.AddSearchDocuments(docs); + return docs.Length; + } + + private int AddSearchDocsForCustomBoost(int searchTypeId = ModuleSearchTypeId) + { + var docs = this.GetSearchDocsForCustomBoost(searchTypeId).ToArray(); + this._internalSearchController.AddSearchDocuments(docs); + return docs.Length; + } + + private int AddDocumentsWithNumericKeys(int searchTypeId = OtherSearchTypeId) + { + var doc1 = new SearchDocument + { + Title = "Title", + UniqueKey = "key1", + Body = "hello", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue50 } }, + }; + var doc2 = new SearchDocument + { + Title = "Title", + UniqueKey = "key2", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue100 } }, + }; + var doc3 = new SearchDocument + { + Title = "Title", + UniqueKey = "key3", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue200 } }, + }; + var doc4 = new SearchDocument + { + Title = "Title", + UniqueKey = "key4", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + NumericKeys = new Dictionary() { { NumericKey1, NumericValue500 } }, + }; + var doc5 = new SearchDocument + { + Title = "Title", + UniqueKey = "key5", + 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; + } + + private int AddDocumentsWithKeywords(int searchTypeId = OtherSearchTypeId) + { + var doc1 = new SearchDocument + { + Title = "Title", + UniqueKey = "key1", + Body = "hello", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord1Value } }, + }; + var doc2 = new SearchDocument + { + Title = "Title", + UniqueKey = "key2", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord2Value } }, + }; + var doc3 = new SearchDocument + { + Title = "Title", + UniqueKey = "key3", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord3Value } }, + }; + var doc4 = new SearchDocument + { + Title = "Title", + UniqueKey = "key4", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord4Value } }, + }; + var doc5 = new SearchDocument + { + Title = "Title", + UniqueKey = "key5", + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + Keywords = new Dictionary() { { KeyWord1Name, KeyWord5Value } }, + }; + + var docs = new List() { doc1, doc2, doc3, doc4, doc5 }; + + this._internalSearchController.AddSearchDocuments(docs); + + return docs.Count; + } + + 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, + })) + { + this._internalSearchController.AddSearchDocument(doc); + count++; + } + + return count; + } + + private int AddDocumentsWithKeywords(IEnumerable keywords, string title, int searchTypeId = OtherSearchTypeId) + { + var count = 0; + foreach (var doc in keywords.Select(keyword => new SearchDocument + { + Title = title, + UniqueKey = Guid.NewGuid().ToString(), + Keywords = new Dictionary() { { KeyWord1Name, keyword } }, + SearchTypeId = OtherSearchTypeId, + ModifiedTimeUtc = DateTime.UtcNow, + PortalId = PortalId12, + })) + { + this._internalSearchController.AddSearchDocument(doc); + count++; + } + + return count; + } + + private void AddLinesAsSearchDocs(IList lines, int searchTypeId = OtherSearchTypeId) + { + var now = DateTime.UtcNow - TimeSpan.FromSeconds(lines.Count()); + var i = 0; + + this._internalSearchController.AddSearchDocuments( + lines.Select(line => + new SearchDocument + { + Title = line, + UniqueKey = Guid.NewGuid().ToString(), + SearchTypeId = searchTypeId, + ModifiedTimeUtc = now.AddSeconds(i++), + }).ToList()); + } + + private SearchResults SearchForKeyword(string keyword, int searchTypeId = OtherSearchTypeId, bool useWildcard = false, bool allowLeadingWildcard = false) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = useWildcard, AllowLeadingWildcard = allowLeadingWildcard }; + return this._searchController.SiteSearch(query); + } + + private SearchResults SearchForKeywordWithWildCard(string keyword, int searchTypeId = OtherSearchTypeId) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId }, WildCardSearch = true }; + return this._searchController.SiteSearch(query); + } + + private SearchResults SearchForKeywordInModule(string keyword, int searchTypeId = ModuleSearchTypeId) + { + var query = new SearchQuery { KeyWords = keyword, SearchTypeIds = new[] { searchTypeId } }; + return this._searchController.SiteSearch(query); + } + + private string StipEllipses(string text) + { + return text.Replace("...", string.Empty).Trim(); + } + + /// + /// 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), + }); + } + } + + 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(); + } } } 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 35e21b0e764..8bc61cc7896 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchHelperTests.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Search ///
    [TestFixture] public class SearchHelperTests - { + { private const int OtherSearchTypeId = 2; private const string TermDNN = "DNN"; private const string TermDotNetNuke = "DotnetNuke"; @@ -32,11 +32,11 @@ public class SearchHelperTests private const string TermLeap = "Leap"; private const string TermHop = "Hop"; private const int PortalId0 = 0; - private const string CultureEnUs = "en-US"; + private const string CultureEnUs = "en-US"; private Mock _dataProvider; private Mock _cachingProvider; - private SearchHelperImpl _searchHelper; - + private SearchHelperImpl _searchHelper; + [SetUp] public void SetUp() { @@ -46,8 +46,8 @@ public void SetUp() this.SetupDataProvider(); this._searchHelper = new SearchHelperImpl(); DataCache.ClearCache(); - } - + } + [Test] public void SearchHelper_GetSynonyms_Two_Terms_Returns_Correct_Results() { @@ -73,84 +73,8 @@ public void SearchHelper_GetSynonyms_Three_Terms_Returns_Correct_Results() 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 - this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); - - this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); - - this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); - - var dataTable = new DataTable("SynonymsGroups"); - var pkId = dataTable.Columns.Add("SynonymsGroupID", typeof(int)); - dataTable.Columns.Add("SynonymsTags", typeof(string)); - 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.Columns.Add("PortalID", typeof(int)); - - dataTable.PrimaryKey = new[] { pkId }; - - // Create some test data - var now = DateTime.Now; - dataTable.Rows.Add(1, string.Join(",", new[] { TermDNN, TermDotNetNuke }), 1, now, 1, now, 0); - dataTable.Rows.Add(2, string.Join(",", new[] { TermLaptop, TermNotebook }), 1, now, 1, now, 0); - dataTable.Rows.Add(3, string.Join(",", new[] { TermJump, TermLeap, TermHop }), 1, now, 1, now, 0); - - this._dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); } - private IDataReader GetPortalSettingsCallBack(int portalId, string culture) - { - var table = new DataTable("PortalSettings"); - - var cols = new string[] - { - "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - table.Rows.Add("SearchAdminInitialization", "true", "-1", DateTime.Now, "-1", DateTime.Now, CultureEnUs); - - return table.CreateDataReader(); - } - - private IDataReader GetPortalsCallBack(string culture) - { - return this.GetPortalCallBack(PortalId0, CultureEnUs); - } - - private IDataReader GetPortalCallBack(int portalId, string culture) - { - DataTable table = new DataTable("Portal"); - - var cols = new string[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - var homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - [Test] public void SearchHelper_Rephrase_NoWildCardButExact_1() { @@ -376,7 +300,7 @@ public void SearchHelper_Rephrase_WildCardWithTilde_4() } [Test] - + // Arrange [TestCase("Cäu", "(Cau OR Cau*)")] [TestCase("Cäutätörül", "(Cautatorul OR Cautatorul*)")] @@ -388,6 +312,82 @@ public void SearchHelper_Rephrase_AccentedCharsReplaced_Replaced(string inPhrase // Assert Assert.AreEqual(expected, analyzed); - } + } + + private void SetupDataProvider() + { + // Standard DataProvider Path for Logging + this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); + + this._dataProvider.Setup(d => d.GetPortals(It.IsAny())).Returns(this.GetPortalsCallBack); + + this._dataProvider.Setup(d => d.GetPortalSettings(It.IsAny(), It.IsAny())).Returns(this.GetPortalSettingsCallBack); + + var dataTable = new DataTable("SynonymsGroups"); + var pkId = dataTable.Columns.Add("SynonymsGroupID", typeof(int)); + dataTable.Columns.Add("SynonymsTags", typeof(string)); + 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.Columns.Add("PortalID", typeof(int)); + + dataTable.PrimaryKey = new[] { pkId }; + + // Create some test data + var now = DateTime.Now; + dataTable.Rows.Add(1, string.Join(",", new[] { TermDNN, TermDotNetNuke }), 1, now, 1, now, 0); + dataTable.Rows.Add(2, string.Join(",", new[] { TermLaptop, TermNotebook }), 1, now, 1, now, 0); + dataTable.Rows.Add(3, string.Join(",", new[] { TermJump, TermLeap, TermHop }), 1, now, 1, now, 0); + + this._dataProvider.Setup(x => x.GetAllSynonymsGroups(0, It.IsAny())).Returns(dataTable.CreateDataReader()); + } + + private IDataReader GetPortalSettingsCallBack(int portalId, string culture) + { + var table = new DataTable("PortalSettings"); + + var cols = new string[] + { + "SettingName", "SettingValue", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + table.Rows.Add("SearchAdminInitialization", "true", "-1", DateTime.Now, "-1", DateTime.Now, CultureEnUs); + + return table.CreateDataReader(); + } + + private IDataReader GetPortalsCallBack(string culture) + { + return this.GetPortalCallBack(PortalId0, CultureEnUs); + } + + private IDataReader GetPortalCallBack(int portalId, string culture) + { + DataTable table = new DataTable("Portal"); + + var cols = new string[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + var homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs index ae872d4a358..65815b522a3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Search/SearchQueryStringParserTests.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Search [TestFixture] public class SearchQueryStringParserTests - { + { public void GetLastModifiedDate_ShouldReturnOneDayAgoDate_WhenKeywordsHaveAfterDay() { // Arrange @@ -124,8 +124,8 @@ public void GetLastModifiedDate_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_W // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } - + } + [Test] public void GetSearchTypeList_ShouldReturnSearchTypeList_WhenKeywordsHaveTypeParameter() { @@ -183,8 +183,8 @@ public void GetSearchTypeList_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_Whe // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } - + } + [Test] public void GetTags_ShouldReturnTagsList_WhenKeywordsHaveTags() { @@ -242,6 +242,6 @@ public void GetTags_ShouldSetOutputKeywordsEqualsToTrimmedKeywords_WhenKeywordsD // Assert Assert.AreEqual(expectedOutputKeywords, outputKeywords); - } + } } } 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 4e314d843a5..0b764808687 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Controllers/Social/RelationshipControllerTests.cs @@ -29,7 +29,7 @@ namespace DotNetNuke.Tests.Core.Controllers.Social ///
    [TestFixture] public class RelationshipControllerTests - { + { private Mock mockCachingProvider; private Mock _portalController; private Mock _portalGroupController; @@ -37,8 +37,8 @@ public class RelationshipControllerTests private DataTable dtRelationshipTypes; private DataTable dtRelationships; private DataTable dtUserRelationships; - private DataTable dtUserRelationshipPreferences; - + private DataTable dtUserRelationshipPreferences; + [SetUp] public void SetUp() { @@ -74,8 +74,8 @@ public void TearDown() ComponentFactory.Container = null; PortalController.ClearInstance(); UserController.ClearInstance(); - } - + } + [Test] public void RelationshipController_Constructor_Throws_On_Null_DataService() { @@ -94,8 +94,8 @@ public void RelationshipController_Constructor_Throws_On_Null_EventLogController // Act, Assert Assert.Throws(() => new RelationshipControllerImpl(mockDataService.Object, null)); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteRelationshipType_Throws_On_Null_RelationshipType() @@ -113,9 +113,9 @@ 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 @@ -133,12 +133,12 @@ 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,9 +153,9 @@ 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 @@ -240,9 +240,9 @@ 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 @@ -261,10 +261,10 @@ 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 @@ -281,9 +281,9 @@ 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 @@ -291,8 +291,8 @@ public void RelationshipController_SaveRelationshipType_Calls_DataCache_RemoveCa // Assert this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteRelationship_Throws_On_Null_Relationship() @@ -310,9 +310,9 @@ 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 @@ -331,10 +331,10 @@ 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 @@ -352,11 +352,11 @@ 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 @@ -415,7 +415,7 @@ public void RelationshipController_GetRelationshipsByUserID_Returns_List_Of_Rela Constants.USER_ValidId, RelationshipStatus.None); } - + mockDataService.Setup(md => md.GetRelationshipsByUserId(Constants.USER_ValidId)).Returns(this.dtRelationships.CreateDataReader()); var relationshipController = this.CreateRelationshipController(mockDataService); @@ -458,7 +458,7 @@ public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Re Constants.USER_Null, RelationshipStatus.None); } - + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); var relationshipController = this.CreateRelationshipController(mockDataService); @@ -487,7 +487,7 @@ public void RelationshipController_GetRelationshipsByPortalID_Returns_List_Of_Re Constants.USER_Null, RelationshipStatus.None); } - + mockDataService.Setup(md => md.GetRelationshipsByPortalId(Constants.PORTAL_Zero)).Returns(this.dtRelationships.CreateDataReader()); var relationshipController = this.CreateRelationshipController(mockDataService); @@ -542,9 +542,9 @@ 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 @@ -563,10 +563,10 @@ 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 @@ -593,8 +593,8 @@ public void RelationshipController_SaveRelationship_Calls_DataCache_RemoveCache( // Assert this.mockCachingProvider.Verify(e => e.Remove(cacheKey)); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteUserRelationship_Throws_On_Null_UserRelationship() @@ -612,9 +612,9 @@ 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 @@ -633,13 +633,13 @@ 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); @@ -694,7 +694,7 @@ public void RelationshipController_GetUserRelationships_Returns_List_Of_UserRela this.dtUserRelationships.Rows.Add(i, Constants.USER_ValidId, Constants.USER_TenId, Constants.SOCIAL_FriendRelationshipID, RelationshipStatus.None); } - + mockDataService.Setup(md => md.GetUserRelationships(Constants.USER_ValidId)).Returns(this.dtUserRelationships.CreateDataReader()); var relationshipController = this.CreateRelationshipController(mockDataService); @@ -725,7 +725,7 @@ public void RelationshipController_GetUserRelationships_Returns_EmptyList_Of_Use Assert.IsInstanceOf>(userRelationships); Assert.AreEqual(0, userRelationships.Count); } - + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_SaveUserRelationship_Throws_On_Null_UserRelationship() @@ -743,9 +743,9 @@ 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 @@ -767,21 +767,21 @@ 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); // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationship_Updated, Constants.SOCIAL_UserRelationshipIDUser10User11, Constants.USER_ElevenId, Constants.USER_TenId); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RelationshipController_DeleteUserRelationshipPreference_Throws_On_Null_UserRelationshipPreference() @@ -799,9 +799,9 @@ 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 @@ -820,11 +820,11 @@ 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 @@ -884,11 +884,11 @@ 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 @@ -910,11 +910,11 @@ 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 @@ -923,8 +923,8 @@ public void RelationshipController_SaveUserRelationshipPreference_Calls_EventLog // Assert var logContent = string.Format(Constants.LOCALIZATION_UserRelationshipPreference_Updated, Constants.SOCIAL_PrefereceIDForUser11, Constants.USER_ElevenId, Constants.SOCIAL_FriendRelationshipID); mockEventLogController.Verify(e => e.AddLog("Message", logContent, EventLogController.EventLogType.ADMIN_ALERT)); - } - + } + [Test] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void RelationshipController_InitiateUserRelationship_Throws_On_Negative_RelationshipID() @@ -1043,8 +1043,8 @@ public void RelationshipController_InitiateUserRelationship_Returns_Status_Initi // Assert Assert.AreEqual(userRelationship.Status, RelationshipStatus.Pending); - } - + } + [Test] [ExpectedException(typeof(UserRelationshipDoesNotExistException))] public void RelationshipController_RemoveUserRelationship_Throws_On_NonExistent_Relationship() @@ -1081,8 +1081,8 @@ public void RelationshipController_AcceptRelationship_Throws_On_NonExistent_Rela // Act, Assert relationshipController.AcceptUserRelationship(Constants.SOCIAL_UserRelationshipIDUser10User11); - } - + } + [Test] public void RelationshipController_AcceptUserRelationship_Calls_DataService_On_Valid_RelationshipID() { @@ -1127,7 +1127,7 @@ 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) { @@ -1146,8 +1146,8 @@ private static PortalGroupInfo CreatePortalGroupInfo(int portalGroupId, int mast }; return mockPortalGroupInfo; - } - + } + private Mock CreateMockDataServiceWithRelationshipTypes() { var mockDataService = new Mock(); 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 6ea0a60a62d..4f9fdc488f8 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 @@ -25,7 +25,7 @@ public abstract class BaseSettingsTests 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; 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 7bebab06a2a..fba4752988a 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 @@ -40,37 +40,6 @@ public void SaveSettings_CallsUpdateModuleSetting_WithRightParameters_zh_CN(stri { this.SaveSettings_CallsUpdateModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - - public class ModulesSettings - { - [ModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [ModuleSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [ModuleSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [ModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class ModulesSettingsRepository : SettingsRepository - { - } [Test] [TestCaseSource(nameof(SettingsCases))] @@ -146,42 +115,6 @@ public void GetSettings_CallsGetCachedObject() this.MockRepository.VerifyAll(); } - 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}")); - - var settingsRepository = new ModulesSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("ar-JO")] @@ -281,5 +214,71 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVal Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); this.MockRepository.VerifyAll(); } + + 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}")); + + var settingsRepository = new ModulesSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + + public class ModulesSettings + { + [ModuleSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [ModuleSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [ModuleSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [ModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class ModulesSettingsRepository : SettingsRepository + {} } } 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 37a8486b546..51e46f6689d 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 @@ -22,7 +22,7 @@ public class NullableSettingsTests : BaseSettingsTests 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")] @@ -46,25 +46,6 @@ 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))] @@ -141,38 +122,6 @@ public void GetSettings_CallsGetCachedObject() this.MockRepository.VerifyAll(); } - 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)); - - var settingsRepository = new MyNullableSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - [Test] [TestCaseSource(nameof(NullableCases))] [SetCulture("ar-JO")] @@ -237,6 +186,38 @@ public void GetSettings_GetsValues_FromCorrectSettings_tr_TR(string stringValue, this.GetSettings_GetsValues_FromCorrectSettings(stringValue, integerValue, datetimeValue, timeSpanValue); } + 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)); + + var settingsRepository = new MyNullableSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + private void GetSettings_GetsValues_FromCorrectSettings(string stringValue, int? integerValue, DateTime? datetimeValue, TimeSpan? timeSpanValue) { // Arrange @@ -262,5 +243,23 @@ 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 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 + {} } } 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 997a80aeb93..725631066b8 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 @@ -40,37 +40,6 @@ public void SaveSettings_CallsUpdatePortalSetting_WithRightParameters_zh_CN(stri { this.SaveSettings_CallsUpdatePortalSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - - public class MyPortalSettings - { - [PortalSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [PortalSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [PortalSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [PortalSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [PortalSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [PortalSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class MyPortalSettingsRepository : SettingsRepository - { - } [Test] [TestCaseSource(nameof(SettingsCases))] @@ -145,41 +114,6 @@ public void GetSettings_CallsGetCachedObject() this.MockRepository.VerifyAll(); } - 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)); - - var settingsRepository = new MyPortalSettingsRepository(); - - // Act - settingsRepository.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("ar-JO")] @@ -244,6 +178,41 @@ public void GetSettings_GetsValuesFrom_PortalSettings_tr_TR(string stringValue, this.GetSettings_GetsValuesFrom_PortalSettings(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) + { + // 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 settingsRepository = new MyPortalSettingsRepository(); + + // Act + settingsRepository.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { // Arrange @@ -278,5 +247,35 @@ private void GetSettings_GetsValuesFrom_PortalSettings(string stringValue, int i Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); this.MockRepository.VerifyAll(); } + + public class MyPortalSettings + { + [PortalSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [PortalSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [PortalSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [PortalSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [PortalSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [PortalSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class MyPortalSettingsRepository : SettingsRepository + {} } } 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 37a4d45709d..5d7ed767a43 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 @@ -40,37 +40,6 @@ public void SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters_zh_CN(s { this.SaveSettings_CallsUpdateTabModuleSetting_WithRightParameters(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } - - public class MyTabModuleSettings - { - [TabModuleSetting(Prefix = SettingNamePrefix)] - public string StringProperty { get; set; } = string.Empty; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public int IntegerProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public double DoubleProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public bool BooleanProperty { get; set; } - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public DateTime DateTimeProperty { get; set; } = DateTime.Now; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; - - [TabModuleSetting(Prefix = SettingNamePrefix)] - public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; - - [TabModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] - public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); - } - - public class MyTabModuleSettingsRepository : SettingsRepository - { - } [Test] [TestCaseSource(nameof(SettingsCases))] @@ -147,41 +116,6 @@ public void GetSettings_CallsGetCachedObject() this.MockRepository.VerifyAll(); } - 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.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.SaveSettings(moduleInfo, settings); - - // Assert - this.MockRepository.VerifyAll(); - } - [Test] [TestCaseSource(nameof(SettingsCases))] [SetCulture("ar-JO")] @@ -246,6 +180,41 @@ public void GetSettings_GetsValuesFrom_ModuleSettingsCollection_tr_TR(string str this.GetSettings_GetsValuesFrom_ModuleSettingsCollection(stringValue, integerValue, doubleValue, booleanValue, datetimeValue, timeSpanValue, enumValue, complexValue); } + 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.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.SaveSettings(moduleInfo, settings); + + // Assert + this.MockRepository.VerifyAll(); + } + private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringValue, int integerValue, double doubleValue, bool booleanValue, DateTime datetimeValue, TimeSpan timeSpanValue, TestingEnum enumValue, ComplexType complexValue) { // Arrange @@ -280,5 +249,35 @@ private void GetSettings_GetsValuesFrom_ModuleSettingsCollection(string stringVa Assert.AreEqual(complexValue, settings.ComplexProperty, "The retrieved complex property value is not equal to the stored one"); this.MockRepository.VerifyAll(); } + + public class MyTabModuleSettings + { + [TabModuleSetting(Prefix = SettingNamePrefix)] + public string StringProperty { get; set; } = string.Empty; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public int IntegerProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public double DoubleProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public bool BooleanProperty { get; set; } + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public DateTime DateTimeProperty { get; set; } = DateTime.Now; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public TimeSpan TimeSpanProperty { get; set; } = TimeSpan.Zero; + + [TabModuleSetting(Prefix = SettingNamePrefix)] + public TestingEnum EnumProperty { get; set; } = TestingEnum.Value1; + + [TabModuleSetting(Prefix = SettingNamePrefix, Serializer = "DotNetNuke.Tests.Core.Entities.Modules.Settings.ComplexTypeSerializer,DotNetNuke.Tests.Core")] + public ComplexType ComplexProperty { get; set; } = new ComplexType(20, 25); + } + + public class MyTabModuleSettingsRepository : SettingsRepository + {} } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs index 9c53a1f0c7e..d2ce2d91fe9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsControllerTests.cs @@ -92,7 +92,7 @@ public void LoadPortalSettings_Loads_Default_Value(Dictionary te // Act controller.LoadPortalSettings(settings); - + // Assert var property = settings.GetType().GetProperty(propertyName); var actualValue = property.GetValue(settings, null); 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 e0893017f4e..db90573b46c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Entities/Portals/PortalSettingsTests.cs @@ -154,16 +154,16 @@ 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 + { + // 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)); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs index 93d0130320f..2b183e8f691 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/FileSystemUtilsTests.cs @@ -34,7 +34,7 @@ public void SetUp() field.SetValue(null, rootPath); } - + [TestCase("/")] [TestCase("//")] [TestCase("///")] @@ -84,7 +84,7 @@ public void AddToZip_Should_Able_To_Add_Multiple_Files() { Directory.CreateDirectory(destPath); } - + try { using (var stream = File.OpenRead(zipFilePath)) @@ -175,7 +175,7 @@ private void DeleteZippedFiles() } } } - + private void DeleteUnzippedFolder(string zippedFolder) { try 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 04e935e69b3..25e5ae97d69 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FileInfoBuilder.cs @@ -65,16 +65,16 @@ 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/Builders/FolderInfoBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs index c2ce4adbd90..791594f837c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Builders/FolderInfoBuilder.cs @@ -28,7 +28,7 @@ internal FolderInfoBuilder() this.folderId = Constants.FOLDER_ValidFolderId; this.physicalPath = string.Empty; } - + internal FolderInfoBuilder WithPhysicalPath(string phisicalPath) { this.physicalPath = phisicalPath; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs index 1992aad09bc..4842a4b5fb6 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Caching/DataCacheTests.cs @@ -22,8 +22,8 @@ namespace DotNetNuke.Tests.Core.Providers.Caching [TestFixture] public class DataCacheTests { - private Mock mockCache; - + private Mock mockCache; + [SetUp] public void SetUp() { @@ -31,8 +31,8 @@ public void SetUp() ComponentFactory.Container = new SimpleContainer(); this.mockCache = MockComponentProvider.CreateNew(); - } - + } + [Test] public void DataCache_GetCache_Should_Return_On_Correct_CacheKey() { @@ -66,8 +66,8 @@ public void DataCache_GetCache_Should_Return_Null_On_Incorrect_CacheKey() public void DataCache_GetCache_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.GetCache(key)); - } - + } + [Test] public void DataCache_GetCacheOfT_Should_Return_On_Correct_CacheKey() { @@ -101,8 +101,8 @@ public void DataCache_GetCacheOfT_Should_Return_Null_On_Incorrect_CacheKey() public void DataCache_GetCacheOfT_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.GetCache(key)); - } - + } + [Test] public void DataCache_RemoveCache_Should_Succeed_On_Valid_CacheKey() { @@ -121,8 +121,8 @@ public void DataCache_RemoveCache_Should_Succeed_On_Valid_CacheKey() public void DataCache_RemoveCache_Should_Throw_On_NullOrEmpty_CacheKey(string key) { Assert.Throws(() => DataCache.RemoveCache(key)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -143,7 +143,7 @@ public void DataCache_SetCache_Should_Succeed_On_Valid_CacheKey_And_Any_Value() DNNCacheDependency dep = null; this.mockCache.Verify( cache => - cache.Insert( + cache.Insert( this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, @@ -151,8 +151,8 @@ public void DataCache_SetCache_Should_Succeed_On_Valid_CacheKey_And_Any_Value() Cache.NoSlidingExpiration, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -174,7 +174,7 @@ public void DataCache_SetCache_With_Dependency_Should_Succeed_On_Valid_CacheKey_ // Assert this.mockCache.Verify( cache => - cache.Insert( + cache.Insert( this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, @@ -182,8 +182,8 @@ public void DataCache_SetCache_With_Dependency_Should_Succeed_On_Valid_CacheKey_ Cache.NoSlidingExpiration, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -206,7 +206,7 @@ public void DataCache_SetCache_With_AbsoluteExpiration_Should_Succeed_On_Valid_C DNNCacheDependency dep = null; this.mockCache.Verify( cache => - cache.Insert( + cache.Insert( this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, @@ -214,8 +214,8 @@ public void DataCache_SetCache_With_AbsoluteExpiration_Should_Succeed_On_Valid_C Cache.NoSlidingExpiration, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -239,7 +239,7 @@ public void DataCache_SetCache_With_SlidingExpiration_Should_Succeed_On_Valid_Ca DNNCacheDependency dep = null; this.mockCache.Verify( cache => - cache.Insert( + cache.Insert( this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, @@ -247,8 +247,8 @@ public void DataCache_SetCache_With_SlidingExpiration_Should_Succeed_On_Valid_Ca slidingExpiry, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -275,8 +275,8 @@ public void DataCache_SetCache_With_CacheDependency_AbsoluteExpiration_SlidingEx this.mockCache.Verify( cache => cache.Insert(this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, DataCache.ItemRemovedCallback)); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -320,8 +320,8 @@ public void DataCache_SetCache_With_Callback_Should_Succeed_On_Valid_CacheKey_An // Assert this.mockCache.Verify( cache => cache.Insert(this.GetDnnCacheKey(Constants.CACHEING_ValidKey), Constants.CACHEING_ValidValue, dep, absExpiry, slidingExpiry, CacheItemPriority.Normal, this.ItemRemovedCallback)); - } - + } + private DNNCacheDependency CreateTestDependency() { return new DNNCacheDependency("C:\\testdependency.txt"); @@ -335,6 +335,6 @@ private string GetDnnCacheKey(string cacheKey) private void ItemRemovedCallback(string key, object value, CacheItemRemovedReason removedReason) { // do nothing - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs index 343967a2053..a912ec0380a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DatabaseFolderProviderTests.cs @@ -23,14 +23,14 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class DatabaseFolderProviderTests - { + { private DatabaseFolderProvider _dfp; private Mock _mockData; private Mock _folderInfo; private Mock _fileInfo; private Mock _folderManager; - private Mock _fileManager; - + private Mock _fileManager; + [SetUp] public void Setup() { @@ -49,8 +49,8 @@ public void Setup() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() @@ -69,8 +69,8 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) var stream = new Mock(); this._dfp.AddFile(this._folderInfo.Object, fileName, stream.Object); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() @@ -86,8 +86,8 @@ public void DeleteFile_Calls_DataProvider_ClearFileContent() this._dfp.DeleteFile(this._fileInfo.Object); this._mockData.Verify(md => md.ClearFileContent(Constants.FOLDER_ValidFileId), Times.Once()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() @@ -127,8 +127,8 @@ public void ExistsFile_Returns_False_When_File_Does_Not_Exist() var result = this._dfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() @@ -170,16 +170,16 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() var result = this._dfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - + } + [Test] public void GetFileAttributes_Returns_Null() { var result = this._dfp.GetFileAttributes(It.IsAny()); Assert.IsNull(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() @@ -240,8 +240,8 @@ public void GetFiles_Returns_Valid_FileNames_When_Folder_Contains_Files() var files = this._dfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedFiles, files); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() @@ -298,7 +298,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } - + resultBytes = ms.ToArray(); } @@ -317,8 +317,8 @@ public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() var result = this._dfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { @@ -328,8 +328,8 @@ public void GetImageUrl_Calls_IconControllerWrapper_IconURL() this._dfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderDatabase", "32x32"), Times.Once()); - } - + } + [Test] public void GetLastModificationTime_Returns_Null_Date() { @@ -338,8 +338,8 @@ public void GetLastModificationTime_Returns_Null_Date() var result = this._dfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedResult, result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() @@ -376,7 +376,7 @@ public void GetSubFolders_Count_Equals_DataProvider_GetFoldersByParentFolder_Cou var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - var subFolders = new List() + var subFolders = new List() { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath }, @@ -393,7 +393,7 @@ public void GetSubFolders_Count_Equals_DataProvider_GetFoldersByParentFolder_Cou [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedResult = new List + var expectedResult = new List { Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_OtherValidSubFolderRelativePath, @@ -402,7 +402,7 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() var folderMapping = new FolderMappingInfo(); folderMapping.PortalID = Constants.CONTENT_ValidPortalId; - var subFolders = new List + var subFolders = new List { new FolderInfo { FolderPath = Constants.FOLDER_ValidSubFolderRelativePath }, new FolderInfo { FolderPath = Constants.FOLDER_OtherValidSubFolderRelativePath }, @@ -414,24 +414,24 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() var result = this._dfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedResult, result); - } - + } + [Test] public void IsInSync_Returns_True() { var result = this._dfp.IsInSync(It.IsAny()); Assert.IsTrue(result); - } - + } + [Test] public void SupportsFileAttributes_Returns_False() { var result = this._dfp.SupportsFileAttributes(); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() @@ -478,6 +478,6 @@ public void UpdateFile_Does_Not_Call_DataProvider_UpdateFileContent_When_File_Do this._dfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); this._mockData.Verify(md => md.UpdateFileContent(It.IsAny(), It.IsAny()), Times.Never()); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs index 37b60981f8f..ba415d482f0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/DefaultFolderProvidersTests.cs @@ -11,7 +11,7 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class DefaultFolderProvidersTests - { + { [Test] public void GetDefaultProviders_Should_Return_3_Valid_Providers() { @@ -20,6 +20,6 @@ public void GetDefaultProviders_Should_Return_3_Valid_Providers() var defaultProviders = DefaultFolderProviders.GetDefaultProviders(); CollectionAssert.AreEqual(expectedValues, defaultProviders); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs index a245a53dbe5..2179f2b26ed 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileContentTypeManagerTests.cs @@ -30,7 +30,7 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class FileContentTypeManagerTests - { + { [SetUp] public void Setup() { @@ -50,8 +50,8 @@ public void TearDown() { TestableGlobals.ClearInstance(); CBO.ClearInstance(); - } - + } + [Test] public void GetContentType_Returns_Known_Value_When_Extension_Is_Not_Managed() { @@ -70,6 +70,6 @@ public void GetContentType_Returns_Correct_Value_For_Extension() var contentType = FileContentTypeManager.Instance.GetContentType(notManagedExtension); Assert.AreEqual("text/html", contentType); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs index 4b50cc9d7a9..db06604373e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileDeletionControllerTests.cs @@ -105,7 +105,7 @@ public void DeleteFile_Throws_WhenFolderProviderThrows() this._mockFileLockingController.Setup(mflc => mflc.IsFileLocked(fileInfo, out someString)).Returns(false); this._mockFolderProvider.Setup(mf => mf.DeleteFile(fileInfo)).Throws(); - + FileDeletionController.Instance.DeleteFile(fileInfo); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs index 4898fb2825f..9b23adb255f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileLockingControllerTests.cs @@ -39,8 +39,8 @@ public void TearDown() { UserSecurityController.ClearInstance(); MockComponentProvider.ResetContainer(); - } - + } + [Test] public void IsFileLocked_ReturnsTrue_WhenPublishPeriodIsOut() { @@ -158,8 +158,8 @@ public void IsFileLocked_ReturnsFalse_WhenPublishPeriodIsDisabled() // Assert Assert.IsFalse(result); - } - + } + [Test] public void IsFileOutOfPublishPeriod_ReturnsTrue_WhenPublishPeriodIsOut() { @@ -242,6 +242,6 @@ public void IsFileOutOfPublishPeriod_ReturnsFalse_WhenPublishPeriodIsDisabled() // Assert Assert.IsFalse(result); - } + } } } 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 e0585b69ce0..71c5b655c57 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FileManagerTests.cs @@ -34,7 +34,7 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class FileManagerTests - { + { private FileManager _fileManager; private Mock _folderManager; private Mock _folderPermissionController; @@ -54,8 +54,8 @@ public class FileManagerTests private Mock> _fileEventHandlersContainer; private Mock _mockFileLockingController; private Mock _mockFileDeletionController; - private Mock _hostController; - + private Mock _hostController; + [SetUp] public void Setup() { @@ -111,8 +111,8 @@ public void TearDown() FileDeletionController.ClearInstance(); MockComponentProvider.ResetContainer(); PortalController.ClearInstance(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() @@ -188,7 +188,7 @@ public void AddFile_Checks_Space_For_Stream_Length() this._portalController.Setup(pc => pc.HasSpaceAvailable(It.IsAny(), It.IsAny())).Returns(true); this._globals.Setup(g => g.GetSubFolderPath(Constants.FOLDER_ValidFilePath, Constants.CONTENT_ValidPortalId)).Returns(Constants.FOLDER_ValidFolderRelativePath); - + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); @@ -199,7 +199,7 @@ public void AddFile_Checks_Space_For_Stream_Length() this._mockFileManager.Setup(mfm => mfm.IsAllowedExtension(Constants.FOLDER_ValidFileName)).Returns(true); this._mockFileManager.Setup(mfm => mfm.CreateFileContentItem()).Returns(new ContentItem()); this._mockFileManager.Setup(mfm => mfm.IsImageFile(It.IsAny())).Returns(false); - + this._workflowManager.Setup(we => we.GetWorkflow(It.IsAny())).Returns((Workflow)null); // Act @@ -256,14 +256,6 @@ public void AddFile_No_Error_When_File_Content_Is_Valid() } } - private class UnSeekableStream : MemoryStream - { - public override bool CanSeek - { - get { return false; } - } - } - [Test] public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_And_File_Exists() { @@ -295,7 +287,7 @@ public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_A this._mockData.Setup( md => - md.AddFile( + md.AddFile( It.IsAny(), It.IsAny(), It.IsAny(), @@ -323,8 +315,8 @@ public void AddFile_Does_Not_Call_FolderProvider_AddFile_When_Not_Overwritting_A this._mockFileManager.Object.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, fileContent, false, false, Constants.CONTENTTYPE_ValidContentType); this._mockFolder.Verify(mf => mf.AddFile(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void CopyFile_Throws_On_Null_File() @@ -332,50 +324,6 @@ 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() @@ -432,8 +380,8 @@ public void CopyFile_Throws_When_FolderMapping_Of_Source_And_Destination_Folders this._portalController.Setup(pc => pc.HasSpaceAvailable(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFileSize)).Returns(false); this._fileManager.CopyFile(this._fileInfo.Object, this._folderInfo.Object); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() @@ -466,8 +414,8 @@ public void DeleteFile_Throws_WhenFileDeletionControllerThrows() .Throws(); this._mockFileManager.Object.DeleteFile(this._fileInfo.Object); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DownloadFile_Throws_On_Null_File() @@ -542,8 +490,8 @@ public void DownloadFile_Calls_FileManager_WriteBytesToHttpContext() this._mockFileManager.Object.WriteFileToResponse(this._fileInfo.Object, ContentDisposition.Inline); this._mockFileManager.Verify(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() @@ -654,8 +602,8 @@ public void ExistsFile_Throws_When_FolderProvider_Throws() this._mockFolder.Setup(mf => mf.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName)).Throws(); this._mockFileManager.Object.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); - } - + } + [Test] [TestCase(null)] [TestCase("")] @@ -701,8 +649,8 @@ public void GetFile_Handles_Path_Beyond_Portal_Root() this._folderManager.Verify(); this._mockData.Verify(); - } - + } + [Test] public void GetFileByID_Does_Not_Call_DataCache_GetCache_If_FileId_Is_Not_Valid() { @@ -731,8 +679,8 @@ public void GetFileByID_Calls_DataProvider_GetFileById_When_File_Is_Not_In_Cache this._fileManager.GetFile(Constants.FOLDER_ValidFileId); this._mockData.Verify(md => md.GetFileById(Constants.FOLDER_ValidFileId, It.IsAny()), Times.Once()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void MoveFile_Throws_On_Null_File() @@ -846,8 +794,8 @@ public void MoveFile_Calls_DeleteFile_When_A_File_With_The_Same_Name_Exists_On_T this._mockFileManager.Object.MoveFile(this._fileInfo.Object, this._folderInfo.Object); this._mockFileManager.Verify(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() @@ -951,8 +899,8 @@ public void RenameFile_Throws_When_FolderProvider_Throws() this._mockFolder.Setup(mf => mf.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName)).Throws(); this._mockFileManager.Object.RenameFile(this._fileInfo.Object, Constants.FOLDER_OtherValidFileName); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UnzipFile_Throws_On_Null_File() @@ -986,8 +934,8 @@ public void UnzipFile_Calls_FileManager_ExtractFiles() this._mockFileManager.Object.UnzipFile(this._fileInfo.Object, this._folderInfo.Object); this._mockFileManager.Verify(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_File() @@ -1001,7 +949,7 @@ public void UpdateFile_Calls_DataProvider_UpdateFile() this._fileInfo.Setup(fi => fi.StartDate).Returns(DateTime.Parse(Constants.FOLDER_FileStartDate)); this._mockFileManager.Object.UpdateFile(this._fileInfo.Object); - this._mockData.Verify( + this._mockData.Verify( md => md.UpdateFile( It.IsAny(), It.IsAny(), @@ -1090,8 +1038,8 @@ public void UpdateFile_Calls_FileManager_UpdateFile_Overload() this._mockFileManager.Object.UpdateFile(this._fileInfo.Object, stream); this._mockFileManager.Verify(mfm => mfm.UpdateFile(this._fileInfo.Object), Times.Once()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSeekableStream_Throws_On_Null_Stream() @@ -1121,6 +1069,58 @@ public void GetSeekableStream_Calls_GetHostMapPath_And_Creates_A_Temporary_FileS this._mockFileManager.Object.GetSeekableStream(inputStream.Object); this._mockFileManager.Verify(); - } + } + + 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); + } + + private class UnSeekableStream : MemoryStream + { + public override bool CanSeek + { + get { return false; } + } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs index 14c8a1a8ef2..5056140ebe1 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/FolderManagerTests.cs @@ -29,1050 +29,1050 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class FolderManagerTests { - private FolderManager _folderManager; - private Mock _mockFolder; - private Mock _mockData; - private Mock _mockFolderManager; - private Mock _folderInfo; - private Mock _folderMappingController; - private Mock _directory; - private Mock _file; - private Mock _cbo; - private Mock _pathUtils; - private Mock _mockUserSecurityController; + private FolderManager _folderManager; + private Mock _mockFolder; + private Mock _mockData; + private Mock _mockFolderManager; + private Mock _folderInfo; + private Mock _folderMappingController; + private Mock _directory; + private Mock _file; + private Mock _cbo; + private Mock _pathUtils; + private Mock _mockUserSecurityController; private Mock _mockFileDeletionController; - [SetUp] - public void Setup() - { - this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); - this._mockData = MockComponentProvider.CreateDataProvider(); - - this._folderMappingController = new Mock(); - this._directory = new Mock(); - this._file = new Mock(); - this._cbo = new Mock(); - this._pathUtils = new Mock(); - this._mockUserSecurityController = new Mock(); - this._mockFileDeletionController = new Mock(); - - FolderMappingController.RegisterInstance(this._folderMappingController.Object); - DirectoryWrapper.RegisterInstance(this._directory.Object); - FileWrapper.RegisterInstance(this._file.Object); - CBO.SetTestableInstance(this._cbo.Object); - PathUtils.RegisterInstance(this._pathUtils.Object); - UserSecurityController.SetTestableInstance(this._mockUserSecurityController.Object); - FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); - - this._mockFolderManager = new Mock { CallBase = true }; - - this._folderManager = new FolderManager(); - - this._folderInfo = new Mock(); - } - - [TearDown] - public void TearDown() - { - UserSecurityController.ClearInstance(); - FileLockingController.ClearInstance(); - MockComponentProvider.ResetContainer(); - CBO.ClearInstance(); - FileDeletionController.ClearInstance(); - MockComponentProvider.ResetContainer(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void AddFolder_Throws_On_Null_FolderPath() - { - this._folderManager.AddFolder(It.IsAny(), null); - } - - // [Test] - // public void AddFolder_Calls_FolderProvider_AddFolder() - // { - // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - // var folderMapping = new FolderMappingInfo - // { - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, - // PortalID = Constants.CONTENT_ValidPortalId - // }; - - // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Verifiable(); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); - // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)); - - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - - // _mockFolder.Verify(); - // } - - // [Test] - // [ExpectedException(typeof(FolderProviderException))] - // public void AddFolder_Throws_When_FolderProvider_Throws() - // { - // var folderMapping = new FolderMappingInfo - // { - // PortalID = Constants.CONTENT_ValidPortalId, - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // FolderProviderType = Constants.FOLDER_ValidFolderProviderType - // }; - - // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); - // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Throws(); - - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - // } - - // [Test] - // public void AddFolder_Calls_FolderManager_CreateFolderInFileSystem_And_CreateFolderInDatabase_If_Folder_Does_Not_Exist() - // { - // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - // var folderMapping = new FolderMappingInfo - // { - // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, - // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, - // PortalID = Constants.CONTENT_ValidPortalId - // }; - - // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)); - - // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); - // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)).Verifiable(); - // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); - - // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - - // _mockFolderManager.Verify(); - // } - [Test] - [ExpectedException(typeof(FolderAlreadyExistsException))] - public void AddFolder_Throws_When_Folder_Already_Exists() - { - var folderMapping = new FolderMappingInfo - { - PortalID = Constants.CONTENT_ValidPortalId, - }; - - this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); - - this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - } - - [Test] - [ExpectedException(typeof(InvalidFolderPathException))] - public void AddFolder_Throws_When_FolderPath_Is_Invalid() - { - // arrange - var folderMapping = new FolderMappingInfo - { - PortalID = Constants.CONTENT_ValidPortalId, - }; - - this._mockFolderManager - .Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())) - .Returns(false); - - this._mockFolderManager - .Setup(mfm => mfm.IsValidFolderPath(It.IsAny())) - .Returns(false); - - // act - this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); - - // assert (implicit) - } - - [Test] - public void IsValidFolderPath_Returns_True_When_FolderPath_Is_Valid() - { - // arrange (implicit) - - // act - var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); - - // assert - Assert.IsTrue(result); - } - - [Test] - public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid() - { - // arrange (implicit) - - // act - var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); - - // assert - Assert.IsFalse(result); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void DeleteFolder_Throws_On_Null_Folder() - { - this._folderManager.DeleteFolder(null); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void DeleteFolder_Throws_OnNullFolder_WhenRecursive() - { - // Arrange - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - // Act - var notDeletedSubfolders = new List(); - this._folderManager.DeleteFolder(null, notDeletedSubfolders); - } - - [Test] - public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive() - { - // Arrange - var folderInfo = new FolderInfoBuilder() - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) - .Build(); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); - - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); - - // Act - var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - - // Assert - this._mockFolder.Verify(); - Assert.AreEqual(0, subfoldersNotDeleted.Count); - } - - [Test] - public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExistSubfolders() - { - // Arrange - var folderInfo = new FolderInfoBuilder() - .WithFolderId(1) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) - .Build(); - - var subfolder1 = new FolderInfoBuilder() - .WithFolderId(2) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1") - .Build(); - var subfolder2 = new FolderInfoBuilder() - .WithFolderId(3) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2") - .Build(); - var subfolders = new List - { - subfolder1, - subfolder2, - }; - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - - this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); - - // Act - var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - - // Assert - this._mockFolder.Verify(); - Assert.AreEqual(0, subfoldersNotDeleted.Count); - } - - [Test] - public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHasNotDeletePermission() - { - // Arrange - var folderInfo = new FolderInfoBuilder() - .WithFolderId(1) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) - .Build(); - - var subfolder1 = new FolderInfoBuilder() - .WithFolderId(2) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1") - .Build(); - var subfolder2 = new FolderInfoBuilder() - .WithFolderId(3) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2") - .Build(); - var subfolders = new List - { - subfolder1, - subfolder2, - }; - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); - - this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); - - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); - - // Act - var subfoldersNotDeleted = new List(); - this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); - - // Assert - Assert.AreEqual(2, subfoldersNotDeleted.Count); // folderInfo and subfolder2 are not deleted - } - - [Test] - [ExpectedException(typeof(FileLockedException))] - public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_WhenFileIsLocked() - { - // Arrange - var folderInfo = new FolderInfoBuilder() - .WithFolderId(1) - .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) - .Build(); - - var fileInfo1 = new FileInfoBuilder() - .WithFileId(1) - .Build(); - var fileInfo2 = new FileInfoBuilder() - .WithFileId(2) - .Build(); - var files = new List - { - fileInfo1, - fileInfo2, - }; - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - // _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)); - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); - - this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); - - this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); - - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); - this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); - - // Act - this._mockFolderManager.Object.DeleteFolder(folderInfo, new List()); - } - - [Test] - public void DeleteFolder_Calls_FolderProvider_DeleteFolder() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Verifiable(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - - this._mockFolder.Verify(); - } - - [Test] - [ExpectedException(typeof(FolderProviderException))] - public void DeleteFolder_Throws_When_FolderProvider_Throws() - { - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Throws(); - - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - } - - [Test] - public void DeleteFolder_Calls_Directory_Delete_When_Directory_Exists() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); - - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - this._directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - - this._directory.Verify(); - } - - [Test] - public void DeleteFolder_Calls_FolderManager_DeleteFolder_Overload() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; - - this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - - this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - - this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); - - this._mockFolderManager.Verify(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void ExistsFolder_Throws_On_Null_FolderPath() - { - this._folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); - } - - [Test] - public void ExistsFolder_Calls_FolderManager_GetFolder() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); - - this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - this._mockFolderManager.Verify(); - } - - [Test] - public void ExistsFolder_Returns_True_When_Folder_Exists() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); - - var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - Assert.IsTrue(result); - } - - [Test] - public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - - var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - Assert.IsFalse(result); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void GetFilesByFolder_Throws_On_Null_Folder() - { - this._folderManager.GetFiles(null); - } - - [Test] - public void GetFilesByFolder_Calls_DataProvider_GetFiles() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - var files = new DataTable(); - files.Columns.Add("FolderName"); - - var dr = files.CreateDataReader(); - - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); - - var filesList = new List { new FileInfo() { FileName = Constants.FOLDER_ValidFileName } }; - - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - - this._folderManager.GetFiles(this._folderInfo.Object); - - this._mockData.Verify(); - } - - [Test] - public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - var files = new DataTable(); - files.Columns.Add("FileName"); - files.Rows.Add(Constants.FOLDER_ValidFileName); - - var dr = files.CreateDataReader(); - - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); - - var filesList = new List { new FileInfo { FileName = Constants.FOLDER_ValidFileName } }; - - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - - var result = this._folderManager.GetFiles(this._folderInfo.Object).ToList(); - - Assert.AreEqual(1, result.Count); - } - - [Test] - public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files() - { - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - var files = new DataTable(); - files.Columns.Add("FileName"); - files.Rows.Add(Constants.FOLDER_ValidFileName); - files.Rows.Add(Constants.FOLDER_OtherValidFileName); - - var dr = files.CreateDataReader(); - - this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); - - var filesList = new List - { - new FileInfo { FileName = Constants.FOLDER_ValidFileName }, - new FileInfo { FileName = Constants.FOLDER_OtherValidFileName }, - }; - - this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); - - var result = this._folderManager.GetFiles(this._folderInfo.Object).Cast(); - - CollectionAssert.AreEqual(filesList, result); - } - - [Test] - public void GetFolder_Calls_DataProvider_GetFolder() - { - var folderDataTable = new DataTable(); - folderDataTable.Columns.Add("FolderName"); - - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); - - this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); - - this._mockData.Verify(); - } - - [Test] - public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() - { - var folderDataTable = new DataTable(); - folderDataTable.Columns.Add("FolderName"); - - var dr = folderDataTable.CreateDataReader(); - - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - - var result = this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); - - Assert.IsNull(result); - } - - [Test] - public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() - { - this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - - this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); - - var folderDataTable = new DataTable(); - folderDataTable.Columns.Add("FolderName"); - folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName); - - var dr = folderDataTable.CreateDataReader(); - - this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); - - var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - - var result = this._mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); - - Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void GetFolder_Throws_On_Null_FolderPath() - { - this._folderManager.GetFolder(It.IsAny(), null); - } - - [Test] - public void GetFolder_Calls_GetFolders() - { - var foldersSorted = new List(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); - - this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - this._mockFolderManager.Verify(); - } - - [Test] - public void GetFolder_Calls_DataProvider_GetFolder_When_Folder_Is_Not_In_Cache() - { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var foldersSorted = new List(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - - this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - this._mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); - } - - [Test] - public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() - { - var folderDataTable = new DataTable(); - folderDataTable.Columns.Add("FolderName"); - - var dr = folderDataTable.CreateDataReader(); - - this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); - - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - - var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - Assert.IsNull(result); - } - - [Test] - public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() - { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); - - var folderDataTable = new DataTable(); - folderDataTable.Columns.Add("FolderName"); - folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName); - - var dr = folderDataTable.CreateDataReader(); - - this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); - - var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; - - this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - - var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); - - Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void GetFoldersByParentFolder_Throws_On_Null_ParentFolder() - { - this._folderManager.GetFolders((IFolderInfo)null); - } - - [Test] - public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contains_No_Subfolders() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); - - var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); - - Assert.AreEqual(0, result.Count); - } - - [Test] - public void GetFoldersByParentFolder_Returns_Valid_Subfolders() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); - - var foldersSorted = new List - { - new FolderInfo { FolderID = Constants.FOLDER_ValidFolderId, ParentID = Null.NullInteger }, - new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId }, - }; - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); - - var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); - - Assert.AreEqual(1, result.Count); - Assert.AreEqual(Constants.FOLDER_OtherValidFolderId, result[0].FolderID); - } - - [Test] - public void GetFolders_Calls_CBO_GetCachedObject() - { - var folders = new List(); - - this._cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); - - this._mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); - - this._cbo.Verify(); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void RenameFolder_Throws_On_Null_Folder() - { - this._folderManager.RenameFolder(null, It.IsAny()); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void RenameFolder_Throws_On_Null_Or_Empty_NewFolderName(string newFolderName) - { - this._folderManager.RenameFolder(this._folderInfo.Object, newFolderName); - } - - [Test] - [ExpectedException(typeof(FolderAlreadyExistsException))] - public void RenameFolder_Throws_When_DestinationFolder_Exists() - { - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - - this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); - - this._mockFolderManager.Object.RenameFolder(this._folderInfo.Object, Constants.FOLDER_OtherValidFolderName); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void UpdateFolder_Throws_On_Null_Folder() - { - this._folderManager.UpdateFolder(null); - } - - [Test] - public void UpdateFolder_Calls_DataProvider_UpdateFolder() - { - this._mockFolderManager.Setup(mfm => mfm.AddLogEntry(this._folderInfo.Object, It.IsAny())); - this._mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(this._folderInfo.Object)); - this._mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); - - this._mockFolderManager.Object.UpdateFolder(this._folderInfo.Object); - + [SetUp] + public void Setup() + { + this._mockFolder = MockComponentProvider.CreateFolderProvider(Constants.FOLDER_ValidFolderProviderType); + this._mockData = MockComponentProvider.CreateDataProvider(); + + this._folderMappingController = new Mock(); + this._directory = new Mock(); + this._file = new Mock(); + this._cbo = new Mock(); + this._pathUtils = new Mock(); + this._mockUserSecurityController = new Mock(); + this._mockFileDeletionController = new Mock(); + + FolderMappingController.RegisterInstance(this._folderMappingController.Object); + DirectoryWrapper.RegisterInstance(this._directory.Object); + FileWrapper.RegisterInstance(this._file.Object); + CBO.SetTestableInstance(this._cbo.Object); + PathUtils.RegisterInstance(this._pathUtils.Object); + UserSecurityController.SetTestableInstance(this._mockUserSecurityController.Object); + FileDeletionController.SetTestableInstance(this._mockFileDeletionController.Object); + + this._mockFolderManager = new Mock { CallBase = true }; + + this._folderManager = new FolderManager(); + + this._folderInfo = new Mock(); + } + + [TearDown] + public void TearDown() + { + UserSecurityController.ClearInstance(); + FileLockingController.ClearInstance(); + MockComponentProvider.ResetContainer(); + CBO.ClearInstance(); + FileDeletionController.ClearInstance(); + MockComponentProvider.ResetContainer(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void AddFolder_Throws_On_Null_FolderPath() + { + this._folderManager.AddFolder(It.IsAny(), null); + } + + // [Test] + // public void AddFolder_Calls_FolderProvider_AddFolder() + // { + // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + // var folderMapping = new FolderMappingInfo + // { + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, + // PortalID = Constants.CONTENT_ValidPortalId + // }; + + // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Verifiable(); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); + // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)); + + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + + // _mockFolder.Verify(); + // } + + // [Test] + // [ExpectedException(typeof(FolderProviderException))] + // public void AddFolder_Throws_When_FolderProvider_Throws() + // { + // var folderMapping = new FolderMappingInfo + // { + // PortalID = Constants.CONTENT_ValidPortalId, + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // FolderProviderType = Constants.FOLDER_ValidFolderProviderType + // }; + + // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); + // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)).Throws(); + + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + // } + + // [Test] + // public void AddFolder_Calls_FolderManager_CreateFolderInFileSystem_And_CreateFolderInDatabase_If_Folder_Does_Not_Exist() + // { + // _folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + // _folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + // _folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + // var folderMapping = new FolderMappingInfo + // { + // FolderMappingID = Constants.FOLDER_ValidFolderMappingID, + // FolderProviderType = Constants.FOLDER_ValidFolderProviderType, + // PortalID = Constants.CONTENT_ValidPortalId + // }; + + // _mockFolder.Setup(mf => mf.AddFolder(Constants.FOLDER_ValidSubFolderRelativePath, folderMapping)); + + // _pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(Constants.FOLDER_ValidSubFolderPath); + // _mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(false); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInFileSystem(Constants.FOLDER_ValidSubFolderPath)).Verifiable(); + // _mockFolderManager.Setup(mfm => mfm.CreateFolderInDatabase(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_ValidFolderMappingID)).Verifiable(); + + // _mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + + // _mockFolderManager.Verify(); + // } + [Test] + [ExpectedException(typeof(FolderAlreadyExistsException))] + public void AddFolder_Throws_When_Folder_Already_Exists() + { + var folderMapping = new FolderMappingInfo + { + PortalID = Constants.CONTENT_ValidPortalId, + }; + + this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderRelativePath)).Returns(true); + + this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + } + + [Test] + [ExpectedException(typeof(InvalidFolderPathException))] + public void AddFolder_Throws_When_FolderPath_Is_Invalid() + { + // arrange + var folderMapping = new FolderMappingInfo + { + PortalID = Constants.CONTENT_ValidPortalId, + }; + + this._mockFolderManager + .Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())) + .Returns(false); + + this._mockFolderManager + .Setup(mfm => mfm.IsValidFolderPath(It.IsAny())) + .Returns(false); + + // act + this._mockFolderManager.Object.AddFolder(folderMapping, Constants.FOLDER_ValidSubFolderRelativePath); + + // assert (implicit) + } + + [Test] + public void IsValidFolderPath_Returns_True_When_FolderPath_Is_Valid() + { + // arrange (implicit) + + // act + var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_ValidSubFolderRelativePath); + + // assert + Assert.IsTrue(result); + } + + [Test] + public void IsValidFolderPath_Returns_False_When_FolderPath_Is_Invalid() + { + // arrange (implicit) + + // act + var result = this._mockFolderManager.Object.IsValidFolderPath(Constants.FOLDER_InvalidSubFolderRelativePath); + + // assert + Assert.IsFalse(result); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void DeleteFolder_Throws_On_Null_Folder() + { + this._folderManager.DeleteFolder(null); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void DeleteFolder_Throws_OnNullFolder_WhenRecursive() + { + // Arrange + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + // Act + var notDeletedSubfolders = new List(); + this._folderManager.DeleteFolder(null, notDeletedSubfolders); + } + + [Test] + public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive() + { + // Arrange + var folderInfo = new FolderInfoBuilder() + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) + .Build(); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(new List()); + + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(folderInfo, "DELETE")).Returns(true); + + // Act + var subfoldersNotDeleted = new List(); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + + // Assert + this._mockFolder.Verify(); + Assert.AreEqual(0, subfoldersNotDeleted.Count); + } + + [Test] + public void DeleteFolder_CallsFolderProviderDeleteFolder_WhenRecursive_WhenExistSubfolders() + { + // Arrange + var folderInfo = new FolderInfoBuilder() + .WithFolderId(1) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) + .Build(); + + var subfolder1 = new FolderInfoBuilder() + .WithFolderId(2) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1") + .Build(); + var subfolder2 = new FolderInfoBuilder() + .WithFolderId(3) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2") + .Build(); + var subfolders = new List + { + subfolder1, + subfolder2, + }; + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)).Verifiable(); + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder2)).Verifiable(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + + this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + + // Act + var subfoldersNotDeleted = new List(); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + + // Assert + this._mockFolder.Verify(); + Assert.AreEqual(0, subfoldersNotDeleted.Count); + } + + [Test] + public void DeleteFolder_SubFoldersCollectionIsNotEmpty_WhenRecursive_WhenUserHasNotDeletePermission() + { + // Arrange + var folderInfo = new FolderInfoBuilder() + .WithFolderId(1) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) + .Build(); + + var subfolder1 = new FolderInfoBuilder() + .WithFolderId(2) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder1") + .Build(); + var subfolder2 = new FolderInfoBuilder() + .WithFolderId(3) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath + "\\subfolder2") + .Build(); + var subfolders = new List + { + subfolder1, + subfolder2, + }; + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(subfolder1)); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(subfolders); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsNotIn(folderInfo))).Returns(new List()); + + this._mockFolderManager.Setup(mfm => mfm.GetFiles(It.IsAny(), It.IsAny(), It.IsAny())).Returns(new List()); + + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(subfolder2, "DELETE")).Returns(false); + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsNotIn(subfolder2), "DELETE")).Returns(true); + + // Act + var subfoldersNotDeleted = new List(); + this._mockFolderManager.Object.DeleteFolder(folderInfo, subfoldersNotDeleted); + + // Assert + Assert.AreEqual(2, subfoldersNotDeleted.Count); // folderInfo and subfolder2 are not deleted + } + + [Test] + [ExpectedException(typeof(FileLockedException))] + public void DeleteFolder_Throws_OnFileDeletionControllerThrows_WhenRecursive_WhenFileIsLocked() + { + // Arrange + var folderInfo = new FolderInfoBuilder() + .WithFolderId(1) + .WithPhysicalPath(Constants.FOLDER_ValidFolderPath) + .Build(); + + var fileInfo1 = new FileInfoBuilder() + .WithFileId(1) + .Build(); + var fileInfo2 = new FileInfoBuilder() + .WithFileId(2) + .Build(); + var files = new List + { + fileInfo1, + fileInfo2, + }; + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + // _mockFolder.Setup(mf => mf.DeleteFolder(folderInfo)); + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + this._mockFolderManager.Setup(mfm => mfm.GetFolders(folderInfo)).Returns(new List()); + + this._mockFolderManager.Setup(mfm => mfm.GetFiles(folderInfo, It.IsAny(), It.IsAny())).Returns(files); + + this._mockUserSecurityController.Setup(musc => musc.HasFolderPermission(It.IsAny(), "DELETE")).Returns(true); + + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo1)); + this._mockFileDeletionController.Setup(mfdc => mfdc.DeleteFile(fileInfo2)).Throws(); + + // Act + this._mockFolderManager.Object.DeleteFolder(folderInfo, new List()); + } + + [Test] + public void DeleteFolder_Calls_FolderProvider_DeleteFolder() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Verifiable(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + + this._mockFolder.Verify(); + } + + [Test] + [ExpectedException(typeof(FolderProviderException))] + public void DeleteFolder_Throws_When_FolderProvider_Throws() + { + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)).Throws(); + + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + } + + [Test] + public void DeleteFolder_Calls_Directory_Delete_When_Directory_Exists() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); + + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + this._directory.Setup(d => d.Delete(Constants.FOLDER_ValidFolderPath, true)).Verifiable(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + + this._directory.Verify(); + } + + [Test] + public void DeleteFolder_Calls_FolderManager_DeleteFolder_Overload() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFolderPath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var folderMapping = new FolderMappingInfo { FolderProviderType = Constants.FOLDER_ValidFolderProviderType }; + + this._folderMappingController.Setup(fmc => fmc.GetFolderMapping(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + + this._mockFolder.Setup(mf => mf.DeleteFolder(this._folderInfo.Object)); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + + this._mockFolderManager.Object.DeleteFolder(this._folderInfo.Object); + + this._mockFolderManager.Verify(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void ExistsFolder_Throws_On_Null_FolderPath() + { + this._folderManager.FolderExists(Constants.CONTENT_ValidPortalId, null); + } + + [Test] + public void ExistsFolder_Calls_FolderManager_GetFolder() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object).Verifiable(); + + this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + this._mockFolderManager.Verify(); + } + + [Test] + public void ExistsFolder_Returns_True_When_Folder_Exists() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + + var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + Assert.IsTrue(result); + } + + [Test] + public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + + var result = this._mockFolderManager.Object.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + Assert.IsFalse(result); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void GetFilesByFolder_Throws_On_Null_Folder() + { + this._folderManager.GetFiles(null); + } + + [Test] + public void GetFilesByFolder_Calls_DataProvider_GetFiles() + { + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + var files = new DataTable(); + files.Columns.Add("FolderName"); + + var dr = files.CreateDataReader(); + + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr).Verifiable(); + + var filesList = new List { new FileInfo() { FileName = Constants.FOLDER_ValidFileName } }; + + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + + this._folderManager.GetFiles(this._folderInfo.Object); + + this._mockData.Verify(); + } + + [Test] + public void GetFilesByFolder_Count_Equals_DataProvider_GetFiles_Count() + { + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + var files = new DataTable(); + files.Columns.Add("FileName"); + files.Rows.Add(Constants.FOLDER_ValidFileName); + + var dr = files.CreateDataReader(); + + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + + var filesList = new List { new FileInfo { FileName = Constants.FOLDER_ValidFileName } }; + + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + + var result = this._folderManager.GetFiles(this._folderInfo.Object).ToList(); + + Assert.AreEqual(1, result.Count); + } + + [Test] + public void GetFilesByFolder_Returns_Valid_FileNames_When_Folder_Contains_Files() + { + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + var files = new DataTable(); + files.Columns.Add("FileName"); + files.Rows.Add(Constants.FOLDER_ValidFileName); + files.Rows.Add(Constants.FOLDER_OtherValidFileName); + + var dr = files.CreateDataReader(); + + this._mockData.Setup(md => md.GetFiles(Constants.FOLDER_ValidFolderId, It.IsAny(), It.IsAny())).Returns(dr); + + var filesList = new List + { + new FileInfo { FileName = Constants.FOLDER_ValidFileName }, + new FileInfo { FileName = Constants.FOLDER_OtherValidFileName }, + }; + + this._cbo.Setup(cbo => cbo.FillCollection(dr)).Returns(filesList); + + var result = this._folderManager.GetFiles(this._folderInfo.Object).Cast(); + + CollectionAssert.AreEqual(filesList, result); + } + + [Test] + public void GetFolder_Calls_DataProvider_GetFolder() + { + var folderDataTable = new DataTable(); + folderDataTable.Columns.Add("FolderName"); + + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(folderDataTable.CreateDataReader()).Verifiable(); + + this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + + this._mockData.Verify(); + } + + [Test] + public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist() + { + var folderDataTable = new DataTable(); + folderDataTable.Columns.Add("FolderName"); + + var dr = folderDataTable.CreateDataReader(); + + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + + var result = this._folderManager.GetFolder(Constants.FOLDER_ValidFolderId); + + Assert.IsNull(result); + } + + [Test] + public void GetFolder_Returns_Valid_Folder_When_Folder_Exists() + { + this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + + this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + + var folderDataTable = new DataTable(); + folderDataTable.Columns.Add("FolderName"); + folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName); + + var dr = folderDataTable.CreateDataReader(); + + this._mockData.Setup(md => md.GetFolder(Constants.FOLDER_ValidFolderId)).Returns(dr); + + var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; + + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + + var result = this._mockFolderManager.Object.GetFolder(Constants.FOLDER_ValidFolderId); + + Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void GetFolder_Throws_On_Null_FolderPath() + { + this._folderManager.GetFolder(It.IsAny(), null); + } + + [Test] + public void GetFolder_Calls_GetFolders() + { + var foldersSorted = new List(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted).Verifiable(); + + this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + this._mockFolderManager.Verify(); + } + + [Test] + public void GetFolder_Calls_DataProvider_GetFolder_When_Folder_Is_Not_In_Cache() + { + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var foldersSorted = new List(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + + this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + this._mockData.Verify(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath), Times.Once()); + } + + [Test] + public void GetFolder_Returns_Null_When_Folder_Does_Not_Exist_Overload() + { + var folderDataTable = new DataTable(); + folderDataTable.Columns.Add("FolderName"); + + var dr = folderDataTable.CreateDataReader(); + + this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(null); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + + var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + Assert.IsNull(result); + } + + [Test] + public void GetFolder_Returns_Valid_Folder_When_Folder_Exists_Overload() + { + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._pathUtils.Setup(pu => pu.RemoveTrailingSlash(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderName); + + var folderDataTable = new DataTable(); + folderDataTable.Columns.Add("FolderName"); + folderDataTable.Rows.Add(Constants.FOLDER_ValidFolderName); + + var dr = folderDataTable.CreateDataReader(); + + this._mockData.Setup(md => md.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(dr); + + var folderInfo = new FolderInfo { FolderPath = Constants.FOLDER_ValidFolderRelativePath }; + + this._cbo.Setup(cbo => cbo.FillObject(dr)).Returns(folderInfo); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + + var result = this._mockFolderManager.Object.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath); + + Assert.AreEqual(Constants.FOLDER_ValidFolderName, result.FolderName); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void GetFoldersByParentFolder_Throws_On_Null_ParentFolder() + { + this._folderManager.GetFolders((IFolderInfo)null); + } + + [Test] + public void GetFoldersByParentFolder_Returns_Empty_List_When_ParentFolder_Contains_No_Subfolders() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(new List()); + + var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); + + Assert.AreEqual(0, result.Count); + } + + [Test] + public void GetFoldersByParentFolder_Returns_Valid_Subfolders() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderID).Returns(Constants.FOLDER_ValidFolderId); + + var foldersSorted = new List + { + new FolderInfo { FolderID = Constants.FOLDER_ValidFolderId, ParentID = Null.NullInteger }, + new FolderInfo { FolderID = Constants.FOLDER_OtherValidFolderId, ParentID = Constants.FOLDER_ValidFolderId }, + }; + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(Constants.CONTENT_ValidPortalId)).Returns(foldersSorted); + + var result = this._mockFolderManager.Object.GetFolders(this._folderInfo.Object).ToList(); + + Assert.AreEqual(1, result.Count); + Assert.AreEqual(Constants.FOLDER_OtherValidFolderId, result[0].FolderID); + } + + [Test] + public void GetFolders_Calls_CBO_GetCachedObject() + { + var folders = new List(); + + this._cbo.Setup(cbo => cbo.GetCachedObject>(It.IsAny(), It.IsAny(), false)).Returns(folders).Verifiable(); + + this._mockFolderManager.Object.GetFolders(Constants.CONTENT_ValidPortalId); + + this._cbo.Verify(); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void RenameFolder_Throws_On_Null_Folder() + { + this._folderManager.RenameFolder(null, It.IsAny()); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void RenameFolder_Throws_On_Null_Or_Empty_NewFolderName(string newFolderName) + { + this._folderManager.RenameFolder(this._folderInfo.Object, newFolderName); + } + + [Test] + [ExpectedException(typeof(FolderAlreadyExistsException))] + public void RenameFolder_Throws_When_DestinationFolder_Exists() + { + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderName)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + + this._folderInfo.Setup(fi => fi.FolderName).Returns(Constants.FOLDER_ValidFolderName); + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + + this._mockFolderManager.Setup(mfm => mfm.FolderExists(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidFolderRelativePath)).Returns(true); + + this._mockFolderManager.Object.RenameFolder(this._folderInfo.Object, Constants.FOLDER_OtherValidFolderName); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void UpdateFolder_Throws_On_Null_Folder() + { + this._folderManager.UpdateFolder(null); + } + + [Test] + public void UpdateFolder_Calls_DataProvider_UpdateFolder() + { + this._mockFolderManager.Setup(mfm => mfm.AddLogEntry(this._folderInfo.Object, It.IsAny())); + this._mockFolderManager.Setup(mfm => mfm.SaveFolderPermissions(this._folderInfo.Object)); + this._mockFolderManager.Setup(mfm => mfm.ClearFolderCache(It.IsAny())); + + this._mockFolderManager.Object.UpdateFolder(this._folderInfo.Object); + this._mockData.Verify( - md => md.UpdateFolder( - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny(), - It.IsAny()), Times.Once()); - } - - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void SynchronizeFolder_Throws_On_Null_RelativePath() - { - this._folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); - } - - [Test] - [ExpectedException(typeof(NoNetworkAvailableException))] - public void SynchronizeFolder_Throws_When_Some_Folder_Mapping_Requires_Network_Connectivity_But_There_Is_No_Network_Available() - { - this._mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); - this._mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); - - this._mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); - } - - [Test] - public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() - { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); - - var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); - - Assert.IsEmpty(result); - } - - [Test] - public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() - { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); - - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - - var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); - - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Values[0].ExistsInFileSystem); - } - - [Test] - public void GetFileSystemFolders_Calls_FolderManager_GetFileSystemFoldersRecursive_When_Folder_Exists_And_Is_Recursive() - { - this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - .Returns(Constants.FOLDER_ValidFolderPath); - - this._mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) - .Returns(It.IsAny>()) - .Verifiable(); - - this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); - - this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - - this._mockFolderManager.Verify(); - } - - [Test] - public void GetFileSystemFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() - { - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - this._directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); - - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); - - Assert.AreEqual(1, result.Count); - } - - [Test] - public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() - { - var relativePaths = new Dictionary - { - { @"C:\folder", "folder/" }, - { @"C:\folder\subfolder", "folder/subfolder/" }, - { @"C:\folder\subfolder2", "folder/subfolder2/" }, - { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, - { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, - }; - - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) - .Returns((portalID, physicalPath) => relativePaths[physicalPath]); - - var directories = new List { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - - this._directory.Setup(d => d.GetDirectories(It.IsAny())) - .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); - - Assert.AreEqual(5, result.Count); - } - - [Test] - public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items() - { - var relativePaths = new Dictionary - { - { @"C:\folder", "folder/" }, - { @"C:\folder\subfolder", "folder/subfolder/" }, - { @"C:\folder\subfolder2", "folder/subfolder2/" }, - { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, - { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, - }; - - this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) - .Returns((portalID, physicalPath) => relativePaths[physicalPath]); - - var directories = new List { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; - - this._directory.Setup(d => d.GetDirectories(It.IsAny())) - .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); - - var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); - - foreach (var mergedTreeItem in result.Values) - { - Assert.True(mergedTreeItem.ExistsInFileSystem); - } - } - - [Test] - public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); - - var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); - - Assert.IsEmpty(result); - } - - [Test] - public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); - - var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); - - Assert.AreEqual(1, result.Count); - Assert.IsTrue(result.Values[0].ExistsInDatabase); - } - - [Test] - public void GetDatabaseFolders_Calls_FolderManager_GetDatabaseFoldersRecursive_When_Folder_Exists_And_Is_Recursive() - { - this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) - .Returns(this._folderInfo.Object); - - this._mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(this._folderInfo.Object)) - .Returns(It.IsAny>()) - .Verifiable(); - - this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); - - this._mockFolderManager.Verify(); - } - - [Test] - public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() - { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var subfolders = new List(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(this._folderInfo.Object)).Returns(subfolders); - - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); - - Assert.AreEqual(1, result.Count); - } - - [Test] - public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() - { - this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var subfolders = new List - { - new FolderInfo { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - }; - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) - .Returns(parent => subfolders.FindAll(sub => - sub.FolderPath.StartsWith(parent.FolderPath) && - sub.FolderPath.Length > parent.FolderPath.Length && - sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); - - Assert.AreEqual(5, result.Count); - } - - [Test] - public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() - { - this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var subfolders = new List - { - new FolderInfo() { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo() { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, - }; - - this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) - .Returns(parent => subfolders.FindAll(sub => - sub.FolderPath.StartsWith(parent.FolderPath) && - sub.FolderPath.Length > parent.FolderPath.Length && - sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); - - var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); - - foreach (var mergedTreeItem in result.Values) - { - Assert.True(mergedTreeItem.ExistsInDatabase); - } + md => md.UpdateFolder( + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny(), + It.IsAny()), Times.Once()); + } + + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void SynchronizeFolder_Throws_On_Null_RelativePath() + { + this._folderManager.Synchronize(It.IsAny(), null, It.IsAny(), It.IsAny()); + } + + [Test] + [ExpectedException(typeof(NoNetworkAvailableException))] + public void SynchronizeFolder_Throws_When_Some_Folder_Mapping_Requires_Network_Connectivity_But_There_Is_No_Network_Available() + { + this._mockFolderManager.Setup(mfm => mfm.AreThereFolderMappingsRequiringNetworkConnectivity(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false)).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.IsNetworkAvailable()).Returns(false); + + this._mockFolderManager.Object.Synchronize(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false, false); + } + + [Test] + public void GetFileSystemFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() + { + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(false); + + var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + + Assert.IsEmpty(result); + } + + [Test] + public void GetFileSystemFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() + { + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderPath); + + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + + var result = this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + + Assert.AreEqual(1, result.Count); + Assert.IsTrue(result.Values[0].ExistsInFileSystem); + } + + [Test] + public void GetFileSystemFolders_Calls_FolderManager_GetFileSystemFoldersRecursive_When_Folder_Exists_And_Is_Recursive() + { + this._pathUtils.Setup(pu => pu.GetPhysicalPath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + .Returns(Constants.FOLDER_ValidFolderPath); + + this._mockFolderManager.Setup(mfm => mfm.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)) + .Returns(It.IsAny>()) + .Verifiable(); + + this._directory.Setup(d => d.Exists(Constants.FOLDER_ValidFolderPath)).Returns(true); + + this._mockFolderManager.Object.GetFileSystemFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + + this._mockFolderManager.Verify(); + } + + [Test] + public void GetFileSystemFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() + { + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + this._directory.Setup(d => d.GetDirectories(Constants.FOLDER_ValidFolderPath)).Returns(new string[0]); + + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderPath); + + Assert.AreEqual(1, result.Count); + } + + [Test] + public void GetFileSystemFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() + { + var relativePaths = new Dictionary + { + { @"C:\folder", "folder/" }, + { @"C:\folder\subfolder", "folder/subfolder/" }, + { @"C:\folder\subfolder2", "folder/subfolder2/" }, + { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, + { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, + }; + + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + .Returns((portalID, physicalPath) => relativePaths[physicalPath]); + + var directories = new List { @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; + + this._directory.Setup(d => d.GetDirectories(It.IsAny())) + .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); + + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + + Assert.AreEqual(5, result.Count); + } + + [Test] + public void GetFileSystemFoldersRecursive_Sets_ExistsInFileSystem_For_All_Items() + { + var relativePaths = new Dictionary + { + { @"C:\folder", "folder/" }, + { @"C:\folder\subfolder", "folder/subfolder/" }, + { @"C:\folder\subfolder2", "folder/subfolder2/" }, + { @"C:\folder\subfolder2\subsubfolder", "folder/subfolder2/subsubfolder/" }, + { @"C:\folder\subfolder2\subsubfolder2", "folder/subfolder2/subsubfolder2/" }, + }; + + this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, It.IsAny())) + .Returns((portalID, physicalPath) => relativePaths[physicalPath]); + + var directories = new List { @"C:\folder", @"C:\folder\subfolder", @"C:\folder\subfolder2", @"C:\folder\subfolder2\subsubfolder", @"C:\folder\subfolder2\subsubfolder2" }; + + this._directory.Setup(d => d.GetDirectories(It.IsAny())) + .Returns(path => directories.FindAll(sub => sub.StartsWith(path + "\\") && sub.LastIndexOf("\\") == path.Length).ToArray()); + + var result = this._mockFolderManager.Object.GetFileSystemFoldersRecursive(Constants.CONTENT_ValidPortalId, @"C:\folder"); + + foreach (var mergedTreeItem in result.Values) + { + Assert.True(mergedTreeItem.ExistsInFileSystem); + } + } + + [Test] + public void GetDatabaseFolders_Returns_Empty_List_When_Folder_Does_Not_Exist() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(null); + + var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + + Assert.IsEmpty(result); + } + + [Test] + public void GetDatabaseFolders_Returns_One_Item_When_Folder_Exists_And_Is_Not_Recursive() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Returns(this._folderInfo.Object); + + var result = this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, false); + + Assert.AreEqual(1, result.Count); + Assert.IsTrue(result.Values[0].ExistsInDatabase); + } + + [Test] + public void GetDatabaseFolders_Calls_FolderManager_GetDatabaseFoldersRecursive_When_Folder_Exists_And_Is_Recursive() + { + this._mockFolderManager.Setup(mfm => mfm.GetFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)) + .Returns(this._folderInfo.Object); + + this._mockFolderManager.Setup(mfm => mfm.GetDatabaseFoldersRecursive(this._folderInfo.Object)) + .Returns(It.IsAny>()) + .Verifiable(); + + this._mockFolderManager.Object.GetDatabaseFolders(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath, true); + + this._mockFolderManager.Verify(); + } + + [Test] + public void GetDatabaseFoldersRecursive_Returns_One_Item_When_Folder_Does_Not_Have_SubFolders() + { + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var subfolders = new List(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(this._folderInfo.Object)).Returns(subfolders); + + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + + Assert.AreEqual(1, result.Count); + } + + [Test] + public void GetDatabaseFoldersRecursive_Returns_All_The_Folders_In_Folder_Tree() + { + this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var subfolders = new List + { + new FolderInfo { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + }; + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + .Returns(parent => subfolders.FindAll(sub => + sub.FolderPath.StartsWith(parent.FolderPath) && + sub.FolderPath.Length > parent.FolderPath.Length && + sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); + + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + + Assert.AreEqual(5, result.Count); + } + + [Test] + public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() + { + this._folderInfo.Setup(fi => fi.FolderPath).Returns("folder/"); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var subfolders = new List + { + new FolderInfo() { FolderPath = "folder/subfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + new FolderInfo() { FolderPath = "folder/subfolder2/subsubfolder2/", FolderMappingID = Constants.FOLDER_ValidFolderMappingID }, + }; + + this._mockFolderManager.Setup(mfm => mfm.GetFolders(It.IsAny())) + .Returns(parent => subfolders.FindAll(sub => + sub.FolderPath.StartsWith(parent.FolderPath) && + sub.FolderPath.Length > parent.FolderPath.Length && + sub.FolderPath.Substring(parent.FolderPath.Length).IndexOf("/") == sub.FolderPath.Substring(parent.FolderPath.Length).LastIndexOf("/"))); + + var result = this._mockFolderManager.Object.GetDatabaseFoldersRecursive(this._folderInfo.Object); + + foreach (var mergedTreeItem in result.Values) + { + Assert.True(mergedTreeItem.ExistsInDatabase); + } } // [Test] @@ -1144,35 +1144,35 @@ public void GetDatabaseFoldersRecursive_Sets_ExistsInDatabase_For_All_Items() // Assert.True(mergedTreeItem.ExistsInFolderMappings.Contains(Constants.FOLDER_ValidFolderMappingID)); // } // } - [Test] - public void MergeFolderLists_Returns_Empty_List_When_Both_Lists_Are_Empty() - { - var list1 = new SortedList(); - var list2 = new SortedList(); - - var result = this._folderManager.MergeFolderLists(list1, list2); - - Assert.IsEmpty(result); - } - - [Test] - public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Lists() - { - var list1 = new SortedList - { - { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, - { "folder2", new FolderManager.MergedTreeItem { FolderPath = "folder2" } }, - }; - - var list2 = new SortedList - { - { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, - { "folder3", new FolderManager.MergedTreeItem { FolderPath = "folder3" } }, - }; - - var result = this._folderManager.MergeFolderLists(list1, list2); - - Assert.AreEqual(3, result.Count); + [Test] + public void MergeFolderLists_Returns_Empty_List_When_Both_Lists_Are_Empty() + { + var list1 = new SortedList(); + var list2 = new SortedList(); + + var result = this._folderManager.MergeFolderLists(list1, list2); + + Assert.IsEmpty(result); + } + + [Test] + public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Lists() + { + var list1 = new SortedList + { + { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, + { "folder2", new FolderManager.MergedTreeItem { FolderPath = "folder2" } }, + }; + + var list2 = new SortedList + { + { "folder1", new FolderManager.MergedTreeItem { FolderPath = "folder1" } }, + { "folder3", new FolderManager.MergedTreeItem { FolderPath = "folder3" } }, + }; + + var result = this._folderManager.MergeFolderLists(list1, list2); + + Assert.AreEqual(3, result.Count); } // [Test] @@ -2077,55 +2077,55 @@ public void MergeFolderLists_Count_Equals_The_Intersection_Count_Between_Both_Li // _mockFolderManager.Verify(mfm => mfm.DeleteFolder(It.IsAny(), It.IsAny()), Times.Never()); // _directory.Verify(d => d.Delete(It.IsAny(), It.IsAny()), Times.Never()); // } - [Test] - [ExpectedException(typeof(ArgumentNullException))] - public void MoveFolder_Throws_On_Null_Folder() - { - this._folderManager.MoveFolder(null, It.IsAny()); - } - - [Test] - [TestCase(null)] - [TestCase("")] - [ExpectedException(typeof(ArgumentException))] - public void MoveFolder_Throws_On_Null_Or_Emtpy_NewFolderPath(string newFolderPath) - { - this._folderManager.MoveFolder(this._folderInfo.Object, newFolderPath); - } - - [Test] - public void MoveFolder_Returns_The_Same_Folder_If_The_Paths_Are_The_Same() - { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - - IFolderInfo destinationFolder = new FolderInfo(); - destinationFolder.FolderPath = Constants.FOLDER_ValidFolderRelativePath; - - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); - - var movedFolder = this._folderManager.MoveFolder(this._folderInfo.Object, destinationFolder); - - Assert.AreEqual(this._folderInfo.Object, movedFolder); - } - - [Test] - [ExpectedException(typeof(InvalidOperationException))] - public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() - { - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - IFolderInfo destinationFolder = new FolderInfo(); - destinationFolder.FolderPath = Constants.FOLDER_OtherValidFolderRelativePath; - destinationFolder.FolderMappingID = Constants.FOLDER_ValidFolderMappingID; - - this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); - - this._mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); - this._mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); - this._mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(this._folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); - - this._mockFolderManager.Object.MoveFolder(this._folderInfo.Object, destinationFolder); + [Test] + [ExpectedException(typeof(ArgumentNullException))] + public void MoveFolder_Throws_On_Null_Folder() + { + this._folderManager.MoveFolder(null, It.IsAny()); + } + + [Test] + [TestCase(null)] + [TestCase("")] + [ExpectedException(typeof(ArgumentException))] + public void MoveFolder_Throws_On_Null_Or_Emtpy_NewFolderPath(string newFolderPath) + { + this._folderManager.MoveFolder(this._folderInfo.Object, newFolderPath); + } + + [Test] + public void MoveFolder_Returns_The_Same_Folder_If_The_Paths_Are_The_Same() + { + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + + IFolderInfo destinationFolder = new FolderInfo(); + destinationFolder.FolderPath = Constants.FOLDER_ValidFolderRelativePath; + + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_ValidFolderRelativePath)).Returns(Constants.FOLDER_ValidFolderRelativePath); + + var movedFolder = this._folderManager.MoveFolder(this._folderInfo.Object, destinationFolder); + + Assert.AreEqual(this._folderInfo.Object, movedFolder); + } + + [Test] + [ExpectedException(typeof(InvalidOperationException))] + public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() + { + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + IFolderInfo destinationFolder = new FolderInfo(); + destinationFolder.FolderPath = Constants.FOLDER_OtherValidFolderRelativePath; + destinationFolder.FolderMappingID = Constants.FOLDER_ValidFolderMappingID; + + this._pathUtils.Setup(pu => pu.FormatFolderPath(Constants.FOLDER_OtherValidFolderRelativePath)).Returns(Constants.FOLDER_OtherValidFolderRelativePath); + + this._mockFolderManager.Setup(mfm => mfm.FolderExists(It.IsAny(), It.IsAny())).Returns(false); + this._mockFolderManager.Setup(mfm => mfm.CanMoveBetweenFolderMappings(It.IsAny(), It.IsAny())).Returns(true); + this._mockFolderManager.Setup(mfm => mfm.IsMoveOperationValid(this._folderInfo.Object, destinationFolder, It.IsAny())).Returns(false); + + this._mockFolderManager.Object.MoveFolder(this._folderInfo.Object, destinationFolder); } // [Test] @@ -2181,92 +2181,92 @@ public void MoveFolder_Throws_When_Move_Operation_Is_Not_Valid() // _mockFolderManager.Verify(); // } - [Test] - public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() - { - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var destinationFolder = new FolderInfo(); - - var file1 = new FileInfo(); - var file2 = new FileInfo(); - var file3 = new FileInfo(); - - var files = new List { file1, file2, file3 }; - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); - - var fileManager = new Mock(); - FileManager.RegisterInstance(fileManager.Object); - - fileManager.Setup(fm => fm.MoveFile(It.IsAny(), destinationFolder)); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - - var folderMapping = new FolderMappingInfo(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); - - fileManager.Verify(fm => fm.MoveFile(It.IsAny(), destinationFolder), Times.Exactly(3)); - } - - [Test] - public void OverwriteFolder_Deletes_Source_Folder_In_Database() - { - var fileManager = new Mock(); - FileManager.RegisterInstance(fileManager.Object); - - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var files = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); - - var destinationFolder = new FolderInfo(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); - - var folderMapping = new FolderMappingInfo(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); - - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); - - this._mockFolderManager.Verify(); - } - - [Test] - public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_Editable() - { - var fileManager = new Mock(); - FileManager.RegisterInstance(fileManager.Object); - - this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); - this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); - this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); - - var files = new List(); - this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); - - var destinationFolder = new FolderInfo(); - - this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); - - var folderMapping = new FolderMappingInfo(); - - this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); - this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); - - var foldersToDelete = new SortedList(); - this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); - - Assert.AreEqual(1, foldersToDelete.Count); + [Test] + public void OverwriteFolder_Calls_MoveFile_For_Each_File_In_Source_Folder() + { + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var destinationFolder = new FolderInfo(); + + var file1 = new FileInfo(); + var file2 = new FileInfo(); + var file3 = new FileInfo(); + + var files = new List { file1, file2, file3 }; + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + + var fileManager = new Mock(); + FileManager.RegisterInstance(fileManager.Object); + + fileManager.Setup(fm => fm.MoveFile(It.IsAny(), destinationFolder)); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + + var folderMapping = new FolderMappingInfo(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + + fileManager.Verify(fm => fm.MoveFile(It.IsAny(), destinationFolder), Times.Exactly(3)); + } + + [Test] + public void OverwriteFolder_Deletes_Source_Folder_In_Database() + { + var fileManager = new Mock(); + FileManager.RegisterInstance(fileManager.Object); + + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var files = new List(); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + + var destinationFolder = new FolderInfo(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)).Verifiable(); + + var folderMapping = new FolderMappingInfo(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(false); + + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), new SortedList()); + + this._mockFolderManager.Verify(); + } + + [Test] + public void OverwriteFolder_Adds_Folder_To_FoldersToDelete_If_FolderMapping_Is_Editable() + { + var fileManager = new Mock(); + FileManager.RegisterInstance(fileManager.Object); + + this._folderInfo.Setup(fi => fi.PortalID).Returns(Constants.CONTENT_ValidPortalId); + this._folderInfo.Setup(fi => fi.FolderPath).Returns(Constants.FOLDER_ValidFolderRelativePath); + this._folderInfo.Setup(fi => fi.FolderMappingID).Returns(Constants.FOLDER_ValidFolderMappingID); + + var files = new List(); + this._mockFolderManager.Setup(mfm => mfm.GetFiles(this._folderInfo.Object, It.IsAny(), It.IsAny())).Returns(files); + + var destinationFolder = new FolderInfo(); + + this._mockFolderManager.Setup(mfm => mfm.DeleteFolder(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidFolderRelativePath)); + + var folderMapping = new FolderMappingInfo(); + + this._mockFolderManager.Setup(mfm => mfm.GetFolderMapping(It.IsAny>(), Constants.FOLDER_ValidFolderMappingID)).Returns(folderMapping); + this._mockFolderManager.Setup(mfm => mfm.IsFolderMappingEditable(folderMapping)).Returns(true); + + var foldersToDelete = new SortedList(); + this._mockFolderManager.Object.OverwriteFolder(this._folderInfo.Object, destinationFolder, new Dictionary(), foldersToDelete); + + Assert.AreEqual(1, foldersToDelete.Count); } // [Test] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs index d5f6a7ef03f..a24c2041dd7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/SecureFolderProviderTests.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class SecureFolderProviderTests - { + { private SecureFolderProvider _sfp; private Mock _folderInfo; private Mock _fileInfo; @@ -26,8 +26,8 @@ public class SecureFolderProviderTests private Mock _directoryWrapper; private Mock _folderManager; private Mock _fileManager; - private Mock _pathUtils; - + private Mock _pathUtils; + [SetUp] public void Setup() { @@ -51,8 +51,8 @@ public void Setup() public void TearDown() { MockComponentProvider.ResetContainer(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() @@ -78,8 +78,8 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) public void AddFile_Throws_On_Null_Content() { this._sfp.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() @@ -109,8 +109,8 @@ public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exist this._sfp.DeleteFile(this._fileInfo.Object); this._fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() @@ -157,8 +157,8 @@ public void ExistsFile_Returns_False_When_File_Does_Not_Exist() var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() @@ -213,8 +213,8 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileAttributes_Throws_On_Null_File() @@ -256,8 +256,8 @@ public void GetFileAttributes_Returns_Null_When_File_Does_Not_Exist() var result = this._sfp.GetFileAttributes(this._fileInfo.Object); Assert.IsNull(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() @@ -302,8 +302,8 @@ public void GetFiles_Return_Valid_FileNames_When_Folder_Contains_Files() var files = this._sfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedValues, files); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() @@ -349,7 +349,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } - + resultBytes = ms.ToArray(); } @@ -366,8 +366,8 @@ public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { @@ -377,8 +377,8 @@ public void GetImageUrl_Calls_IconControllerWrapper_IconURL() this._sfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderSecure", "32x32"), Times.Once()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetLastModificationTime_Throws_On_Null_File() @@ -422,8 +422,8 @@ public void GetLastModificationTime_Returns_Null_Date_When_File_Does_Not_Exist() var result = this._sfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedDate, result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() @@ -461,7 +461,7 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] + var subFolders = new[] { Constants.FOLDER_ValidSubFolderPath, Constants.FOLDER_OtherValidSubFolderPath, @@ -477,7 +477,7 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedSubFolders = new[] + var expectedSubFolders = new[] { Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_OtherValidSubFolderRelativePath, @@ -489,7 +489,7 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] + var subFolders = new[] { Constants.FOLDER_ValidSubFolderPath, Constants.FOLDER_OtherValidSubFolderPath, @@ -500,8 +500,8 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedSubFolders, result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void IsInSync_Throws_On_Null_File() @@ -533,8 +533,8 @@ public void IsInSync_Returns_True_When_File_Is_Not_In_Sync() var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() @@ -574,8 +574,8 @@ public void RenameFile_Does_Not_Call_FileWrapper_Move_When_FileNames_Are_Equal() this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); this._fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetFileAttributes_Throws_On_Null_File() @@ -593,16 +593,16 @@ public void SetFileAttributes_Calls_FileWrapper_SetAttributes() this._sfp.SetFileAttributes(this._fileInfo.Object, validFileAttributes); this._fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidSecureFilePath, validFileAttributes), Times.Once()); - } - + } + [Test] public void SupportsFileAttributes_Returns_True() { var result = this._sfp.SupportsFileAttributes(); Assert.IsTrue(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() @@ -656,6 +656,6 @@ public void UpdateFile_Calls_FileWrapper_Create() this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); this._fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidSecureFilePath), Times.Once()); - } + } } } 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 61a22a0ce6d..efee9d35458 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Folder/StandardFolderProviderTests.cs @@ -26,7 +26,7 @@ namespace DotNetNuke.Tests.Core.Providers.Folder [TestFixture] public class StandardFolderProviderTests - { + { private StandardFolderProvider _sfp; private Mock _folderInfo; private Mock _fileInfo; @@ -37,8 +37,8 @@ public class StandardFolderProviderTests private Mock _pathUtils; private Mock _portalControllerMock; private Mock _cryptographyProviderMock; - private Mock _localeControllerMock; - + private Mock _localeControllerMock; + [TestFixtureSetUp] public void FixtureSetup() { @@ -88,8 +88,8 @@ public void TearDown() MockComponentProvider.ResetContainer(); TestableGlobals.ClearInstance(); PortalController.ClearInstance(); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddFile_Throws_On_Null_Folder() @@ -99,25 +99,6 @@ public void AddFile_Throws_On_Null_Folder() this._sfp.AddFile(null, Constants.FOLDER_ValidFileName, stream.Object); } - private Dictionary GetPortalSettingsDictionaryMock() - { - var portalSettingsDictionary = new Dictionary(); - portalSettingsDictionary.Add("AddCachebusterToResourceUris", true.ToString()); - - return portalSettingsDictionary; - } - - private PortalSettings GetPortalSettingsMock() - { - var portalSettingsMock = new Mock(); - portalSettingsMock.Object.HomeDirectory = "/portals/" + Constants.CONTENT_ValidPortalId; - portalSettingsMock.Object.PortalId = Constants.CONTENT_ValidPortalId; - portalSettingsMock.Object.EnableUrlLanguage = false; - portalSettingsMock.Object.GUID = Guid.NewGuid(); - - return portalSettingsMock.Object; - } - [Test] [TestCase(null)] [TestCase("")] @@ -134,38 +115,38 @@ public void AddFile_Throws_On_NullOrEmpty_FileName(string fileName) public void AddFile_Throws_On_Null_Content() { this._sfp.AddFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, null); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeleteFile_Throws_On_Null_File() { this._sfp.DeleteFile(null); - } - - // [Test] - // public void DeleteFile_Calls_FileWrapper_Delete_When_File_Exists() - // { - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); - - // _sfp.DeleteFile(_fileInfo.Object); - - // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); - // } - - // [Test] - // public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exist() - // { - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); - - // _sfp.DeleteFile(_fileInfo.Object); - - // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); - // } + } + + // [Test] + // public void DeleteFile_Calls_FileWrapper_Delete_When_File_Exists() + // { + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(true); + + // _sfp.DeleteFile(_fileInfo.Object); + + // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Once()); + // } + + // [Test] + // public void DeleteFile_Does_Not_Call_FileWrapper_Delete_When_File_Does_Not_Exist() + // { + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _fileWrapper.Setup(fw => fw.Exists(Constants.FOLDER_ValidFilePath)).Returns(false); + + // _sfp.DeleteFile(_fileInfo.Object); + + // _fileWrapper.Verify(fw => fw.Delete(Constants.FOLDER_ValidFilePath), Times.Never()); + // } [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFile_Throws_On_Null_Folder() @@ -212,8 +193,8 @@ public void ExistsFile_Returns_False_When_File_Does_Not_Exist() var result = this._sfp.FileExists(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void ExistsFolder_Throws_On_Null_FolderMapping() @@ -268,8 +249,8 @@ public void ExistsFolder_Returns_False_When_Folder_Does_Not_Exist() var result = this._sfp.FolderExists(Constants.FOLDER_ValidFolderRelativePath, folderMapping); Assert.IsFalse(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileAttributes_Throws_On_Null_File() @@ -310,8 +291,8 @@ public void GetFileAttributes_Returns_Null_When_File_Does_Not_Exist() var result = this._sfp.GetFileAttributes(this._fileInfo.Object); Assert.IsNull(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFiles_Throws_On_Null_Folder() @@ -356,8 +337,8 @@ public void GetFiles_Returns_Valid_FileNames_When_Folder_Contains_Files() var files = this._sfp.GetFiles(this._folderInfo.Object); CollectionAssert.AreEqual(expectedValues, files); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetFileStream_Throws_On_Null_Folder() @@ -403,7 +384,7 @@ public void GetFileStream_Returns_Valid_Stream_When_File_Exists() { ms.Write(buffer, 0, read); } - + resultBytes = ms.ToArray(); } @@ -420,8 +401,8 @@ public void GetFileStream_Returns_Null_When_File_Does_Not_Exist() var result = this._sfp.GetFileStream(this._folderInfo.Object, Constants.FOLDER_ValidFileName); Assert.IsNull(result); - } - + } + [Test] public void GetImageUrl_Calls_IconControllerWrapper_IconURL() { @@ -431,8 +412,8 @@ public void GetImageUrl_Calls_IconControllerWrapper_IconURL() this._sfp.GetFolderProviderIconPath(); iconControllerWrapper.Verify(icw => icw.IconURL("FolderStandard", "32x32"), Times.Once()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetLastModificationTime_Throws_On_Null_File() @@ -475,8 +456,8 @@ public void GetLastModificationTime_Returns_Null_Date_When_File_Does_Not_Exist() var result = this._sfp.GetLastModificationTime(this._fileInfo.Object); Assert.AreEqual(expectedDate, result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void GetSubFolders_Throws_On_Null_FolderMapping() @@ -514,7 +495,7 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] + var subFolders = new[] { Constants.FOLDER_ValidSubFolderPath, Constants.FOLDER_OtherValidSubFolderPath, @@ -530,7 +511,7 @@ public void GetSubFolders_Count_Equals_DirectoryWrapper_GetDirectories_Count() [Test] public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() { - var expectedSubFolders = new[] + var expectedSubFolders = new[] { Constants.FOLDER_ValidSubFolderRelativePath, Constants.FOLDER_OtherValidSubFolderRelativePath, @@ -542,7 +523,7 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_ValidSubFolderPath)).Returns(Constants.FOLDER_ValidSubFolderRelativePath); this._pathUtils.Setup(pu => pu.GetRelativePath(Constants.CONTENT_ValidPortalId, Constants.FOLDER_OtherValidSubFolderPath)).Returns(Constants.FOLDER_OtherValidSubFolderRelativePath); - var subFolders = new[] + var subFolders = new[] { Constants.FOLDER_ValidSubFolderPath, Constants.FOLDER_OtherValidSubFolderPath, @@ -553,8 +534,8 @@ public void GetSubFolders_Returns_Valid_SubFolders_When_Folder_Is_Not_Empty() var result = this._sfp.GetSubFolders(Constants.FOLDER_ValidFolderRelativePath, folderMapping).ToList(); CollectionAssert.AreEqual(expectedSubFolders, result); - } - + } + [Test] public void GetFileUrl_WhenCurrentPortalSettingsReturnsNull_DontThrow() { @@ -630,8 +611,8 @@ public void GetFileUrl_ReturnsLinkclickUrl_WhenFileUrlContainsInvalidCharactes(s // Assert Assert.IsTrue(fileUrl.ToLowerInvariant().Contains("linkclick")); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void IsInSync_Throws_On_Null_File() @@ -663,8 +644,8 @@ public void IsInSync_Returns_True_When_File_Is_Not_In_Sync() var result = sfp.Object.IsInSync(this._fileInfo.Object); Assert.IsTrue(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void RenameFile_Throws_On_Null_File() @@ -704,34 +685,34 @@ public void RenameFile_Does_Not_Call_FileWrapper_Move_When_FileNames_Are_Equal() this._sfp.RenameFile(this._fileInfo.Object, Constants.FOLDER_ValidFileName); this._fileWrapper.Verify(fw => fw.Move(It.IsAny(), It.IsAny()), Times.Never()); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetFileAttributes_Throws_On_Null_File() { this._sfp.SetFileAttributes(null, FileAttributes.Archive); - } - - // [Test] - // public void SetFileAttributes_Calls_FileWrapper_SetAttributes() - // { - // const FileAttributes validFileAttributes = FileAttributes.Archive; - - // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); - - // _sfp.SetFileAttributes(_fileInfo.Object, validFileAttributes); - - // _fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidFilePath, validFileAttributes), Times.Once()); - // } + } + + // [Test] + // public void SetFileAttributes_Calls_FileWrapper_SetAttributes() + // { + // const FileAttributes validFileAttributes = FileAttributes.Archive; + + // _fileInfo.Setup(fi => fi.PhysicalPath).Returns(Constants.FOLDER_ValidFilePath); + + // _sfp.SetFileAttributes(_fileInfo.Object, validFileAttributes); + + // _fileWrapper.Verify(fw => fw.SetAttributes(Constants.FOLDER_ValidFilePath, validFileAttributes), Times.Once()); + // } [Test] public void SupportsFileAttributes_Returns_True() { var result = this._sfp.SupportsFileAttributes(); Assert.IsTrue(result); - } - + } + [Test] [ExpectedException(typeof(ArgumentNullException))] public void UpdateFile_Throws_On_Null_Folder() @@ -785,6 +766,25 @@ public void UpdateFile_Calls_FileWrapper_Create() this._sfp.UpdateFile(this._folderInfo.Object, Constants.FOLDER_ValidFileName, stream.Object); this._fileWrapper.Verify(fw => fw.Create(Constants.FOLDER_ValidFilePath), Times.Once()); - } + } + + private Dictionary GetPortalSettingsDictionaryMock() + { + var portalSettingsDictionary = new Dictionary(); + portalSettingsDictionary.Add("AddCachebusterToResourceUris", true.ToString()); + + return portalSettingsDictionary; + } + + private PortalSettings GetPortalSettingsMock() + { + var portalSettingsMock = new Mock(); + portalSettingsMock.Object.HomeDirectory = "/portals/" + Constants.CONTENT_ValidPortalId; + portalSettingsMock.Object.PortalId = Constants.CONTENT_ValidPortalId; + portalSettingsMock.Object.EnableUrlLanguage = false; + portalSettingsMock.Object.GUID = Guid.NewGuid(); + + return portalSettingsMock.Object; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs index cfc39211bca..1ef084f7b17 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Membership/MembershipProviderTests.cs @@ -118,7 +118,7 @@ private static UserInfo CreateNewUser() UserInfo user = null; - Assert.DoesNotThrow( + Assert.DoesNotThrow( () => { user = new UserInfo 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 cd8dd5ba728..18301db1962 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Providers/Permissions/PermissionTests.cs @@ -233,7 +233,7 @@ public void PortalSecurity_IsInRoles_NonAdminUser_True_WhenRoleIsOwnerRoleAndRol // Act and Assert Assert.IsTrue(PortalSecurity.IsInRoles(user, portalSettings, roles)); } - + [Test] public void PortalSecurity_IsInRoles_NonAdminUser_False_WhenRoleIsOwnerRoleAndRoleEntityIsNotUser() { @@ -269,7 +269,7 @@ public void PortalSecurity_IsInRoles_NonAdmin_In_Deny_Role_Is_False() // var permissionProvider = new CorePermissionProvider(); // Assert.IsTrue(permissionProvider.HasModuleAccess(SecurityAccessLevel.Anonymous, "", new ModuleInfo())); // } - + // [Test] // public void CorePermissionProvider_HasModuleAccess_SecurityLevelAnonymous_Is_Always_True() // { @@ -325,7 +325,7 @@ private void CreateUser(bool isSuperUser, IEnumerable Roles) { userRoles.Add(new UserRoleInfo() { RoleName = role, Status = RoleStatus.Approved }); } - + mockRoleProvider.Setup(rp => rp.GetUserRoles(It.Is(u => u.UserID == UserId), It.IsAny())).Returns(userRoles); var simulator = new Instance.Utilities.HttpSimulator.HttpSimulator(this.WebsitePhysicalAppPath); simulator.SimulateRequest(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs index 8c55d236b50..db68b59c197 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/RetryableActionTests.cs @@ -102,21 +102,19 @@ public void GoToSleep(int delay) internal class ActionMonitor { - private int _failuresRemaining; private readonly List _callTimes = new List(); + private int _failuresRemaining; - public ActionMonitor() - : this(0) - { - } + public ActionMonitor() + : this(0) + { + } public ActionMonitor(int failureCount) { this._failuresRemaining = failureCount; } - public int TimesCalled { get; private set; } - public IList CallTime { get @@ -125,6 +123,8 @@ public IList CallTime } } + public int TimesCalled { get; private set; } + public void Action() { this._callTimes.Add(DateTime.Now); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs index fa4d275f24b..7946e9b9cc9 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Security/PortalSecurity/PortalSecurityTest.cs @@ -9,17 +9,17 @@ namespace DotNetNuke.Tests.Core.Security.PortalSecurity [TestFixture] public class PortalSecurityTest - { + { [SetUp] public void Setup() { - } - + } + [TearDown] public void TearDown() { - } - + } + [TestCase("", " ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoScripting | @@ -66,7 +66,7 @@ public void TearDown() [TestCase("", "<source></source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase( + [TestCase( "Hi this is personal Test for source tag ", "<source>Hi this is personal Test for source tag</source> ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | @@ -74,7 +74,7 @@ public void TearDown() [TestCase("{Upper case}", "<SOURCE>{Upper case}</SOURCE>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase( + [TestCase( "Source with attribute", "<source src="https://google.com">Source with attribute</source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup | @@ -82,13 +82,13 @@ public void TearDown() [TestCase("", "<source></source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] - [TestCase( + [TestCase( "Hi this is personal Test for source tag ", "<source>Hi this is personal Test for source tag</source> ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] [TestCase("Upper case", "<SOURCE>Upper case</SOURCE>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] - [TestCase( + [TestCase( "Source with attribute", "<source src="https://google.com">Source with attribute</source>", DotNetNuke.Security.PortalSecurity.FilterFlag.NoMarkup)] @@ -104,13 +104,13 @@ public void TearDown() [TestCase("", "", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase( + [TestCase( "Hi this is personal Test for source tag ", "Hi this is personal Test for source tag ", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] [TestCase("Upper case", "Upper case", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] - [TestCase( + [TestCase( "Source with attribute", "Source with attribute", DotNetNuke.Security.PortalSecurity.FilterFlag.NoAngleBrackets)] @@ -125,6 +125,6 @@ public void Html_Source_Tag_Should_Not_Be_Allowed(string html, string expectedOu // Assert Assert.AreEqual(filterOutput, expectedOutput); - } + } } } 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 ba7a2a015b0..0e58a1a8e62 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/ClientCapability/FacebookRequestControllerTests.cs @@ -18,9 +18,9 @@ namespace DotNetNuke.Tests.Core.Services.ClientCapability ///
    [TestFixture] public class FacebookRequestControllerTests - { - private IDictionary _requestDics; - + { + private IDictionary _requestDics; + [SetUp] public void SetUp() { @@ -29,11 +29,11 @@ public void SetUp() this._requestDics.Add("Valid", "vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsIjAiOiJwYXlsb2FkIiwidXNlcl9pZCI6ICIxIiwiZXhwaXJlcyI6IjEzMjUzNzU5OTkifQ=="); this._requestDics.Add("ValidForAPage", "ylleuHAFR0DTpZ3bNr0fjMp7X7le_j8_HN3ONpbbgkk.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTMxOTQ4ODEwNywicGFnZSI6eyJpZCI6IjEzMDYzNDU0MDM3MjcyOCIsImxpa2VkIjpmYWxzZSwiYWRtaW4iOnRydWV9LCJ1c2VyIjp7ImNvdW50cnkiOiJjYSIsImxvY2FsZSI6ImVuX1VTIiwiYWdlIjp7Im1pbiI6MjF9fX0"); - + // json data "{\"algorithm\":\"HMAC-SHA256\",\"issued_at\":1319488107,\"page\":{\"id\":\"130634540372728\",\"liked\":false,\"admin\":true},\"user\":{\"country\":\"ca\",\"locale\":\"en_US\",\"age\":{\"min\":21}}}" this._requestDics.Add("Invalid", "Invalid Content"); - } - + } + [Test] public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Empty_Request_String() { @@ -114,7 +114,7 @@ public void FacebookRequestController_GetFacebookDetailsFromRequest_With_Post_Va var request = FacebookRequestController.GetFacebookDetailsFromRequest(httpRequest); Assert.AreEqual(true, request.IsValid); - } + } /// /// method for converting a System.DateTime value to a UNIX Timestamp. @@ -127,8 +127,8 @@ private static DateTime ConvertToTimestamp(long value) // the Unix Epoch 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); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs index 18590dc879b..8b07ef76f3f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/CoreCryptographyProviderTests.cs @@ -27,7 +27,7 @@ public void EncryptData_Should_Return_Encrypted_String() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - + // Arrange // Act @@ -42,7 +42,7 @@ public void DecryptData_Should_Return_Empty_String_If_Data_Is_Not_Encypted() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - + // Arrange // Act diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs index d4aa78800cd..ff8602b56a4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/CryptographyProviders/FipsCompilanceCryptographyProviderTests.cs @@ -27,7 +27,7 @@ public void EncryptData_Should_Return_Encrypted_String() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - + // Arrange // Act @@ -42,7 +42,7 @@ public void DecryptData_Should_Return_Empty_String_If_Data_Is_Not_Encypted() { var message = "Hello world!"; var encryptionKey = Config.GetDecryptionkey(); - + // Arrange // Act diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs index 06119c8b4fc..553bf8217f2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/HtmlUtilsTest.cs @@ -46,8 +46,8 @@ public void DNN_12926_IsHtml_Detection() [TearDown] public void TearDown() { - } - + } + [Test] public void HtmlUtils_CleanWithTagInfo_Should_Return_Clean_Content_With_Attribute_Values() { @@ -58,7 +58,7 @@ public void HtmlUtils_CleanWithTagInfo_Should_Return_Clean_Content_With_Attribut // Act object retValue = HtmlUtils.CleanWithTagInfo(HtmlStr, Filters, true); - + // Assert Assert.AreEqual(this._expected, retValue); @@ -75,7 +75,7 @@ public void HtmlUtils_CleanWithTagInfo_Should_Return_Clean_Content_Without_Attri // Act object retValue = HtmlUtils.CleanWithTagInfo(HtmlStr, " ", true); - + // Assert Assert.AreEqual(this._expected, retValue); @@ -93,7 +93,7 @@ public void HtmlUtils_StripUnspecifiedTags_Should_Return_Attribute_Values() // Act object retValue = HtmlUtils.StripUnspecifiedTags(HtmlStr, Filters, false); - + // Assert Assert.AreEqual(this._expected, retValue); @@ -110,12 +110,12 @@ public void HtmlUtils_StripUnspecifiedTags_Should_Not_Return_Attribute_Values() // Act object retValue = HtmlUtils.StripUnspecifiedTags(HtmlStr, " ", false); - + // Assert Assert.AreEqual(this._expected, retValue); // TearDown this.TearDown(); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs index acbd67a8543..5f0aa904e1e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Localization/LocalizationTests.cs @@ -16,9 +16,9 @@ namespace DotNetNuke.Tests.Core.Services.Localization [TestFixture] public class LocalizationTests { + private readonly string[] _standardCultureCodes = new[] { "en-US", "de-DE", "fr-CA", "Lt-sr-SP", "kok-IN" }; private Mock _mockHttpContext; private HttpContextBase _httpContext; - private readonly string[] _standardCultureCodes = new[] { "en-US", "de-DE", "fr-CA", "Lt-sr-SP", "kok-IN" }; [SetUp] public void Setup() @@ -31,7 +31,7 @@ public void Setup() public void NoMatchReturnsFallback() { const string fallback = "fallback"; - + // Arrange // Act @@ -46,7 +46,7 @@ public void NoMatchReturnsFallback() public void CultureCodesCannotBeNull() { // Arrange - + // Act TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(null); @@ -58,7 +58,7 @@ public void CultureCodesCannotBeNull() public void FallBackCannotBeNull() { // Arrange - + // Act TestableLocalization.Instance.BestCultureCodeBasedOnBrowserLanguages(new string[0], null); @@ -116,7 +116,7 @@ public void PerfectMatchPreferredToFirstMatch() // Assert Assert.AreEqual(ret, "fr-FR"); } - + [Test] [TestCase("My/Path/To/File with.locale-extension")] [TestCase("My\\Path\\To\\File with.locale-extension")] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs index 03032d7a0d5..27124f48d3c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/PreviewProfileControllerTests.cs @@ -20,11 +20,11 @@ namespace DotNetNuke.Tests.Core.Services.Mobile /// [TestFixture] public class PreviewProfileControllerTests - { + { private Mock _dataProvider; - private DataTable _dtProfiles; - + private DataTable _dtProfiles; + [SetUp] public void SetUp() { @@ -46,7 +46,7 @@ public void SetUp() this._dtProfiles.PrimaryKey = new[] { pkCol }; this._dataProvider.Setup(d => - d.SavePreviewProfile( + d.SavePreviewProfile( It.IsAny(), It.IsAny(), It.IsAny(), @@ -106,8 +106,8 @@ public void SetUp() this._dtProfiles.Rows.Remove(rows[0]); } }); - } - + } + [Test] public void PreviewProfileController_Save_Valid_Profile() { @@ -120,10 +120,10 @@ public void PreviewProfileController_Save_Valid_Profile() { affectedCount++; } - + Assert.AreEqual(1, affectedCount); } - + [Test] public void PreviewProfileController_GetProfilesByPortal_With_Valid_PortalID() { @@ -143,8 +143,8 @@ public void PreviewProfileController_Delete_With_ValidID() IList list = new PreviewProfileController().GetProfilesByPortal(0); Assert.AreEqual(2, list.Count); - } - + } + private IDataReader GetProfilesCallBack(int portalId) { var dtCheck = this._dtProfiles.Clone(); @@ -164,6 +164,6 @@ private void PrepareData() this._dtProfiles.Rows.Add(4, 1, "R4", 640, 480, string.Empty, 4); this._dtProfiles.Rows.Add(5, 1, "R5", 640, 480, string.Empty, 5); this._dtProfiles.Rows.Add(6, 1, "R6", 640, 480, string.Empty, 6); - } + } } } 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 03fd64ba6e6..1e76702fa13 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Mobile/RedirectionControllerTests.cs @@ -34,17 +34,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; - private Mock _mockHostController; - - private DataTable _dtRedirections; - private DataTable _dtRules; 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)"; @@ -82,8 +74,16 @@ public class RedirectionControllerTests private const string DisableMobileRedirectCookieName = "disablemobileredirect"; private const string DisableRedirectPresistCookieName = "disableredirectpresist"; - private const string DisableMobileRedirectQueryStringName = "nomo"; - + private const string DisableMobileRedirectQueryStringName = "nomo"; + + private Mock _dataProvider; + private RedirectionController _redirectionController; + private Mock _clientCapabilityProvider; + private Mock _mockHostController; + + private DataTable _dtRedirections; + private DataTable _dtRules; + [SetUp] public void SetUp() { @@ -124,16 +124,16 @@ public void TearDown() this._dtRedirections.Dispose(); this._dtRedirections = null; } - + if (this._dtRules != null) { this._dtRules.Dispose(); this._dtRules = null; } - + ComponentFactory.Container = null; } - + [Test] public void RedirectionController_Save_Valid_Redirection() { @@ -146,7 +146,7 @@ public void RedirectionController_Save_Valid_Redirection() { affectedCount++; } - + Assert.AreEqual(1, affectedCount); } @@ -164,22 +164,13 @@ public void RedirectionController_Save_ValidRedirection_With_Rules() { affectedCount++; } - + Assert.AreEqual(1, affectedCount); var getRe = this._redirectionController.GetRedirectionsByPortal(Portal0)[0]; 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() { @@ -231,8 +222,8 @@ public void RedirectionController_PurgeInvalidRedirections_DoPurgeRuleForDeletet this._dtRedirections.Rows.Add(new object[] { 1, Portal0, "R1", (int)RedirectionType.MobilePhone, SortOrder1, HomePageOnPortal0, IncludeChildTabsFlag, (int)TargetType.Tab, DeletedPageOnSamePortal2, EnabledFlag }); this._redirectionController.PurgeInvalidRedirections(0); Assert.AreEqual(0, this._redirectionController.GetRedirectionsByPortal(0).Count); - } - + } + [Test] [ExpectedException(typeof(ArgumentException))] public void RedirectionController_GetRedirectionUrl_Throws_On_Null_UserAgent() @@ -350,8 +341,8 @@ public void RedirectionController_GetRedirectionUrl_Returns_EmptyString_When_Not { this.PrepareOperaBrowserOnIPhoneOSRedirectionRule(); Assert.AreEqual(string.Empty, this._redirectionController.GetRedirectUrl(iphoneUserAgent, Portal0, 1)); - } - + } + [Test] public void RedirectionController_GetFullSiteUrl_With_NoRedirections() { @@ -387,8 +378,8 @@ public void RedirectionController_GetFullSiteUrl_When_Redirect_To_DifferentUrl() var url = this._redirectionController.GetFullSiteUrl(Portal1, AnotherPageOnSamePortal); Assert.AreEqual(string.Empty, url); - } - + } + [Test] public void RedirectionController_GetMobileSiteUrl_With_NoRedirections() { @@ -442,8 +433,8 @@ public void RedirectionController_GetMobileSiteUrl_When_Redirect_To_DifferentUrl var url = this._redirectionController.GetMobileSiteUrl(Portal1, AnotherPageOnSamePortal); Assert.AreEqual(string.Empty, url); - } - + } + [Test] public void RedirectionController_IsRedirectAllowedForTheSession_In_Normal_Action() { @@ -481,8 +472,17 @@ public void RedirectionController_IsRedirectAllowedForTheSession_With_Nonmo_Para app.Context.Request.QueryString.Add(DisableMobileRedirectQueryStringName, "0"); Assert.IsTrue(this._redirectionController.IsRedirectAllowedForTheSession(app)); - } - + } + + 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; + } + private void SetupDataProvider() { this._dataProvider.Setup(d => d.GetProviderPath()).Returns(string.Empty); @@ -510,7 +510,7 @@ private void SetupDataProvider() this._dtRules.PrimaryKey = new[] { pkCol1 }; this._dataProvider.Setup(d => - d.SaveRedirection( + d.SaveRedirection( It.IsAny(), It.IsAny(), It.IsAny(), @@ -580,7 +580,7 @@ private void SetupDataProvider() } }); - this._dataProvider.Setup(d => d.SaveRedirectionRule( + this._dataProvider.Setup(d => d.SaveRedirectionRule( It.IsAny(), It.IsAny(), It.IsAny(), @@ -694,15 +694,15 @@ private IDataReader GetPortalCallBack(int portalId, string culture) } int homePage = 55; - if (portalId == Portal0) - { - homePage = HomePageOnPortal0; - } - else if (portalId == Portal1) - { - homePage = HomePageOnPortal1; - } - + if (portalId == Portal0) + { + homePage = HomePageOnPortal0; + } + else if (portalId == Portal1) + { + homePage = HomePageOnPortal1; + } + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright 2011 by DotNetNuke Corporation", null, "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", "-1", "2011-08-25 07:34:29", culture); return table.CreateDataReader(); @@ -770,7 +770,7 @@ private IDataReader GetTabModulesCallBack(int tabId) { table.Columns.Add(col); } - + table.Columns["ModuleID"].DataType = typeof(int); var portalId = tabId == HomePageOnPortal0 ? Portal0 : Portal1; @@ -940,10 +940,10 @@ private HttpApplication GenerateApplication() return app; } - + private string NavigateUrl(int tabId) { return string.Format("/Default.aspx?tabid={0}", tabId); - } + } } } 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 dba880e0079..33a1909f4fd 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/Services/Tokens/PropertyAccessTests.cs @@ -81,7 +81,7 @@ public void DateTimePropertyAcccess_GetProperty_Sets_PropertyNotFound(string pro // Arrange var dtPropertyAccess = new DateTimePropertyAccess(); var accessingUser = new UserInfo { Profile = new UserProfile { PreferredTimeZone = TimeZoneInfo.Local } }; - + // Act bool propertyNotFound = false; string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, CultureInfo.InvariantCulture, @@ -124,7 +124,7 @@ public void DateTimePropertyAcccess_GetProperty_Returns_Correct_String_For_Cultu expected = DateTime.Now.ToUniversalTime().ToString("g", culture); break; } - + // Act bool propertyNotFound = false; string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, culture, @@ -143,38 +143,38 @@ 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); - - 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; - } - - // Act - bool propertyNotFound = false; - string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, - accessingUser, Scope.DefaultSettings, ref propertyNotFound); - - // Assert - Assert.AreEqual(expected, propertyValue); + 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; + } + + // Act + bool propertyNotFound = false; + string propertyValue = dtPropertyAccess.GetProperty(propertyName, format, culture, + accessingUser, Scope.DefaultSettings, ref propertyNotFound); + + // Assert + Assert.AreEqual(expected, propertyValue); } [Test] @@ -185,10 +185,10 @@ 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); @@ -213,7 +213,7 @@ public void DateTimePropertyAcccess_GetProperty_Adjusts_For_TimeZone(string prop expected = DateTime.Now.ToUniversalTime().ToString("g", culture); break; } - + // Act bool propertyNotFound = false; string propertyValue = dtPropertyAccess.GetProperty(propertyName, string.Empty, culture, diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs index 14c88f5518f..7c27302d92a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Core/TabCollectionTest.cs @@ -23,7 +23,7 @@ public void SetUp() ComponentFactory.Container = new SimpleContainer(); MockComponentProvider.CreateDataCacheProvider(); } - + [Test] public void DNN_13659_WithTabName_NullTabName() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs index c7a0f97ae21..a5606afed99 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/DataUtil.cs @@ -14,7 +14,7 @@ namespace DotNetNuke.Tests.Data using DotNetNuke.Tests.Utilities; public class DataUtil - { + { public static void CreateDatabase(string databaseName) { if (File.Exists(databaseName)) @@ -96,12 +96,12 @@ public static void SetUpDatabase(int count) { index = 0; } - + ExecuteNonQuery(Constants.PETAPOCO_DatabaseName, string.Format(Constants.PETAPOCO_InsertDogRow, _dogNames[index], _dogAges[index])); index++; } - } - + } + private static TReturn ExecuteQuery(string databaseName, string sqlScript, Func command) { using (var connection = new SqlCeConnection(GetConnectionString(databaseName))) diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs index 4d7bbbeb947..186e2310d7c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Fakes/FakeDataProvider.cs @@ -14,8 +14,8 @@ internal class FakeDataProvider : DataProvider public FakeDataProvider(Dictionary settings) { this.Settings = settings; - } - + } + public override bool IsConnectionValid { get { throw new System.NotImplementedException(); } @@ -122,6 +122,6 @@ public override IDataReader ExecuteSQLTemp(string connectionString, string sql, public override IDataReader ExecuteSQLTemp(string connectionString, string sql, int timeoutSec, out string errorMessage) { throw new System.NotImplementedException(); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs index f52a908e91f..630fc48e5e3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableCat.cs @@ -14,9 +14,9 @@ namespace DotNetNuke.Tests.Data.Models public class CacheableCat { public int? Age { get; set; } - + public int ModuleId { get; set; } - + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs index cc2a7cc398e..bfb4bfe87e7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/CacheableDog.cs @@ -12,9 +12,9 @@ namespace DotNetNuke.Tests.Data.Models public class CacheableDog { public int? Age { get; set; } - + public int ID { get; set; } - + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs index b1c2704c47f..f031c368cb0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Cat.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Tests.Data.Models public class Cat { public int? Age { get; set; } - + public int ModuleId { get; set; } - + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs index bd8a7e94858..6be02eff5c5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Dog.cs @@ -7,9 +7,9 @@ namespace DotNetNuke.Tests.Data.Models public class Dog { public int? Age { get; set; } - + public int ID { get; set; } - + public string Name { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs index 6bf7e04588d..848d1da979f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/Models/Person.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Tests.Data.Models public class Person { public int? Age { get; set; } - + public int ID { get; set; } [ColumnName(Constants.COLUMNNAME_PersonName)] diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs index 781972ca453..2547cccadff 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Data/RepositoryBaseTests.cs @@ -29,8 +29,8 @@ public class RepositoryBaseTests public void SetUp() { MockComponentProvider.ResetContainer(); - } - + } + [Test] public void RepositoryBase_Constructor_Sets_CacheArgs_Null_If_Not_Cacheable() { @@ -200,8 +200,8 @@ public void RepositoryBase_Constructor_Sets_Scope_If_Cacheable_And_Scoped() // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); - } - + } + [Test] public void RepositoryBase_Initialize_Sets_CacheArgs_Null_If_Not_Cacheable() { @@ -383,8 +383,8 @@ public void RepositoryBase_Initialize_Sets_Scope_If_Cacheable_And_Scoped() // Assert var baseRepo = repo as RepositoryBase; Assert.AreEqual(Constants.CACHE_ScopeModule, Util.GetPrivateMember, string>(baseRepo, "Scope")); - } - + } + [Test] public void RepositoryBase_Delete_Clears_Cache_If_Cacheable() { @@ -448,8 +448,8 @@ public void RepositoryBase_Delete_Calls_DeleteInternal() // Assert mockRepository.Protected().Verify("DeleteInternal", Times.Once(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_Get_Checks_Cache_If_Cacheable() { @@ -565,8 +565,8 @@ public void RepositoryBase_Get_Does_Not_Call_GetAllInternal_If_Cacheable_And_Cac // Assert mockRepository.Protected().Verify("GetInternal", Times.Never()); - } - + } + [Test] public void RepositoryBase_Get_Overload_Checks_Cache_If_Cacheable_And_Scoped() { @@ -678,8 +678,8 @@ public void RepositoryBase_Get_Overload_Does_Not_Call_GetAllByScopeInternal_If_C // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Never(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_GetById_Checks_Cache_If_Cacheable() { @@ -775,8 +775,8 @@ public void RepositoryBase_GetById_Does_Not_Call_GetByIdInternal_If_Cacheable_An // Assert mockRepository.Protected().Verify("GetByIdInternal", Times.Never(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_GetById_Overload_Checks_Cache_If_Cacheable_And_Scoped() { @@ -818,8 +818,8 @@ public void RepositoryBase_GetById_Overload_Throws__If_Cacheable_But_Not_Scoped( // Act, Assert Assert.Throws(() => mockRepository.Object.GetById(Constants.PETAPOCO_ValidDogId, Constants.MODULE_ValidId)); - } - + } + [Test] public void RepositoryBase_GetPage_Checks_Cache_If_Cacheable() { @@ -916,8 +916,8 @@ public void RepositoryBase_GetPage_Does_Not_Call_GetAllByPageInternal_If_Cacheab // Assert mockRepository.Protected().Verify>("GetPageInternal", Times.Never(), ItExpr.IsAny(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_GetPage_Overload_Checks_Cache_If_Cacheable_And_Scoped() { @@ -1033,8 +1033,8 @@ public void RepositoryBase_GetPage_Overload_Does_Not_Call_GetAllByScopeInternal_ // Assert mockRepository.Protected().Verify>("GetByScopeInternal", Times.Never(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_Insert_Clears_Cache_If_Cacheable() { @@ -1098,8 +1098,8 @@ public void RepositoryBase_Insert_Calls_InsertInternal() // Assert mockRepository.Protected().Verify("InsertInternal", Times.Once(), ItExpr.IsAny()); - } - + } + [Test] public void RepositoryBase_Update_Clears_Cache_If_Cacheable() { @@ -1163,8 +1163,8 @@ public void RepositoryBase_Update_Calls_UpdateInternal() // Assert mockRepository.Protected().Verify("UpdateInternal", Times.Once(), ItExpr.IsAny()); - } - - // ReSharper restore InconsistentNaming + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs index 1c5a635c4fa..f49658d346c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoDataContextTests.cs @@ -16,11 +16,11 @@ namespace DotNetNuke.Tests.Data [TestFixture] public class PetaPocoDataContextTests - { + { private const string connectionStringName = "PetaPoco"; - private const string tablePrefix = "dnn_"; - - // ReSharper disable InconsistentNaming + private const string tablePrefix = "dnn_"; + + // ReSharper disable InconsistentNaming [SetUp] public void SetUp() { @@ -29,8 +29,8 @@ public void SetUp() [TearDown] public void TearDown() { - } - + } + [Test] public void PetaPocoDataContext_Constructors_Throw_On_Null_ConnectionString() { @@ -114,8 +114,8 @@ public void PetaPocoDataContext_Constructor_Initialises_Database_Property_With_C string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; Assert.AreEqual(connectionString, Util.GetPrivateMember(db, "_connectionString")); - } - + } + [Test] public void PetaPocoDataContext_BeginTransaction_Increases_Database_Transaction_Count() { @@ -130,8 +130,8 @@ public void PetaPocoDataContext_BeginTransaction_Increases_Database_Transaction_ // Assert Assert.AreEqual(transactionDepth + 1, Util.GetPrivateMember(db, "_transactionDepth")); - } - + } + [Test] public void PetaPocoDataContext_Commit_Decreases_Database_Transaction_Count() { @@ -162,8 +162,8 @@ public void PetaPocoDataContext_Commit_Sets_Database_TransactionCancelled_False( // Assert Assert.AreEqual(false, Util.GetPrivateMember(db, "_transactionCancelled")); - } - + } + [Test] public void PetaPocoDataContext_RollbackTransaction_Decreases_Database_Transaction_Count() { @@ -194,8 +194,8 @@ public void PetaPocoDataContext_RollbackTransaction_Sets_Database_TransactionCan // Assert Assert.AreEqual(true, Util.GetPrivateMember(db, "_transactionCancelled")); - } - + } + [Test] public void PetaPocoDataContext_GetRepository_Returns_Repository() { @@ -250,8 +250,8 @@ public void PetaPocoDataContext_GetRepository_Uses_FluentMapper_If_FluentMapper_ // Assert Assert.IsInstanceOf(Util.GetPrivateMember, IMapper>(repo, "_mapper")); Assert.IsInstanceOf>(Util.GetPrivateMember, IMapper>(repo, "_mapper")); - } - - // ReSharper restore InconsistentNaming + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs index dfa1ce753ae..a4e98438694 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoIntegrationTests.cs @@ -21,10 +21,10 @@ namespace DotNetNuke.Tests.Data public class PetaPocoIntegrationTests { private const string ConnectionStringName = "PetaPoco"; - - private Dictionary _mappers; - - // ReSharper disable InconsistentNaming + + private Dictionary _mappers; + + // ReSharper disable InconsistentNaming [SetUp] public void SetUp() { @@ -59,7 +59,7 @@ public void SetUp() public void TearDown() { DataUtil.DeleteDatabase(Constants.PETAPOCO_DatabaseName); - } + } [Test] public void PetaPoco_Add_Inserts_Item() @@ -67,10 +67,10 @@ 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)) @@ -82,7 +82,7 @@ public void PetaPoco_Add_Inserts_Item() } // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); @@ -94,10 +94,10 @@ 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)) @@ -109,7 +109,7 @@ public void PetaPoco_Add_Inserts_Item_Using_FluentMapper() } // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); @@ -121,11 +121,11 @@ 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)) @@ -137,7 +137,7 @@ public void PetaPoco_Delete_Deletes_Item() } // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); @@ -149,11 +149,11 @@ 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)) @@ -165,7 +165,7 @@ public void PetaPoco_Delete_Deletes_Item_Using_FluentMapper() } // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); @@ -186,7 +186,7 @@ public void PetaPoco_Delete_Overload_Deletes_Item() } // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); @@ -231,7 +231,7 @@ public void PetaPoco_Get_Returns_All_Items(int count) // Act dogs = dogRepository.Get(); } - + // Assert Assert.AreEqual(count, dogs.Count()); } @@ -253,7 +253,7 @@ public void PetaPoco_GetAll_Overload_Returns_Page_Of_Items(int pageIndex, int pa // Act dogs = dogRepository.GetPage(pageIndex, pageSize); } - + // Assert Assert.AreEqual(pageSize, dogs.PageSize); } @@ -306,11 +306,11 @@ 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 @@ -343,11 +343,11 @@ 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 @@ -373,7 +373,7 @@ public void PetaPoco_Update_Updates_Item_Using_FluentMapper() } } } - + [Test] public void PetaPoco_Update_Overload_Updates_Item() { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs index 394abd97cbe..9dc6e269083 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoMapperTests.cs @@ -14,8 +14,8 @@ namespace DotNetNuke.Tests.Data [TestFixture] public class PetaPocoMapperTests - { - // ReSharper disable InconsistentNaming + { + // ReSharper disable InconsistentNaming [Test] public void PetaPocoMapper_Constructor_Initialises_TablePrefix_Property() { @@ -26,8 +26,8 @@ public void PetaPocoMapper_Constructor_Initialises_TablePrefix_Property() // Assert Assert.AreEqual(Constants.TABLENAME_Prefix, Util.GetPrivateMember(mapper, "_tablePrefix")); - } - + } + [Test] public void PetaPocoMapper_GetTableInfo_Returns_TableInfo() { @@ -130,8 +130,8 @@ public void PetaPocoMapper_Sets_AutoIncrement_To_True() // Assert Assert.IsTrue(ti.AutoIncrement); - } - + } + [Test] public void PetaPocoMapper_GetColumnInfo_Returns_ColumnInfo() { @@ -175,8 +175,8 @@ public void PetaPocoMapper_GetColumnInfo_Maps_ColumnName_To_PropertyName_If_No_A // Assert Assert.AreEqual(Constants.COLUMNNAME_Name, ci.ColumnName); - } - - // ReSharper restore InconsistentNaming + } + + // ReSharper restore InconsistentNaming } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs index 08ba316ec55..3fd37e4c380 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Data/PetaPocoRepositoryTests.cs @@ -46,8 +46,8 @@ public void SetUp() public void TearDown() { DataUtil.DeleteDatabase(Constants.PETAPOCO_DatabaseName); - } - + } + [Test] public void PetaPocoRepository_Constructor_Throws_On_Null_Database() { @@ -72,8 +72,8 @@ public void PetaPocoRepository_Constructor_Registers_Mapper() // Assert Assert.AreSame(mockMapper.Object, Mappers.GetMapper(typeof(Dog), mockMapper.Object)); - } - + } + [Test] [TestCase(0)] [TestCase(1)] @@ -157,8 +157,8 @@ public void PetaPocoRepository_Get_Returns_Models_With_Correct_Properties_Using_ var dog = dogs.First(); Assert.AreEqual(this._dogAges[0], dog.Age.ToString()); Assert.AreEqual(this._dogNames[0], dog.Name); - } - + } + [Test] public void PetaPocoRepository_GetById_Returns_Instance_Of_Model_If_Valid_Id() { @@ -259,8 +259,8 @@ public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties_Usi // Assert Assert.AreEqual(Constants.PETAPOCO_ValidDogAge, dog.Age); Assert.AreEqual(Constants.PETAPOCO_ValidDogName, dog.Name); - } - + } + [Test] public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase() { @@ -271,17 +271,17 @@ 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); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, actualCount); @@ -297,17 +297,17 @@ 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); // Assert - int newId = DataUtil.GetLastAddedRecordID( + int newId = DataUtil.GetLastAddedRecordID( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName, Constants.TABLENAME_Key); Assert.AreEqual(Constants.PETAPOCO_RecordCount + 1, newId); @@ -323,10 +323,10 @@ 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 @@ -370,8 +370,8 @@ public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_Colum Assert.AreEqual(Constants.PETAPOCO_InsertDogAge, row["Age"]); Assert.AreEqual(Constants.PETAPOCO_InsertDogName, row["Name"]); - } - + } + [Test] public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase() { @@ -382,18 +382,18 @@ 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); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); @@ -409,11 +409,11 @@ 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 @@ -470,11 +470,11 @@ 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 @@ -482,7 +482,7 @@ public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID() // Assert // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); @@ -515,12 +515,12 @@ public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID_Using_FluentM // Assert // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); - } - + } + [Test] public void PetaPocoRepository_Delete_Overload_Deletes_Item_From_DataBase() { @@ -536,7 +536,7 @@ public void PetaPocoRepository_Delete_Overload_Deletes_Item_From_DataBase() repository.Delete("WHERE ID = @0", Constants.PETAPOCO_DeleteDogId); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount - 1, actualCount); @@ -579,12 +579,12 @@ public void PetaPocoRepository_Delete_Overload_Does_Nothing_With_Invalid_ID() repository.Delete("WHERE ID = @0", Constants.PETAPOCO_InvalidDogId); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); - } - + } + [Test] [TestCase(1, "WHERE ID < @0", 2)] [TestCase(4, "WHERE Age <= @0", 5)] @@ -604,8 +604,8 @@ public void PetaPocoRepository_Find_Returns_Correct_Rows(int count, string sqlCo // Assert Assert.AreEqual(count, dogs.Count()); - } - + } + [Test] [TestCase(Constants.PAGE_First, Constants.PAGE_RecordCount)] [TestCase(Constants.PAGE_Second, Constants.PAGE_RecordCount)] @@ -688,8 +688,8 @@ public void PetaPocoRepository_GetPage_Overload_Returns_Correct_Page(int pageInd // Assert var dog = dogs.First(); Assert.AreEqual(firstId, dog.ID); - } - + } + [Test] public void PetaPocoRepository_Update_Updates_Item_In_DataBase() { @@ -700,18 +700,18 @@ 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); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); @@ -727,11 +727,11 @@ 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 @@ -784,8 +784,8 @@ public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID_Using_FluentM Assert.AreEqual(Constants.PETAPOCO_UpdateDogName, row["Name"]); } } - } - + } + [Test] public void PetaPocoRepository_Update_Overload_Updates_Item_In_DataBase() { @@ -801,7 +801,7 @@ public void PetaPocoRepository_Update_Overload_Updates_Item_In_DataBase() repository.Update("SET Age=@1, Name=@2 WHERE ID=@0", Constants.PETAPOCO_UpdateDogId, Constants.PETAPOCO_UpdateDogAge, Constants.PETAPOCO_UpdateDogName); // Assert - int actualCount = DataUtil.GetRecordCount( + int actualCount = DataUtil.GetRecordCount( Constants.PETAPOCO_DatabaseName, Constants.PETAPOCO_DogTableName); Assert.AreEqual(Constants.PETAPOCO_RecordCount, actualCount); @@ -831,8 +831,8 @@ public void PetaPocoRepository_Update_Overload_Updates_Item_With_Correct_ID() Assert.AreEqual(Constants.PETAPOCO_UpdateDogName, row["Name"]); } } - } - + } + private Database CreatePecaPocoDatabase() { var db = new Database(connectionStringName); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj b/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj index ae1fca959f5..6f36f06b0c5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/DotNetNuke.Tests.Integration.csproj @@ -116,6 +116,7 @@ + diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs index 428c9fa3ad6..21b4d5ef6c4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Builders/TabPermissionsBuilder.cs @@ -17,28 +17,28 @@ public TabPermissionsBuilder() this.WithTabId(Null.NullInteger); } - public TabPermissionsBuilder WithTabId(int tabId) - { - this.Set(x => x.TabId, tabId); - return this; + public TabPermissionsBuilder WithTabId(int tabId) + { + this.Set(x => x.TabId, tabId); + return this; } - public TabPermissionsBuilder WithPermissionDefinitions(IList permissionDefinitions) - { - this.Set(x => x.PermissionDefinitions, permissionDefinitions); - return this; + public TabPermissionsBuilder WithPermissionDefinitions(IList permissionDefinitions) + { + this.Set(x => x.PermissionDefinitions, permissionDefinitions); + return this; } - public TabPermissionsBuilder WithRolePermissions(IList rolePermissions) - { - this.Set(x => x.RolePermissions, rolePermissions); - return this; + public TabPermissionsBuilder WithRolePermissions(IList rolePermissions) + { + this.Set(x => x.RolePermissions, rolePermissions); + return this; } - public TabPermissionsBuilder WithUserPermissions(IList userPermissions) - { - this.Set(x => x.UserPermissions, userPermissions); - return this; + public TabPermissionsBuilder WithUserPermissions(IList userPermissions) + { + this.Set(x => x.UserPermissions, userPermissions); + return this; } protected override TabPermissions BuildObject() 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 bf81f1d1c99..54e092e9763 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/Dto/PageSettings.cs @@ -10,59 +10,59 @@ namespace DotNetNuke.Tests.Integration.Executers.Dto public class PageSettings { public bool ApplyWorkflowToChildren { get; set; } - + public string created { get; set; } - + public bool customUrlEnabled { get; set; } - + public bool hasChild { get; set; } - + public string Hierarchy { get; set; } - + public bool IncludeInMenu { get; set; } - + public bool isCopy { get; set; } - + public bool isWorkflowCompleted { get; set; } - + public bool isWorkflowPropagationAvailable { get; set; } - + public string keywords { get; set; } - + public string localizedName { get; set; } - + public string Name { get; set; } - + public string pageType { get; set; } - + public int tabId { get; set; } - + public string tags { get; set; } - + public string thumbnail { get; set; } - + public string title { get; set; } - + public bool trackLinks { get; set; } - + public int type { get; set; } - + public int workflowId { get; set; } - + public string Url { get; set; } - + public string Description { get; set; } - + public DateTime? startDate { get; set; } - + public DateTime? endDate { get; set; } - + public TabPermissions permissions { get; set; } - + public int templateTabId { get; set; } - + public IList modules { get; set; } - + public bool isSecure { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs index c83cd16859b..e039ce50b08 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/PagesExecuter.cs @@ -5,7 +5,7 @@ namespace DotNetNuke.Tests.Integration.Executers { public class PagesExecuter : WebApiExecuter - { + { public PagesExecuter GetPageDetails(int pageId) { this.Responses.Add(this.Connector.GetContent( @@ -16,10 +16,10 @@ public PagesExecuter GetPageDetails(int pageId) public dynamic SavePageDetails(dynamic pageDetails) { - this.Responses.Add(this.Connector.PostJson( + this.Responses.Add(this.Connector.PostJson( "API/PersonaBar/Pages/SavePageDetails", pageDetails)); return this.GetLastDeserializeResponseMessage(); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs index 9eca5061a46..5bae1ca8e71 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Executers/WebApiExecuter.cs @@ -44,13 +44,37 @@ protected WebApiExecuter() this.UserLastName = Constants.RuLastName; } + public string UserName + { + get + { + return this.Connector.UserName; + } + } + + public string DisplayName + { + get + { + return string.Join(" ", this.UserFirstName, this.UserLastName); + } + } + + public int UserId + { + get + { + return DatabaseHelper.ExecuteScalar($"SELECT UserId FROM {{objectQualifier}}Users WHERE UserName = '{this.UserName}'"); + } + } + public LoginAsUser LoginAs { get { return this._loginAs; } - + set { this._loginAs = value; @@ -59,7 +83,7 @@ public LoginAsUser LoginAs } public string UserFirstName { get; set; } - + public string UserLastName { get; set; } public IWebApiConnector Connector @@ -84,10 +108,10 @@ public IWebApiConnector Connector break; } } - + return this._connector; } - + set { this._connector = value; @@ -100,30 +124,6 @@ public IWebApiConnector Connector } } - public string UserName - { - get - { - return this.Connector.UserName; - } - } - - public string DisplayName - { - get - { - return string.Join(" ", this.UserFirstName, this.UserLastName); - } - } - - public int UserId - { - get - { - return DatabaseHelper.ExecuteScalar($"SELECT UserId FROM {{objectQualifier}}Users WHERE UserName = '{this.UserName}'"); - } - } - public HttpResponseMessage GetLastResponseMessage() { return this.Responses.Last(); @@ -140,7 +140,7 @@ public JContainer GetLastDeserializeResponseMessage() { throw new InvalidOperationException("GetLastDeserializeResponseMessage cannot be called when the Executer does not have any Responses"); } - + var data = this.Responses.Last().Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject(data); } @@ -161,7 +161,7 @@ public IEnumerable GetDeserializeResponseMessages() { throw new InvalidOperationException("GetDeserializeResponseMessages cannot be called when the Executer does not have any Responses"); } - + return this.GetResponseMessages().Select(r => JsonConvert.DeserializeObject(r.Content.ReadAsStringAsync().Result)); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs index 4c32fbda29d..7e8f1916c2b 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/DDRMenu/DDRMenuTests.cs @@ -19,10 +19,10 @@ namespace DotNetNuke.Tests.Integration.Modules.DDRMenu [TestFixture] public class DDRMenuTests : IntegrationTestBase - { + { private readonly string _hostName; - private readonly string _hostPass; - + private readonly string _hostPass; + public DDRMenuTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; @@ -34,8 +34,8 @@ public DDRMenuTests() public override void TestFixtureSetUp() { base.TestFixtureSetUp(); - } - + } + [Test] public void Page_Should_Able_To_Duplicate_With_Ddr_Menu_On_It() { @@ -51,8 +51,8 @@ public void Page_Should_Able_To_Duplicate_With_Ddr_Menu_On_It() // Copy Page int copyTabId; this.CreateNewPage(tabId, out copyTabId); - } - + } + private IWebApiConnector CreateNewPage(int templateTabId, out int tabId) { var pagesExecuter = new PagesExecuter { Connector = WebApiTestHelper.LoginHost() }; @@ -98,6 +98,6 @@ private IWebApiConnector AddModuleToPage(int tabId, string moduleName, out int m moduleId = Json.Deserialize(response).TabModuleID; return connector; - } + } } } 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 f54cd85a395..c3795cd3b32 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Modules/Journal/PostJournalTests.cs @@ -15,14 +15,14 @@ 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; - private readonly int PortalId = 0; - + private readonly int PortalId = 0; + public PostJournalTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; @@ -36,17 +36,17 @@ public override void TestFixtureSetUp() base.TestFixtureSetUp(); try { - if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) - { - DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); - } + if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("TEAMCITY_VERSION"))) + { + DatabaseHelper.ExecuteNonQuery("TRUNCATE TABLE {objectQualifier}JsonWebTokens"); + } } catch (Exception) { // ignored } - } - + } + [Test] public void Journal_Should_Able_To_Attach_Files_Upload_By_Himself() { @@ -64,7 +64,7 @@ public void Journal_Should_Able_To_Attach_Files_Upload_By_Himself() securitySet = "E", itemData = $"{{\"ImageUrl\":\"\",\"Url\":\"fileid={fileId}\"}}", }; - + connector.PostJson("/API/Journal/Services/Create", postData, this.GetRequestHeaders()); } @@ -75,7 +75,7 @@ public void Journal_Should_Not_Able_To_Attach_Files_Upload_By_Other_User() string username; var connector = this.PrepareNewUser(out userId, out username, out fileId); fileId = DatabaseHelper.ExecuteScalar($"SELECT MIN(FileId) FROM {{objectQualifier}}Files WHERE PortalId = {this.PortalId}"); - + // POST JOURNAL var postData = new { @@ -376,7 +376,7 @@ public void Journal_Should_Only_Able_See_By_Friends_When_Set_Security_To_Friends var notificationId = DatabaseHelper.ExecuteScalar($"SELECT TOP 1 MessageID FROM {{objectQualifier}}CoreMessaging_Messages WHERE SenderUserID = {userId1}"); connector2.PostJson("/API/InternalServices/RelationshipService/AcceptFriend", new { NotificationId = notificationId }, this.GetRequestHeaders()); - + // POST JOURNAL var journalText = $"{username1} Post"; var postData = new @@ -425,7 +425,7 @@ public void Journal_Should_Only_Able_See_By_Himself_When_Set_Security_To_Private var hostConnector = WebApiTestHelper.LoginHost(); response = hostConnector.GetContent($"/Activity-Feed/userId/{userId}").Content.ReadAsStringAsync().Result; Assert.AreEqual(response.IndexOf(journalText), -1); - } + } private IWebApiConnector PrepareNewUser(out int userId, out string username, out int fileId) { @@ -469,6 +469,6 @@ private void AddUserToGroup(int groupId, int userId) private IDictionary GetRequestHeaders(string moduleName = "Journal") { return WebApiTestHelper.GetRequestHeaders("//ActivityFeed", moduleName, this.PortalId); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs index 65ab13c5583..53c1c3f1567 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/AddPageTests.cs @@ -47,23 +47,23 @@ public void Add_Multi_Pages_For_Exisitng_Shoul_Return_Results() Console.WriteLine(@"Verify bulk pages ersponse = {0}", response2); Assert.AreEqual(0, int.Parse(result2.Status.ToString())); Assert.IsNotNullOrEmpty(result2.Response.Pages.First().ErrorMessage); - } - + } + [JsonObject] public class BulkPage { public string BulkPages { get; set; } - + public int ParentId { get; set; } - + public string Keywords { get; set; } - + public string Tags { get; set; } - + public bool IncludeInMenu { get; set; } - + public DateTime? StartDate { get; set; } - + public DateTime? EndDate { get; set; } } @@ -71,11 +71,11 @@ public class BulkPage public class BulkPageResponseItem { public string PageName { get; set; } - + public int Status { get; set; } - + public int TabId { get; set; } - + public string ErrorMessage { get; set; } } @@ -83,7 +83,7 @@ public class BulkPageResponseItem public class BulkPageResponse { public int OverallStatus { get; set; } - + public IEnumerable Pages { get; set; } } @@ -91,8 +91,8 @@ public class BulkPageResponse public class BulkPageResponseWrapper { public int Status { get; set; } - + public BulkPageResponse Response { get; set; } - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs index 344223607fe..520151d2e20 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Content/Pages/PageUrlsTests.cs @@ -23,8 +23,8 @@ public class PageUrlsTests : IntegrationTestBase private const string UpdateLanguageApi = "/API/PersonaBar/SiteSettings/UpdateLanguage"; private const string CreateCustomUrlApi = "/API/PersonaBar/Pages/CreateCustomUrl"; private const string EnglishLanguageCode = "en-US"; - private const string SpainishLanguageCode = "es-ES"; - + private const string SpainishLanguageCode = "es-ES"; + [Test] public void Page_Url_Should_Able_To_Add_On_English_Disabled_Site() { @@ -53,8 +53,8 @@ public void Page_Url_Should_Able_To_Add_On_English_Disabled_Site() ResetChanges(connector, isEnglishEnabled, languageSettings); Assert.IsTrue(bool.Parse(result.Success.ToString())); - } - + } + private static IWebApiConnector PrepareTest(out bool isEnglishEnabled, out dynamic languageSettings) { var connector = WebApiTestHelper.LoginHost(); @@ -72,12 +72,12 @@ private static IWebApiConnector PrepareTest(out bool isEnglishEnabled, out dynam connector.PostJson(AddLanguageApi, new { Code = SpainishLanguageCode }); UpdateLanguageSettings(connector, languageSettings, SpainishLanguageCode); } - + if (isEnglishEnabled) { EnableEnglish(connector, false); } - + return connector; } @@ -87,7 +87,7 @@ private static void ResetChanges(IWebApiConnector connector, bool isEnglishEnabl { EnableEnglish(connector, true); } - + if (string.Compare(languageSettings.SiteDefaultLanguage.Value, EnglishLanguageCode, StringComparison.InvariantCultureIgnoreCase) == 0) { UpdateLanguageSettings(connector, languageSettings, EnglishLanguageCode); @@ -126,6 +126,6 @@ private static int CreateNewPage(IWebApiConnector connector) var pageDetail = pagesExecuter.SavePageDetails(pageSettingsBuilder.Build()); Assert.NotNull(pageDetail.Page, "The system must create the page and return its details in the response"); return (int)pageDetail.Page.id; - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs index e42c042ff91..87de47392dd 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/PersonaBar/Pages/PagesManagementTests.cs @@ -19,12 +19,12 @@ namespace DotNetNuke.Tests.Integration.PersonaBar.Pages [TestFixture] public class PagesManagementTests : IntegrationTestBase - { + { private readonly string _hostName; private readonly string _hostPass; - private readonly int PortalId = 0; - + private readonly int PortalId = 0; + public PagesManagementTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; @@ -52,8 +52,8 @@ public override void TestFixtureTearDown() this.UpdateSslSettings(false); this.UpdateContentLocalization(false); - } - + } + [Test] public void Page_Marked_As_Secure_Should_Able_To_Management_In_Insecure_Channel() { @@ -98,8 +98,8 @@ private void UpdateSslSettings(bool sslEnabled) var postData = new { SSLEnabled = sslEnabled, SSLEnforced = false, SSLURL = string.Empty, STDURL = string.Empty, SSLOffloadHeader = string.Empty }; connector.PostJson("API/PersonaBar/Security/UpdateSslSettings", postData); - } - + } + private IWebApiConnector CreateNewSecurePage(out int tabId) { var pagesExecuter = new PagesExecuter { Connector = WebApiTestHelper.LoginHost() }; @@ -115,6 +115,6 @@ private IWebApiConnector CreateNewSecurePage(out int tabId) tabId = (int)pageDetail.Page.id; return pagesExecuter.Connector; - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/TestLogSource.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/TestLogSource.cs new file mode 100644 index 00000000000..646cdb95d5a --- /dev/null +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/TestLogSource.cs @@ -0,0 +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 +namespace DotNetNuke.Tests.Integration.Services.Installer +{ + using System; + using DotNetNuke.Instrumentation; + + internal class TestLogSource : ILoggerSource + { + public ILog GetLogger(string name) + { + return new TestLogger(); + } + + public ILog GetLogger(Type type) + { + return new TestLogger(); + } + } +} 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 1f36c87f6aa..077daa75b1c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Services/Installer/XmlMergeTests.cs @@ -27,9 +27,9 @@ public void SetUp() AppDomain.CurrentDomain.SetData("APPBASE", this.WebsitePhysicalAppPath); LoggerSource.SetTestableInstance(new TestLogSource()); - } - - // ReSharper disable PossibleNullReferenceException + } + + // ReSharper disable PossibleNullReferenceException [Test] public void SimpleUpdate() { @@ -44,99 +44,6 @@ public void SimpleUpdate() Assert.AreEqual(2, nodes.Count); } - /// - /// Merges the Merge and Target files based on the name of the calling method. - /// - /// xml files must be embedded resources in the MergeFiles folder named {method}Merge.xml and {method}Target.xml. - /// XmlDocument with the result of the merge operation. - private XmlDocument ExecuteMerge() - { - return this.ExecuteMerge(null); - } - - /// - /// As ExecuteMerge but allows the merge file prefix to be specified. - /// - private XmlDocument ExecuteMerge(string mergeName) - { - string testMethodName = this.GetTestMethodName(); - - XmlMerge merge = this.GetXmlMerge(mergeName ?? testMethodName); - XmlDocument targetDoc = this.LoadTargetDoc(testMethodName); - - merge.UpdateConfig(targetDoc); - - this.WriteToDebug(targetDoc); - - return targetDoc; - } - - private string GetTestMethodName() - { - var st = new StackTrace(2); - - string name; - int i = 0; - do - { - name = st.GetFrame(i).GetMethod().Name; - i++; - } - while (name == "ExecuteMerge"); - - return name; - } - - private XmlDocument LoadTargetDoc(string testMethodName) - { - using (Stream targetStream = - this._assembly.GetManifestResourceStream(string.Format( - "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Target.xml", - testMethodName))) - { - Debug.Assert( - targetStream != null, - string.Format("Unable to location embedded resource for {0}Target.xml", testMethodName)); - var targetDoc = new XmlDocument { XmlResolver = null }; - targetDoc.Load(targetStream); - return targetDoc; - } - } - - private XmlMerge GetXmlMerge(string fileName) - { - using (Stream mergeStream = - this._assembly.GetManifestResourceStream(string.Format( - "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Merge.xml", - fileName))) - { - Debug.Assert( - mergeStream != null, - string.Format("Unable to location embedded resource for {0}Merge.xml", fileName)); - var merge = new XmlMerge(mergeStream, "version", "sender"); - return merge; - } - } - - private void WriteToDebug(XmlDocument targetDoc) - { - // ReSharper disable ConditionIsAlwaysTrueOrFalse - if (OutputXml) - - // ReSharper restore ConditionIsAlwaysTrueOrFalse - { - using (var writer = new StreamWriter(new MemoryStream())) - { - targetDoc.Save(writer); - writer.BaseStream.Seek(0, SeekOrigin.Begin); - using (var sr = new StreamReader(writer.BaseStream)) - { - Debug.WriteLine("{0}", sr.ReadToEnd()); - } - } - } - } - [Test] public void SimpleUpdateInLocation() { @@ -491,22 +398,102 @@ 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 - } + } - internal class TestLogSource : ILoggerSource - { - public ILog GetLogger(string name) + /// + /// Merges the Merge and Target files based on the name of the calling method. + /// + /// xml files must be embedded resources in the MergeFiles folder named {method}Merge.xml and {method}Target.xml. + /// XmlDocument with the result of the merge operation. + private XmlDocument ExecuteMerge() + { + return this.ExecuteMerge(null); + } + + /// + /// As ExecuteMerge but allows the merge file prefix to be specified. + /// + private XmlDocument ExecuteMerge(string mergeName) + { + string testMethodName = this.GetTestMethodName(); + + XmlMerge merge = this.GetXmlMerge(mergeName ?? testMethodName); + XmlDocument targetDoc = this.LoadTargetDoc(testMethodName); + + merge.UpdateConfig(targetDoc); + + this.WriteToDebug(targetDoc); + + return targetDoc; + } + + private string GetTestMethodName() { - return new TestLogger(); + var st = new StackTrace(2); + + string name; + int i = 0; + do + { + name = st.GetFrame(i).GetMethod().Name; + i++; + } + while (name == "ExecuteMerge"); + + return name; + } + + private XmlDocument LoadTargetDoc(string testMethodName) + { + using (Stream targetStream = + this._assembly.GetManifestResourceStream(string.Format( + "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Target.xml", + testMethodName))) + { + Debug.Assert( + targetStream != null, + string.Format("Unable to location embedded resource for {0}Target.xml", testMethodName)); + var targetDoc = new XmlDocument { XmlResolver = null }; + targetDoc.Load(targetStream); + return targetDoc; + } + } + + private XmlMerge GetXmlMerge(string fileName) + { + using (Stream mergeStream = + this._assembly.GetManifestResourceStream(string.Format( + "DotNetNuke.Tests.Integration.Services.Installer.MergeFiles.{0}Merge.xml", + fileName))) + { + Debug.Assert( + mergeStream != null, + string.Format("Unable to location embedded resource for {0}Merge.xml", fileName)); + var merge = new XmlMerge(mergeStream, "version", "sender"); + return merge; + } } - public ILog GetLogger(Type type) + private void WriteToDebug(XmlDocument targetDoc) { - return new TestLogger(); + // ReSharper disable ConditionIsAlwaysTrueOrFalse + if (OutputXml) + + // ReSharper restore ConditionIsAlwaysTrueOrFalse + { + using (var writer = new StreamWriter(new MemoryStream())) + { + targetDoc.Save(writer); + writer.BaseStream.Seek(0, SeekOrigin.Begin); + using (var sr = new StreamReader(writer.BaseStream)) + { + Debug.WriteLine("{0}", sr.ReadToEnd()); + } + } + } } + + // ReSharper restore PossibleNullReferenceException } internal class TestLogger : ILog @@ -525,7 +512,22 @@ public bool IsFatalEnabled { get { return false; } } - + + public bool IsInfoEnabled + { + get { return false; } + } + + public bool IsTraceEnabled + { + get { return false; } + } + + public bool IsWarnEnabled + { + get { return false; } + } + public void Debug(object message, Exception exception) { } @@ -590,21 +592,6 @@ public void InfoFormat(string format, params object[] args) { } - public bool IsInfoEnabled - { - get { return false; } - } - - public bool IsTraceEnabled - { - get { return false; } - } - - public bool IsWarnEnabled - { - get { return false; } - } - public void Trace(object message, Exception exception) { } 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 4867dc352c7..9fa39e36dee 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/DotNetNukeWeb/DotNetNukeWebTests.cs @@ -15,10 +15,10 @@ 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); @@ -28,8 +28,8 @@ public DotNetNukeWebTests() var url = ConfigurationManager.AppSettings["siteUrl"]; var siteUri = new Uri(url); this._httpClient = new HttpClient { BaseAddress = siteUri, Timeout = this._timeout }; - } - + } + [Test] [TestCase(GetMonikerQuery)] [TestCase(GetModuleDetailsQuery)] @@ -39,6 +39,6 @@ public void CallingHelperForAnonymousUserShouldReturnSuccess(string query) var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs index ee2364f81ec..edf714fd43d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/FriendsTests.cs @@ -118,7 +118,7 @@ private bool LanguageEnabled(int portalId, string secondLanguage) Roles = "Administrators", }); } - + return false; } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs index d920498b1d8..b8c49402e78 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalInfoTests.cs @@ -17,7 +17,7 @@ namespace DotNetNuke.Tests.Integration.Tests.Portals [TestFixture] public class PortalInfoTests : DnnWebTest { - public PortalInfoTests() + public PortalInfoTests() : base(Constants.PORTAL_Zero) { } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs index 780883ce220..8d241e5ed1c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Portals/PortalSettingsTests.cs @@ -18,7 +18,7 @@ public class PortalSettingsTests : DnnWebTest private string _settingName; private string _settingValue; - public PortalSettingsTests() + public PortalSettingsTests() : base(Constants.PORTAL_Zero) { } @@ -27,7 +27,7 @@ public PortalSettingsTests() public void Setup() { this._settingName = "NameToCheckFor"; - + // we need different value so when we save we force going to database this._settingValue = "ValueToCheckFor_" + new Random().Next(1, 100); } 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 e0a5f425c9d..2867fdae58c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Integration/Tests/Security/AuthCookieTests.cs @@ -41,7 +41,7 @@ public void Using_Logged_Out_Cookie_Should_Be_Unauthorized() Assert.IsFalse(result2.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.Unauthorized, result2.StatusCode); } - + private static HttpClient CreateHttpClient(Uri domain, TimeSpan timeout, CookieContainer cookies) { var clientHandler = new HttpClientHandler @@ -57,12 +57,12 @@ 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 7934ca4ef15..71ba015a73d 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/DataAnnotationsObjectValidatorTests.cs @@ -23,8 +23,8 @@ public static string ErrorMessage { return ErrorMessageConst; } - } - + } + [Test] public void ValidateObject_Returns_Successful_Result_If_All_Attributes_On_All_Properties_Validate() { @@ -68,15 +68,6 @@ 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() @@ -92,6 +83,15 @@ public void ValidateObject_Collects_ValidationAttribute_Objects_From_Failed_Vali Assert.IsFalse(result.IsValid); Assert.IsInstanceOf(result.Errors.Single(e => e.PropertyName == "Foo").Validator); Assert.IsInstanceOf(result.Errors.Single(e => e.PropertyName == "Bar").Validator); - } + } + + 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; } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs index e676dfc9143..6a018e31888 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.UI/Validation/ValidatorTests.cs @@ -16,8 +16,8 @@ public class ValidatorTests { private static readonly ValidationResult FailedResult = new ValidationResult(new[] { new ValidationError() }); - private static readonly ValidationResult AnotherFailedResult = new ValidationResult(new[] { new ValidationError() }); - + private static readonly ValidationResult AnotherFailedResult = new ValidationResult(new[] { new ValidationError() }); + [Test] public void ValidateObject_Returns_Successful_Result_If_All_Validators_Return_Successful() { @@ -63,8 +63,8 @@ public void ValidateObject_Collects_Errors_From_All_Validators() Assert.IsFalse(result.IsValid); Assert.AreEqual(2, result.Errors.Count()); EnumerableAssert.ElementsMatch(new[] { FailedResult, AnotherFailedResult }, result.Errors, (e, a) => ReferenceEquals(e.Errors.First(), a)); - } - + } + private static void SetupValidators(Validator validator, object target, params ValidationResult[] validationResults) { validator.Validators.Clear(); @@ -74,6 +74,6 @@ private static void SetupValidators(Validator validator, object target, params V mockValidator.Setup(v => v.ValidateObject(target)).Returns(validationResults[i]); validator.Validators.Add(mockValidator.Object); } - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs index abfcdea3525..0f7fdb1fdf5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/Extensions.cs @@ -21,7 +21,7 @@ public static string GetValue(this Dictionary dic, string key, s { returnValue = dic[key]; } - + return returnValue; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs index 6e25f1e4ea9..ddf2064a509 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/FriendlyUrlTests.cs @@ -30,11 +30,11 @@ public class FriendlyUrlTests : UrlTestBase private Locale _customLocale; private PortalAliasInfo _primaryAlias; - public FriendlyUrlTests() - : base(0) - { - } - + public FriendlyUrlTests() + : base(0) + { + } + [SetUp] public override void SetUp() { @@ -59,7 +59,7 @@ public override void TestFixtureSetUp() this.CreateTab(_aboutUsPageName); tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); } - + this._tabId = tab.TabID; // Add Portal Aliases @@ -70,10 +70,10 @@ 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); } @@ -98,7 +98,7 @@ public override void TearDown() Localization.RemoveLanguageFromPortals(this._customLocale.LanguageId, true); Localization.DeleteLanguage(this._customLocale, true); } - + if (this._primaryAlias != null) { PortalAliasController.Instance.DeletePortalAlias(this._primaryAlias); @@ -131,8 +131,8 @@ public override void TestFixtureTearDown() TestUtil.DeleteUser(this.PortalId, fields[0]); }); - } - + } + [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_BaseTestCases")] public void AdvancedUrlProvider_BaseFriendlyUrl(Dictionary testFields) @@ -146,95 +146,6 @@ public void AdvancedUrlProvider_ImprovedFriendlyUrl(Dictionary t { this.ExecuteTest("Improved", testFields); } - - private void ExecuteTest(string test, Dictionary testFields) - { - var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); - - this.SetDefaultAlias(testFields); - - this.ExecuteTest(test, settings, testFields); - } - - private void ExecuteTest(string test, FriendlyUrlSettings settings, Dictionary testFields) - { - var tabName = testFields["Page Name"]; - var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); - if (tab == null) - { - Assert.Fail($"TAB with name [{tabName}] is not found!"); - } - - this.ExecuteTestForTab(test, tab, settings, testFields); - } - - private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) - { - var httpAlias = testFields["Alias"]; - var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); - var tabName = testFields["Page Name"]; - var scheme = testFields["Scheme"]; - var parameters = testFields["Params"]; - var result = testFields["Expected Url"]; - var customPage = testFields.GetValue("Custom Page Name", _defaultPage); - string vanityUrl = testFields.GetValue("VanityUrl", string.Empty); - - var httpAliasFull = scheme + httpAlias + "/"; - var expectedResult = result.Replace("{alias}", httpAlias) - .Replace("{usealias}", defaultAlias) - .Replace("{tabName}", tabName) - .Replace("{tabId}", tab.TabID.ToString()) - .Replace("{vanityUrl}", vanityUrl) - .Replace("{defaultPage}", _defaultPage); - - if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) - { - parameters = "&" + parameters; - } - - var userName = testFields.GetValue("UserName", string.Empty); - if (!string.IsNullOrEmpty(userName)) - { - var user = UserController.GetUserByName(this.PortalId, userName); - if (user != null) - { - expectedResult = expectedResult.Replace("{userId}", user.UserID.ToString()); - parameters = parameters.Replace("{userId}", user.UserID.ToString()); - } - } - - var baseUrl = httpAliasFull + "Default.aspx?TabId=" + tab.TabID + parameters; - string testUrl; - if (test == "Base") - { - testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl( - tab, - baseUrl, - customPage, - httpAlias, - settings); - } - else - { - testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( - tab, - baseUrl, - customPage, - httpAlias, - true, - settings, - Guid.Empty); - } - - Assert.IsTrue(expectedResult.Equals(testUrl, StringComparison.InvariantCultureIgnoreCase)); - } - - private void UpdateTabName(int tabId, string newName) - { - var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); - tab.TabName = newName; - TabController.Instance.UpdateTab(tab); - } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "FriendlyUrl_SpaceEncodingTestCases")] @@ -266,7 +177,7 @@ public void AdvancedUrlProvider_PageExtension(Dictionary testFie { settings.PageExtension = pageExtension; } - + switch (pageExtensionUsageType) { case "AlwaysUse": @@ -437,7 +348,7 @@ public void AdvancedUrlProvider_VanityUrl(Dictionary testFields) UserController.UpdateUser(this.PortalId, user); } } - + this.ExecuteTest("Improved", settings, testFields); } @@ -455,6 +366,95 @@ public void AdvancedUrlProvider_ForceLowerCase(Dictionary testFi } this.ExecuteTest("Improved", settings, testFields); - } + } + + private void ExecuteTest(string test, Dictionary testFields) + { + var settings = UrlTestFactoryClass.GetSettings("FriendlyUrl", testFields["TestName"], this.PortalId); + + this.SetDefaultAlias(testFields); + + this.ExecuteTest(test, settings, testFields); + } + + private void ExecuteTest(string test, FriendlyUrlSettings settings, Dictionary testFields) + { + var tabName = testFields["Page Name"]; + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); + if (tab == null) + { + Assert.Fail($"TAB with name [{tabName}] is not found!"); + } + + this.ExecuteTestForTab(test, tab, settings, testFields); + } + + private void ExecuteTestForTab(string test, TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) + { + var httpAlias = testFields["Alias"]; + var defaultAlias = testFields.GetValue("DefaultAlias", string.Empty); + var tabName = testFields["Page Name"]; + var scheme = testFields["Scheme"]; + var parameters = testFields["Params"]; + var result = testFields["Expected Url"]; + var customPage = testFields.GetValue("Custom Page Name", _defaultPage); + string vanityUrl = testFields.GetValue("VanityUrl", string.Empty); + + var httpAliasFull = scheme + httpAlias + "/"; + var expectedResult = result.Replace("{alias}", httpAlias) + .Replace("{usealias}", defaultAlias) + .Replace("{tabName}", tabName) + .Replace("{tabId}", tab.TabID.ToString()) + .Replace("{vanityUrl}", vanityUrl) + .Replace("{defaultPage}", _defaultPage); + + if (!string.IsNullOrEmpty(parameters) && !parameters.StartsWith("&")) + { + parameters = "&" + parameters; + } + + var userName = testFields.GetValue("UserName", string.Empty); + if (!string.IsNullOrEmpty(userName)) + { + var user = UserController.GetUserByName(this.PortalId, userName); + if (user != null) + { + expectedResult = expectedResult.Replace("{userId}", user.UserID.ToString()); + parameters = parameters.Replace("{userId}", user.UserID.ToString()); + } + } + + var baseUrl = httpAliasFull + "Default.aspx?TabId=" + tab.TabID + parameters; + string testUrl; + if (test == "Base") + { + testUrl = AdvancedFriendlyUrlProvider.BaseFriendlyUrl( + tab, + baseUrl, + customPage, + httpAlias, + settings); + } + else + { + testUrl = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( + tab, + baseUrl, + customPage, + httpAlias, + true, + settings, + Guid.Empty); + } + + Assert.IsTrue(expectedResult.Equals(testUrl, StringComparison.InvariantCultureIgnoreCase)); + } + + private void UpdateTabName(int tabId, string newName) + { + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); + tab.TabName = newName; + TabController.Instance.UpdateTab(tab); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs index 334299063ec..de35a800ab8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/TestUtil.cs @@ -29,7 +29,7 @@ internal static string FilePath 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); @@ -96,12 +96,12 @@ internal static void GetReplaceCharDictionary(Dictionary testFie { key = vals[0]; } - + if (vals.GetUpperBound(0) >= 1) { val = vals[1]; } - + if (key != null && val != null) { replaceCharacterDictionary.Add(key, val); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs index 1e364675313..c7764fb6ef8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlAssert.cs @@ -5,6 +5,5 @@ namespace DotNetNuke.Tests.Urls { public static class UrlAssert - { - } + {} } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs index d706c937253..4113fcb8fa5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlRewriteTests.cs @@ -37,11 +37,11 @@ public class UrlRewriteTests : UrlTestBase private bool _sslEnforced; private bool _sslEnabled; - public UrlRewriteTests() - : base(0) - { - } - + public UrlRewriteTests() + : base(0) + { + } + [SetUp] public override void SetUp() { @@ -86,7 +86,7 @@ public override void TearDown() Localization.RemoveLanguageFromPortals(this._customLocale.LanguageId, true); Localization.DeleteLanguage(this._customLocale, true); } - + if (this._primaryAlias != null) { PortalAliasController.Instance.DeletePortalAlias(this._primaryAlias); @@ -102,57 +102,6 @@ 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() @@ -165,7 +114,7 @@ public override void TestFixtureSetUp() this.CreateTab(_aboutUsPageName); tab = TabController.Instance.GetTabByName(_aboutUsPageName, this.PortalId); } - + this._tabId = tab.TabID; // Add Portal Aliases @@ -210,8 +159,8 @@ public override void TestFixtureTearDown() TestUtil.DeleteUser(this.PortalId, fields[0]); }); - } - + } + [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_BasicTestCases")] public void AdvancedUrlRewriter_BasicTest(Dictionary testFields) @@ -241,7 +190,7 @@ public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary te { tab.EndDate = DateTime.Now - TimeSpan.FromDays(1); } - + this.UpdateTab(tab); CacheController.FlushPageIndexFromCache(); } @@ -265,106 +214,6 @@ public void AdvancedUrlRewriter_DeletedTabHandling(Dictionary te this.ExecuteTest(settings, testFields, true); } - - private void DeleteTab(string tabName) - { - var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); - - if (tab != null) - { - TabController.Instance.DeleteTab(tab.TabID, this.PortalId); - } - } - - private void ExecuteTestForTab(TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) - { - var httpAlias = testFields.GetValue("Alias", string.Empty); - var scheme = testFields["Scheme"]; - var url = testFields["Test Url"]; - var result = testFields["Expected Url"]; - var expectedStatus = int.Parse(testFields["Status"]); - var redirectUrl = testFields.GetValue("Final Url"); - var redirectReason = testFields.GetValue("RedirectReason"); - - var tabID = (tab == null) ? "-1" : tab.TabID.ToString(); - - var expectedResult = this.ReplaceTokens(testFields, result, tabID); - var testurl = this.ReplaceTokens(testFields, url, tabID); - var expectedRedirectUrl = this.ReplaceTokens(testFields, redirectUrl, tabID); - - 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(), - }; - - this.ProcessRequest(settings, testHelper); - - // Test expected response status - Assert.AreEqual(expectedStatus, testHelper.Response.StatusCode); - - switch (expectedStatus) - { - case 200: - // Test expected rewrite path - if (!string.IsNullOrEmpty(expectedResult)) - { - Assert.AreEqual(expectedResult, testHelper.Result.RewritePath.TrimStart('/')); - } - - break; - case 301: - case 302: - // Test for final Url if redirected - Assert.IsTrue(expectedRedirectUrl.Equals(testHelper.Result.FinalUrl.TrimStart('/'), StringComparison.InvariantCultureIgnoreCase)); - Assert.AreEqual(redirectReason, testHelper.Result.Reason.ToString(), "Redirect reason incorrect"); - break; - } - } - - private void ExecuteTest(FriendlyUrlSettings settings, Dictionary testFields, bool setDefaultAlias) - { - var tabName = testFields["Page Name"]; - var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); - - if (setDefaultAlias) - { - this.SetDefaultAlias(testFields); - } - - this.ExecuteTestForTab(tab, settings, testFields); - } - - private void UpdateTab(TabInfo tab) - { - if (tab != null) - { - TabController.Instance.UpdateTab(tab); - } - } - - private void UpdateTabName(int tabId, string newName) - { - var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); - tab.TabName = newName; - TabController.Instance.UpdateTab(tab); - } - - private void UpdateTabSkin(int tabId, string newSkin) - { - var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); - tab.SkinSrc = newSkin; - TabController.Instance.UpdateTab(tab); - } [Test] [TestCaseSource(typeof(UrlTestFactoryClass), "UrlRewrite_DoNotRedirect")] @@ -564,13 +413,13 @@ public void AdvancedUrlRewriter_0_PrimaryPortalAlias(Dictionary alias.CultureCode = language; alias.Skin = skin; } - + PortalAliasController.Instance.AddPortalAlias(alias); } - + this.SetDefaultAlias(defaultAlias); this.ExecuteTest(settings, testFields, false); - + alias = PortalAliasController.Instance.GetPortalAlias(defaultAlias, this.PortalId); if (alias != null) { @@ -603,7 +452,7 @@ public void AdvancedUrlRewriter_VanityUrl(Dictionary testFields) { settings.RedirectOldProfileUrl = Convert.ToBoolean(redirectOld); } - + this.ExecuteTest(settings, testFields, true); } @@ -664,6 +513,157 @@ public void AdvancedUrlRewriter_JiraTests(Dictionary testFields) } } + 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); + } + + private void DeleteTab(string tabName) + { + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); + + if (tab != null) + { + TabController.Instance.DeleteTab(tab.TabID, this.PortalId); + } + } + + private void ExecuteTestForTab(TabInfo tab, FriendlyUrlSettings settings, Dictionary testFields) + { + var httpAlias = testFields.GetValue("Alias", string.Empty); + var scheme = testFields["Scheme"]; + var url = testFields["Test Url"]; + var result = testFields["Expected Url"]; + var expectedStatus = int.Parse(testFields["Status"]); + var redirectUrl = testFields.GetValue("Final Url"); + var redirectReason = testFields.GetValue("RedirectReason"); + + var tabID = (tab == null) ? "-1" : tab.TabID.ToString(); + + var expectedResult = this.ReplaceTokens(testFields, result, tabID); + var testurl = this.ReplaceTokens(testFields, url, tabID); + var expectedRedirectUrl = this.ReplaceTokens(testFields, redirectUrl, tabID); + + 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(), + }; + + this.ProcessRequest(settings, testHelper); + + // Test expected response status + Assert.AreEqual(expectedStatus, testHelper.Response.StatusCode); + + switch (expectedStatus) + { + case 200: + // Test expected rewrite path + if (!string.IsNullOrEmpty(expectedResult)) + { + Assert.AreEqual(expectedResult, testHelper.Result.RewritePath.TrimStart('/')); + } + + break; + case 301: + case 302: + // Test for final Url if redirected + Assert.IsTrue(expectedRedirectUrl.Equals(testHelper.Result.FinalUrl.TrimStart('/'), StringComparison.InvariantCultureIgnoreCase)); + Assert.AreEqual(redirectReason, testHelper.Result.Reason.ToString(), "Redirect reason incorrect"); + break; + } + } + + private void ExecuteTest(FriendlyUrlSettings settings, Dictionary testFields, bool setDefaultAlias) + { + var tabName = testFields["Page Name"]; + var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); + + if (setDefaultAlias) + { + this.SetDefaultAlias(testFields); + } + + this.ExecuteTestForTab(tab, settings, testFields); + } + + private void UpdateTab(TabInfo tab) + { + if (tab != null) + { + TabController.Instance.UpdateTab(tab); + } + } + + private void UpdateTabName(int tabId, string newName) + { + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); + tab.TabName = newName; + TabController.Instance.UpdateTab(tab); + } + + private void UpdateTabSkin(int tabId, string newSkin) + { + var tab = TabController.Instance.GetTab(tabId, this.PortalId, false); + tab.SkinSrc = newSkin; + TabController.Instance.UpdateTab(tab); + } + private int UpdateHomeTab(int homeTabId) { var portalInfo = PortalController.Instance.GetPortal(this.PortalId); @@ -678,6 +678,6 @@ private void UpdateTabSetting(string tabName, string settingName, string setting var tab = TabController.Instance.GetTabByName(tabName, this.PortalId); tab.TabSettings[settingName] = settingValue; TabController.Instance.UpdateTab(tab); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs index 10c0b8c5496..4de173001c0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestBase.cs @@ -16,18 +16,18 @@ namespace DotNetNuke.Tests.Urls public class UrlTestBase : DnnWebTest { - public UrlTestBase(int portalId) + public UrlTestBase(int portalId) : base(portalId) { } + protected virtual string TestType + { + get { return string.Empty; } + } + protected virtual string DefaultAlias { get; private set; } - protected virtual string TestType - { - get { return string.Empty; } - } - public virtual void SetUp() { this.ExecuteScriptFile(string.Format("{0}\\{1}\\{2}", this.TestType, this.GetTestFolder(), "SetUp.sql")); @@ -46,8 +46,8 @@ public virtual void TearDown() public virtual void TestFixtureTearDown() { this.ExecuteScriptFile(string.Format("{0}\\{1}", this.TestType, "TearDown.sql")); - } - + } + protected void CreateTab(string tabName) { var tab = new TabInfo { PortalID = this.PortalId, TabName = tabName }; @@ -72,6 +72,19 @@ protected void SetDefaultAlias(Dictionary testFields) this.SetDefaultAlias(testFields["Alias"]); } + protected void SetDefaultAlias(string defaultAlias) + { + foreach (var alias in PortalAliasController.Instance.GetPortalAliasesByPortalId(this.PortalId)) + { + if (string.Equals(alias.HTTPAlias, defaultAlias, StringComparison.InvariantCultureIgnoreCase)) + { + alias.IsPrimary = true; + PortalAliasController.Instance.UpdatePortalAlias(alias); + break; + } + } + } + private void ExecuteScriptFile(string fileName) { var sql = TestUtil.ReadStream(fileName); @@ -87,18 +100,5 @@ 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)) - { - if (string.Equals(alias.HTTPAlias, defaultAlias, StringComparison.InvariantCultureIgnoreCase)) - { - alias.IsPrimary = true; - PortalAliasController.Instance.UpdatePortalAlias(alias); - break; - } - } - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs index 0fc4b40a55a..f650a3f25e4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestFactoryClass.cs @@ -49,115 +49,6 @@ internal static IEnumerable FriendlyUrl_ImprovedTestCases } } - internal static FriendlyUrlSettings GetSettings(string testType, string testName, int portalId) - { - return GetSettings(testType, testName, "Settings", portalId); - } - - internal static FriendlyUrlSettings GetSettings(string testType, string testName, string settingsFile, int portalId) - { - var settings = new FriendlyUrlSettings(portalId); - - // 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(); - - var type = typeof(FriendlyUrlSettings); - var property = type.GetProperty(key); - if (property != null) - { - if (property.PropertyType == typeof(bool)) - { - property.SetValue(settings, Convert.ToBoolean(value), null); - } - else if (property.PropertyType == typeof(int)) - { - property.SetValue(settings, Convert.ToInt32(value), null); - } - else if (property.PropertyType.BaseType == typeof(Enum)) - { - property.SetValue(settings, Enum.Parse(property.PropertyType, value), null); - } - else - { - property.SetValue(settings, value, null); - } - } - }); - return settings; - } - - private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) - { - TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => - { - string[] fields = line.Split(','); - GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); - }); - } - - private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) - { - try - { - // 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', '"' }); - - fieldList[key] = val; - } - - string name = testName + "_"; - if (!string.IsNullOrEmpty(testPrefix)) - { - name += testPrefix + "_"; - } - - name += fields[0]; - - testData.Add(new TestCaseData(fieldList).SetName(name)); - }); - } - - // ReSharper disable RedundantCatchClause -#pragma warning disable 168 - catch (Exception exc) -#pragma warning restore 168 - { - throw; - } - - // ReSharper restore RedundantCatchClause - } - - internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) - { - var dictionary = new Dictionary(); - - // 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(); - - dictionary.Add(key, value); - }); - return dictionary; - } - internal static IEnumerable FriendlyUrl_PageExtensionTestCases { get @@ -398,5 +289,114 @@ internal static IEnumerable UrlRewrite_VanityUrlTestCases return testData; } } + + internal static FriendlyUrlSettings GetSettings(string testType, string testName, int portalId) + { + return GetSettings(testType, testName, "Settings", portalId); + } + + internal static FriendlyUrlSettings GetSettings(string testType, string testName, string settingsFile, int portalId) + { + var settings = new FriendlyUrlSettings(portalId); + + // 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(); + + var type = typeof(FriendlyUrlSettings); + var property = type.GetProperty(key); + if (property != null) + { + if (property.PropertyType == typeof(bool)) + { + property.SetValue(settings, Convert.ToBoolean(value), null); + } + else if (property.PropertyType == typeof(int)) + { + property.SetValue(settings, Convert.ToInt32(value), null); + } + else if (property.PropertyType.BaseType == typeof(Enum)) + { + property.SetValue(settings, Enum.Parse(property.PropertyType, value), null); + } + else + { + property.SetValue(settings, value, null); + } + } + }); + return settings; + } + + internal static Dictionary GetDictionary(string testType, string testName, string settingsFile) + { + var dictionary = new Dictionary(); + + // 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(); + + dictionary.Add(key, value); + }); + return dictionary; + } + + private static void GetTestsWithAliases(string testType, string testName, ArrayList testData) + { + TestUtil.ReadStream(string.Format("{0}", "Aliases"), (line, header) => + { + string[] fields = line.Split(','); + GetTests(fields[1].Trim(), fields[0].Trim(), testType, testName, testData); + }); + } + + private static void GetTests(string testPrefix, string alias, string testType, string testName, ArrayList testData) + { + try + { + // 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', '"' }); + + fieldList[key] = val; + } + + string name = testName + "_"; + if (!string.IsNullOrEmpty(testPrefix)) + { + name += testPrefix + "_"; + } + + name += fields[0]; + + testData.Add(new TestCaseData(fieldList).SetName(name)); + }); + } + + // ReSharper disable RedundantCatchClause +#pragma warning disable 168 + catch (Exception exc) +#pragma warning restore 168 + { + throw; + } + + // ReSharper restore RedundantCatchClause + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs index 7a21392def7..3060eaabcac 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Urls/UrlTestHelper.cs @@ -13,13 +13,13 @@ namespace DotNetNuke.Tests.Urls internal class UrlTestHelper { public Uri RequestUri { get; set; } - + public UrlAction Result { get; set; } - + public NameValueCollection QueryStringCol { get; set; } - + public string HttpAliasFull { get; set; } - + public HttpResponse Response { get; set; } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs index 41fd7e82ecf..e9f2c5064be 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Constants.cs @@ -10,11 +10,11 @@ namespace DotNetNuke.Tests.Utilities using DotNetNuke.Entities.Content.Taxonomy; public class Constants - { + { public const string CACHEING_InValidKey = "InValidKey"; public const string CACHEING_ParamCacheKey = "CacheKey"; public const string CACHEING_ValidKey = "ValidKey"; - public const string CACHEING_ValidValue = "ValidValue"; + public const string CACHEING_ValidValue = "ValidValue"; public const int USER_Null = -1; public const int USER_ValidId = 200; public const int USER_InValidId = 42; @@ -36,7 +36,7 @@ public class Constants public const string UserDisplayName_FirstSocialGroupOwner = "First Social Group Owner"; public const string RuFirstName = "TestUser"; public const string RuLastName = "Automation"; - public const string DefaultPassword = "dnnhost"; + public const string DefaultPassword = "dnnhost"; public const int RoleID_Administrators = 0; public const int RoleID_RegisteredUsers = 1; public const int RoleID_Subscribers = 2; @@ -47,13 +47,13 @@ public class Constants public const string RoleName_RegisteredUsers = "RegisteredUsers"; public const string RoleName_Subscribers = "Subscribers"; public const string RoleName_Translator_EN_US = "translator_EN_US"; - public const string RoleName_FirstSocialGroup = "First Social Group"; + public const string RoleName_FirstSocialGroup = "First Social Group"; public const int PORTAL_Zero = 0; public const int PORTAL_One = 1; public const int PORTAL_Null = -1; public const int PORTAL_InValidPortalId = -1; - public const int PORTAL_ValidPortalId = 1; - + public const int PORTAL_ValidPortalId = 1; + /// The setting name that stores whether attachments are allowed. public const string PORTALSETTING_MessagingAllowAttachments_Name = "MessagingAllowAttachments"; @@ -61,8 +61,8 @@ public class Constants public const string PORTALSETTING_MessagingIncludeAttachments_Name = "MessagingIncludeAttachments"; public const string PORTALSETTING_MessagingAllowAttachments_Value_YES = "YES"; - public const string PORTALSETTING_MessagingAllowAttachments_Value_NO = "NO"; - public const string CULTURE_EN_US = "en-US"; + public const string PORTALSETTING_MessagingAllowAttachments_Value_NO = "NO"; + public const string CULTURE_EN_US = "en-US"; public const int PORTALGROUP_ValidPortalGroupId = 1; public const int PORTALGROUP_AddPortalGroupId = 2; public const int PORTALGROUP_DeletePortalGroupId = 3; @@ -77,9 +77,9 @@ public class Constants public const int PORTALGROUP_ValidPortalGroupCount = 5; public const string PORTALGROUP_ValidNameFormat = "PortalGroupName {0}"; - public const string PORTALGROUP_ValidDescriptionFormat = "PortalGroupDescription {0}"; - - // Valid Content values + public const string PORTALGROUP_ValidDescriptionFormat = "PortalGroupDescription {0}"; + + // Valid Content values public const int CONTENT_ValidContentItemId = 1; public const string CONTENT_ValidContent = "Content"; public const string CONTENT_ValidContentKey = "ContentKey"; @@ -121,7 +121,7 @@ public class Constants public const string CONTENT_NewMetaDataValue = "My abstract"; public const string CONTENT_InValidMetaDataName = "InvalidName"; public const string CONTENT_InValidMetaDataValue = "InvalidValue"; - public const int CONTENT_MetaDataCount = 4; + public const int CONTENT_MetaDataCount = 4; public const int CONTENTTYPE_ValidContentTypeId = 1; public const string CONTENTTYPE_ValidContentType = "ContentType Name"; @@ -170,7 +170,7 @@ public class Constants public const int CONTENTTYPE_ValidContentTemplateId = 2; public const int CONTENTTYPE_ValidContentTemplateCount = 7; public const int CONTENTTYPE_InValidContentTemplateId = -1; - public const int CONTENTTYPE_UpdateContentTemplateId = 4; + public const int CONTENTTYPE_UpdateContentTemplateId = 4; public const int SCOPETYPE_ValidScopeTypeId = 1; public const string SCOPETYPE_ValidScopeType = "ScopeType Name"; @@ -187,12 +187,12 @@ public class Constants public const string SCOPETYPE_GetByNameScopeType = "TestGetByName"; public const string SCOPETYPE_OriginalUpdateScopeType = "TestUpdate"; - public const string SCOPETYPE_UpdateScopeType = "Update Name"; + public const string SCOPETYPE_UpdateScopeType = "Update Name"; public const int TAG_DuplicateContentItemId = 1; public const int TAG_DuplicateTermId = 6; public const int TAG_NoContentContentId = 99; public const int TAG_ValidContentId = 1; - public const int TAG_ValidContentCount = 2; + public const int TAG_ValidContentCount = 2; public const string TERM_CacheKey = "DNN_Terms_{0}"; public const int TERM_ValidTermId = 1; @@ -224,7 +224,7 @@ public class Constants public const int TERM_ValidCountForContent1 = 2; public const int TERM_ValidContent1 = 1; - public const int TERM_ValidContent2 = 2; + public const int TERM_ValidContent2 = 2; public const string VOCABULARY_CacheKey = "DNN_Vocabularies"; public const int VOCABULARY_ValidVocabularyId = 1; @@ -258,7 +258,7 @@ public class Constants public const string VOCABULARY_ValidNameFormat = "Vocabulary Name {0}"; public const int VOCABULARY_ValidCountForScope1 = 2; public const int VOCABULARY_ValidScope1 = 1; - public const int VOCABULARY_ValidScope2 = 2; + public const int VOCABULARY_ValidScope2 = 2; public const int FOLDER_ValidFileId = 1; public const int FOLDER_InvalidFileId = -1; public const int FOLDER_ValidFileSize = 16; @@ -294,7 +294,7 @@ public class Constants public const string FOLDER_OtherValidSubFolderRelativePath = "folder/othersubfolder/"; public const string FOLDER_ModifiedFileHash = "0123456789X"; public const string FOLDER_UnmodifiedFileHash = "0123456789"; - public const string FOLDER_FileStartDate = "2010-01-01T00:00:00"; + public const string FOLDER_FileStartDate = "2010-01-01T00:00:00"; public const int SOCIAL_InValidRelationshipType = 999; public const int SOCIAL_InValidRelationship = 999; public const int SOCIAL_InValidUserRelationship = 999; @@ -329,13 +329,13 @@ public class Constants public const string LOCALIZATION_UserRelationship_Added = "Added UserRelationship ID {0}, UserID {1}, RelatedUserID {2}"; public const string LOCALIZATION_UserRelationship_Updated_Key = "UserRelationship_Updated"; public const string LOCALIZATION_UserRelationship_Updated = "Updated UserRelationship ID {0}, UserID {1}, RelatedUserID {2}"; - + public const string LOCALIZATION_UserRelationshipPreference_Deleted_Key = "UserRelationshipPreference_Deleted"; public const string LOCALIZATION_UserRelationshipPreference_Deleted = "Deleted UserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const string LOCALIZATION_UserRelationshipPreference_Added_Key = "UserRelationshipPreference_Added"; public const string LOCALIZATION_UserRelationshipPreference_Added = "Added UserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const string LOCALIZATION_UserRelationshipPreference_Updated_Key = "UserRelationshipPreference_Updated"; - public const string LOCALIZATION_UserRelationshipPreference_Updated = "UpdatedUserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; + public const string LOCALIZATION_UserRelationshipPreference_Updated = "UpdatedUserRelationshipPreference ID {0} for User ID {1} and Relationship ID {2}"; public const bool Messaging_ReadMessage = true; public const bool Messaging_UnReadMessage = false; public const bool Messaging_ArchivedMessage = true; @@ -358,7 +358,7 @@ public class Constants public const string Messaging_NotificationSubject = "Friend Request Received"; public const string Messaging_NotificationBody = "You've received a new friend request from {0}"; public const bool Messaging_IncludeDismissAction = true; - public const string Messaging_NotificationContext = "context"; + public const string Messaging_NotificationContext = "context"; public const string COLUMNNAME_Name = "Name"; public const string COLUMNNAME_PersonName = "PersonName"; @@ -395,12 +395,12 @@ public class Constants public const string CACHE_ScopeModule = "ModuleId"; public const int CACHE_TimeOut = 10; public const CacheItemPriority CACHE_Priority = CacheItemPriority.High; - + public const string TABLENAME_Dog = "Dogs"; public const string TABLENAME_Key = "ID"; public const string TABLENAME_Prefix = "dnn_"; public const string TABLENAME_Person = "People"; - public const string TABLENAME_Person_Key = "PersonID"; + public const string TABLENAME_Person_Key = "PersonID"; public const int PAGE_First = 0; public const int PAGE_Second = 1; public const int PAGE_Last = 4; @@ -408,7 +408,7 @@ public class Constants public const int PAGE_TotalCount = 22; public const int PAGE_NegativeIndex = -1; - public const int PAGE_OutOfRange = 5; + public const int PAGE_OutOfRange = 5; public const int TAB_ValidId = 10; public const int TAB_InValidId = -1; public const int MODULE_ValidId = 100; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs index 090b0467461..659c639bc51 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ContentTestHelper.cs @@ -46,13 +46,13 @@ 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 5e2eb43bef3..9d17baed2b2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/DnnWebTest.cs @@ -73,7 +73,7 @@ public DnnWebTest(int portalId) this.PortalId = portalId; } - + public int PortalId { get; private set; } private static void InstallComponents() @@ -111,8 +111,8 @@ private static void InstallComponents() ComponentFactory.InstallComponents(new ProviderInstaller("clientcapability", typeof(ClientCapabilityProvider))); } - private static void RegisterIfNotAlreadyRegistered() - where TConcrete : class, new() + private static void RegisterIfNotAlreadyRegistered() + where TConcrete : class, new() { RegisterIfNotAlreadyRegistered(string.Empty); } @@ -145,7 +145,7 @@ private static void LoadDnnProviders(string providerList) { return; } - + alreadyLoaded = true; if (providerList != null) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs index 9917c138cdb..82e5b6c31ea 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/ExceptionAssert.cs @@ -21,14 +21,14 @@ public static class ExceptionAssert // { // Throws(act, ex => ex.Message.Equals(message, StringComparison.Ordinal)); // } - public static void Throws(string message, Action act, Predicate checker) - where TException : Exception + public static void Throws(string message, Action act, Predicate checker) + where TException : Exception { Throws(act, ex => ex.Message.Equals(message, StringComparison.Ordinal) && checker(ex)); } - public static void Throws(Action act, Predicate checker) - where TException : Exception + public static void Throws(Action act, Predicate checker) + where TException : Exception { bool matched = false; bool thrown = false; @@ -53,14 +53,14 @@ public static void Throws(Action act, Predicate checker) { throw; } - + tex = tiex.InnerException as TException; if (tex == null) { throw; } } - + thrown = true; matched = checker(tex); if (!matched) @@ -86,7 +86,7 @@ public static void ThrowsArgNull(string paramName, Action act) public static void ThrowsArgNullOrEmpty(string paramName, Action act) { - Throws( + Throws( string.Format("Argument cannot be null or an empty string{1}Parameter name: {0}", paramName, Environment.NewLine), act, ex => string.Equals(ex.ParamName, paramName, StringComparison.Ordinal)); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs index 3f99fec9bc0..5af6b2c1155 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpContextHelper.cs @@ -27,7 +27,7 @@ public static Mock RegisterMockHttpContext() HttpContextSource.RegisterInstance(mock.Object); return mock; } - + private static Mock CrateMockHttpContext() { var context = new Mock(); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs index df689d674aa..46499fef5ae 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulator.cs @@ -33,10 +33,10 @@ public enum HttpVerb public class HttpSimulator : IDisposable { private static readonly string WebsitePhysicalAppPath = ConfigurationManager.AppSettings["DefaultPhysicalAppPath"]; - private StringBuilder _builder; - private Uri _referer; private readonly NameValueCollection _formVars = new NameValueCollection(); private readonly NameValueCollection _headers = new NameValueCollection(); + private StringBuilder _builder; + private Uri _referer; private string _applicationPath = "/"; @@ -44,12 +44,12 @@ public class HttpSimulator : IDisposable private string _physicalPath = WebsitePhysicalAppPath; - public HttpSimulator() + public HttpSimulator() : this("/", WebsitePhysicalAppPath) { } - public HttpSimulator(string applicationPath) + public HttpSimulator(string applicationPath) : this(applicationPath, WebsitePhysicalAppPath) { } @@ -60,18 +60,77 @@ public HttpSimulator(string applicationPath, string physicalApplicationPath) this.PhysicalApplicationPath = physicalApplicationPath; } + /// + /// Gets physical path to the requested file (used for simulation purposes). + /// + public string PhysicalPath + { + get { return this._physicalPath; } + } + + /// + /// Gets the text from the response to the simulated request. + /// + public string ResponseText + { + get + { + return (this._builder ?? new StringBuilder()).ToString(); + } + } + public string Host { get; private set; } public string LocalPath { get; private set; } public int Port { get; private set; } + /// + /// Gets portion of the URL after the application. + /// + public string Page { get; private set; } + + /// + /// Gets or sets the same thing as the IIS Virtual directory. It's + /// what gets returned by Request.ApplicationPath. + /// + public string ApplicationPath + { + get { return this._applicationPath; } + + set + { + this._applicationPath = value ?? "/"; + this._applicationPath = NormalizeSlashes(this._applicationPath); + } + } + + /// + /// Gets or sets physical path to the application (used for simulation purposes). + /// + public string PhysicalApplicationPath + { + get { return this._physicalApplicationPath; } + + set + { + this._physicalApplicationPath = value ?? WebsitePhysicalAppPath; + + // strip trailing backslashes. + this._physicalApplicationPath = StripTrailingBackSlashes(this._physicalApplicationPath) + @"\"; + } + } + + public TextWriter ResponseWriter { get; set; } + + public SimulatedHttpRequest WorkerRequest { get; private set; } + /// /// Sets up the HttpContext objects to simulate a GET request. /// /// /// Simulates a request to http://localhost/. - /// + /// /// public HttpSimulator SimulateRequest() { @@ -81,7 +140,7 @@ public HttpSimulator SimulateRequest() /// /// Sets up the HttpContext objects to simulate a GET request. /// - /// + /// /// public HttpSimulator SimulateRequest(Uri url) { @@ -92,7 +151,7 @@ public HttpSimulator SimulateRequest(Uri url) /// Sets up the HttpContext objects to simulate a request. /// /// - /// + /// /// public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb) { @@ -103,7 +162,7 @@ public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb) /// Sets up the HttpContext objects to simulate a POST request. /// /// - /// + /// /// public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables) { @@ -115,7 +174,7 @@ public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables) /// /// /// - /// + /// /// public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables, NameValueCollection headers) { @@ -127,7 +186,7 @@ public HttpSimulator SimulateRequest(Uri url, NameValueCollection formVariables, /// /// /// - /// + /// /// public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection headers) { @@ -141,11 +200,11 @@ public HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollec /// public HttpSimulator SetReferer(Uri referer) { - if (this.WorkerRequest != null) - { - this.WorkerRequest.SetReferer(referer); - } - + if (this.WorkerRequest != null) + { + this.WorkerRequest.SetReferer(referer); + } + this._referer = referer; return this; } @@ -158,11 +217,11 @@ public HttpSimulator SetReferer(Uri referer) /// public HttpSimulator SetFormVariable(string name, string value) { - if (this.WorkerRequest != null) - { - throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); - } - + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set form variables after calling Simulate()."); + } + this._formVars.Add(name, value); return this; @@ -176,23 +235,83 @@ public HttpSimulator SetFormVariable(string name, string value) /// public HttpSimulator SetHeader(string name, string value) { - if (this.WorkerRequest != null) - { - throw new InvalidOperationException("Cannot set headers after calling Simulate()."); - } - + if (this.WorkerRequest != null) + { + throw new InvalidOperationException("Cannot set headers after calling Simulate()."); + } + this._headers.Add(name, value); return this; } + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + /// 2. + public void Dispose() + { + HttpContext.Current = null; + } + + protected static HostingEnvironment GetHostingEnvironment() + { + HostingEnvironment environment; + try + { + environment = new HostingEnvironment(); + } + catch (InvalidOperationException) + { + // Shoot, we need to grab it via reflection. + environment = ReflectionHelper.GetStaticFieldValue("_theHostingEnvironment", typeof(HostingEnvironment)); + } + + return environment; + } + + protected static string NormalizeSlashes(string s) + { + if (string.IsNullOrEmpty(s) || s == "/") + { + return "/"; + } + + s = s.Replace(@"\", "/"); + + // Reduce multiple slashes in row to single. + var normalized = Regex.Replace(s, "(/)/+", "$1"); + + // Strip left. + normalized = StripPrecedingSlashes(normalized); + + // Strip right. + normalized = StripTrailingSlashes(normalized); + return "/" + normalized; + } + + protected static string StripPrecedingSlashes(string s) + { + return Regex.Replace(s, "^/*(.*)", "$1"); + } + + protected static string StripTrailingSlashes(string s) + { + return Regex.Replace(s, "(.*)/*$", "$1", RegexOptions.RightToLeft); + } + + protected static string StripTrailingBackSlashes(string s) + { + return string.IsNullOrEmpty(s) ? string.Empty : Regex.Replace(s, @"(.*)\\*$", "$1", RegexOptions.RightToLeft); + } + /// /// Sets up the HttpContext objects to simulate a request. /// /// /// /// - /// + /// /// protected virtual HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, NameValueCollection formVariables, NameValueCollection headers) { @@ -210,56 +329,56 @@ protected virtual HttpSimulator SimulateRequest(Uri url, HttpVerb httpVerb, Name var query = ExtractQueryStringPart(url); - if (formVariables != null) - { - this._formVars.Add(formVariables); - } - - if (this._formVars.Count > 0) - { - httpVerb = HttpVerb.POST; // Need to enforce this. - } - - if (headers != null) - { - this._headers.Add(headers); - } - + if (formVariables != null) + { + this._formVars.Add(formVariables); + } + + if (this._formVars.Count > 0) + { + httpVerb = HttpVerb.POST; // Need to enforce this. + } + + if (headers != null) + { + this._headers.Add(headers); + } + this.WorkerRequest = new SimulatedHttpRequest(this.ApplicationPath, this.PhysicalApplicationPath, this.PhysicalPath, this.Page, query, this.ResponseWriter, this.Host, this.Port, httpVerb.ToString()); this.WorkerRequest.Form.Add(this._formVars); this.WorkerRequest.Headers.Add(this._headers); - if (this._referer != null) - { - this.WorkerRequest.SetReferer(this._referer); - } - + if (this._referer != null) + { + this.WorkerRequest.SetReferer(this._referer); + } + this.InitializeSession(); - InitializeApplication(); - - // Console.WriteLine("host: " + Host); - // Console.WriteLine("virtualDir: " + _applicationPath); - // Console.WriteLine("page: " + LocalPath); - // Console.WriteLine("pathPartAfterApplicationPart: " + Page); - // Console.WriteLine("appPhysicalDir: " + _physicalApplicationPath); - // if (HttpContext.Current != null) - // { - // Console.WriteLine("Request.Url.LocalPath: " + HttpContext.Current.Request.Url.LocalPath); - // Console.WriteLine("Request.Url.Host: " + HttpContext.Current.Request.Url.Host); - // Console.WriteLine("Request.FilePath: " + HttpContext.Current.Request.FilePath); - // Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path); - // Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl); - // Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url); - // Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port); - // Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath); - // Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath); - // } - // Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath); - // Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath); - // Console.WriteLine("HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath); - // Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath); + InitializeApplication(); + + // Console.WriteLine("host: " + Host); + // Console.WriteLine("virtualDir: " + _applicationPath); + // Console.WriteLine("page: " + LocalPath); + // Console.WriteLine("pathPartAfterApplicationPart: " + Page); + // Console.WriteLine("appPhysicalDir: " + _physicalApplicationPath); + // if (HttpContext.Current != null) + // { + // Console.WriteLine("Request.Url.LocalPath: " + HttpContext.Current.Request.Url.LocalPath); + // Console.WriteLine("Request.Url.Host: " + HttpContext.Current.Request.Url.Host); + // Console.WriteLine("Request.FilePath: " + HttpContext.Current.Request.FilePath); + // Console.WriteLine("Request.Path: " + HttpContext.Current.Request.Path); + // Console.WriteLine("Request.RawUrl: " + HttpContext.Current.Request.RawUrl); + // Console.WriteLine("Request.Url: " + HttpContext.Current.Request.Url); + // Console.WriteLine("Request.Url.Port: " + HttpContext.Current.Request.Url.Port); + // Console.WriteLine("Request.ApplicationPath: " + HttpContext.Current.Request.ApplicationPath); + // Console.WriteLine("Request.PhysicalPath: " + HttpContext.Current.Request.PhysicalPath); + // } + // Console.WriteLine("HttpRuntime.AppDomainAppPath: " + HttpRuntime.AppDomainAppPath); + // Console.WriteLine("HttpRuntime.AppDomainAppVirtualPath: " + HttpRuntime.AppDomainAppVirtualPath); + // Console.WriteLine("HostingEnvironment.ApplicationPhysicalPath: " + HostingEnvironment.ApplicationPhysicalPath); + // Console.WriteLine("HostingEnvironment.ApplicationVirtualPath: " + HostingEnvironment.ApplicationVirtualPath); return this; } @@ -270,6 +389,39 @@ private static void InitializeApplication() ReflectionHelper.SetPrivateInstanceFieldValue("_state", appFactory, HttpContext.Current.Application); } + private static string RightAfter(string original, string search) + { + if (search.Length > original.Length || search.Length == 0) + { + return original; + } + + original = original.Trim(); + search = search.Trim(); + var searchIndex = original.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase); + + if (searchIndex < 0) + { + return original; + } + + // mod to add one onto the search length - otherwise strange results?? + // return original.Substring(original.IndexOf(search) + search.Length + 1); + // return original.Substring(original.IndexOf(search) + search.Length); + // original = original.Substring(searchIndex, original.Length - searchIndex); + // return original.Replace(search,""); + var regexMatch = @"(" + search + ")(?.+)"; + const string regexReplace = @"${keep}"; + var result = Regex.Replace(original, regexMatch, regexReplace, RegexOptions.IgnoreCase); + return result; + } + + private static string ExtractQueryStringPart(Uri url) + { + var query = url.Query; + return query.StartsWith("?") ? query.Substring(1) : query; + } + private void InitializeSession() { HttpContext.Current = new HttpContext(this.WorkerRequest); @@ -279,13 +431,51 @@ private void InitializeSession() HttpContext.Current.Items.Add("AspSession", session); } + 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("/", @"\")); + } + + 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)); + } + public class FakeHttpSessionState : NameObjectCollectionBase, IHttpSessionState { private const bool _isNewSession = true; private readonly string _sessionId = Guid.NewGuid().ToString(); - private int _timeout = 30; // minutes private readonly HttpStaticObjectsCollection _staticObjects = new HttpStaticObjectsCollection(); private readonly object _syncRoot = new object(); + private int _timeout = 30; // minutes /// /// Gets the unique session identifier for the session. @@ -301,138 +491,107 @@ public string SessionID } /// - /// Gets or sets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. + /// Gets a value indicating whether the session was created with the current request. /// /// /// - /// The time-out period, in minutes. + /// true if the session was created with the current request; otherwise, false. /// /// - public int Timeout + public bool IsNewSession { - get { return this._timeout; } - set { this._timeout = value; } + get { return _isNewSession; } } /// - /// Gets a value indicating whether the session was created with the current request. + /// Gets the current session-state mode. /// /// /// - /// true if the session was created with the current request; otherwise, false. + /// One of the values. /// /// - public bool IsNewSession + public SessionStateMode Mode { - get { return _isNewSession; } + get { return SessionStateMode.InProc; } } /// - /// Ends the current session. + /// Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie. /// /// - public void Abandon() + /// + /// true if the session is embedded in the URL; otherwise, false. + /// + /// + public bool IsCookieless { - this.BaseClear(); + get { return false; } } /// - /// Adds a new item to the session-state collection. + /// Gets a value that indicates whether the application is configured for cookieless sessions. /// /// - /// The name of the item to add to the session-state collection. - /// The value of the item to add to the session-state collection. - public void Add(string name, object value) + /// + /// One of the values that indicate whether the application is configured for cookieless sessions. The default is . + /// + /// + public HttpCookieMode CookieMode { - this.BaseAdd(name, value); + get { return HttpCookieMode.UseCookies; } } /// - /// Deletes an item from the session-state item collection. + /// Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax. /// /// - /// The name of the item to delete from the session-state item collection. - public void Remove(string name) - { - this.BaseRemove(name); - } - - /// - /// Deletes an item at a specified index from the session-state item collection. - /// - /// - /// The index of the item to remove from the session-state collection. - public void RemoveAt(int index) - { - this.BaseRemoveAt(index); - } - - /// - /// Clears all values from the session-state item collection. - /// - /// - public void Clear() - { - this.BaseClear(); - } - - /// - /// Clears all values from the session-state item collection. - /// - /// - public void RemoveAll() - { - this.BaseClear(); - } - - /// - /// Copies the collection of session-state item values to a one-dimensional array, starting at the specified index in the array. - /// + /// + /// An containing objects declared in the Global.asax file. + /// /// - /// The that receives the session values. - /// The index in array where copying starts. - public void CopyTo(Array array, int index) + public HttpStaticObjectsCollection StaticObjects { - throw new NotImplementedException(); + get { return this._staticObjects; } } /// - /// Gets the current session-state mode. + /// Gets an object that can be used to synchronize access to the collection of session-state values. /// /// /// - /// One of the values. + /// An object that can be used to synchronize access to the collection. /// /// - public SessionStateMode Mode + public object SyncRoot { - get { return SessionStateMode.InProc; } + get { return this._syncRoot; } } /// - /// Gets a value indicating whether the session ID is embedded in the URL or stored in an HTTP cookie. + /// Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe). /// - /// /// - /// true if the session is embedded in the URL; otherwise, false. + /// true if access to the collection is synchronized (thread safe); otherwise, false. /// /// - public bool IsCookieless + public bool IsSynchronized { - get { return false; } + get { return true; } } /// - /// Gets a value that indicates whether the application is configured for cookieless sessions. + /// Gets or sets and sets the time-out period (in minutes) allowed between requests before the session-state provider terminates the session. /// /// /// - /// One of the values that indicate whether the application is configured for cookieless sessions. The default is . + /// The time-out period, in minutes. /// /// - public HttpCookieMode CookieMode + public int Timeout { - get { return HttpCookieMode.UseCookies; } + get { return this._timeout; } + set { this._timeout = value; } } /// @@ -455,44 +614,6 @@ public HttpCookieMode CookieMode /// public int CodePage { get; set; } - /// - /// Gets a collection of objects declared by <object Runat="Server" Scope="Session"/> tags within the ASP.NET application file Global.asax. - /// - /// - /// - /// An containing objects declared in the Global.asax file. - /// - /// - public HttpStaticObjectsCollection StaticObjects - { - get { return this._staticObjects; } - } - - /// - /// Gets an object that can be used to synchronize access to the collection of session-state values. - /// - /// - /// - /// An object that can be used to synchronize access to the collection. - /// - /// - public object SyncRoot - { - get { return this._syncRoot; } - } - - /// - /// Gets a value indicating whether access to the collection of session-state values is synchronized (thread safe). - /// - /// - /// true if access to the collection is synchronized (thread safe); otherwise, false. - /// - /// - public bool IsSynchronized - { - get { return true; } - } - /// /// Gets a value indicating whether the session is read-only. /// @@ -538,202 +659,81 @@ public object this[int index] get { return this.BaseGet(index); } set { this.BaseSet(index, value); } } - } - - private static string RightAfter(string original, string search) - { - if (search.Length > original.Length || search.Length == 0) - { - return original; - } - - original = original.Trim(); - search = search.Trim(); - var searchIndex = original.IndexOf(search, 0, StringComparison.InvariantCultureIgnoreCase); - if (searchIndex < 0) - { - return original; - } - - // mod to add one onto the search length - otherwise strange results?? - // return original.Substring(original.IndexOf(search) + search.Length + 1); - // return original.Substring(original.IndexOf(search) + search.Length); - // original = original.Substring(searchIndex, original.Length - searchIndex); - // return original.Replace(search,""); - var regexMatch = @"(" + search + ")(?.+)"; - const string regexReplace = @"${keep}"; - var result = Regex.Replace(original, regexMatch, regexReplace, RegexOptions.IgnoreCase); - return result; - } - - 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; } - - /// - /// Gets or sets the same thing as the IIS Virtual directory. It's - /// what gets returned by Request.ApplicationPath. - /// - public string ApplicationPath - { - get { return this._applicationPath; } - - set + /// + /// Ends the current session. + /// + /// + public void Abandon() { - this._applicationPath = value ?? "/"; - this._applicationPath = NormalizeSlashes(this._applicationPath); + this.BaseClear(); } - } - /// - /// Gets or sets physical path to the application (used for simulation purposes). - /// - public string PhysicalApplicationPath - { - get { return this._physicalApplicationPath; } - - set + /// + /// Adds a new item to the session-state collection. + /// + /// + /// The name of the item to add to the session-state collection. + /// The value of the item to add to the session-state collection. + public void Add(string name, object value) { - this._physicalApplicationPath = value ?? WebsitePhysicalAppPath; - - // strip trailing backslashes. - this._physicalApplicationPath = StripTrailingBackSlashes(this._physicalApplicationPath) + @"\"; + this.BaseAdd(name, value); } - } - - /// - /// Gets physical path to the requested file (used for simulation purposes). - /// - public string PhysicalPath - { - get { return this._physicalPath; } - } - - public TextWriter ResponseWriter { get; set; } - /// - /// Gets the text from the response to the simulated request. - /// - public string ResponseText - { - get + /// + /// Deletes an item from the session-state item collection. + /// + /// + /// The name of the item to delete from the session-state item collection. + public void Remove(string name) { - return (this._builder ?? new StringBuilder()).ToString(); + this.BaseRemove(name); } - } - - public SimulatedHttpRequest WorkerRequest { get; private set; } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - /// 2. - public void Dispose() - { - HttpContext.Current = null; - } - protected static HostingEnvironment GetHostingEnvironment() - { - HostingEnvironment environment; - try + /// + /// Deletes an item at a specified index from the session-state item collection. + /// + /// + /// The index of the item to remove from the session-state collection. + public void RemoveAt(int index) { - environment = new HostingEnvironment(); + this.BaseRemoveAt(index); } - catch (InvalidOperationException) + + /// + /// Clears all values from the session-state item collection. + /// + /// + public void Clear() { - // Shoot, we need to grab it via reflection. - environment = ReflectionHelper.GetStaticFieldValue("_theHostingEnvironment", typeof(HostingEnvironment)); + this.BaseClear(); } - - return environment; - } - - protected static string NormalizeSlashes(string s) - { - if (string.IsNullOrEmpty(s) || s == "/") - { - return "/"; - } - - s = s.Replace(@"\", "/"); - - // Reduce multiple slashes in row to single. - var normalized = Regex.Replace(s, "(/)/+", "$1"); - - // Strip left. - normalized = StripPrecedingSlashes(normalized); - - // Strip right. - normalized = StripTrailingSlashes(normalized); - 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"); - } + /// + /// Clears all values from the session-state item collection. + /// + /// + public void RemoveAll() + { + this.BaseClear(); + } - protected static string StripTrailingSlashes(string s) - { - return Regex.Replace(s, "(.*)/*$", "$1", RegexOptions.RightToLeft); + /// + /// Copies the collection of session-state item values to a one-dimensional array, starting at the specified index in the array. + /// + /// + /// The that receives the session values. + /// The index in array where copying starts. + public void CopyTo(Array array, int index) + { + throw new NotImplementedException(); + } } - protected static string StripTrailingBackSlashes(string s) - { - return string.IsNullOrEmpty(s) ? string.Empty : Regex.Replace(s, @"(.*)\\*$", "$1", RegexOptions.RightToLeft); - } - internal class ConfigMapPath : IConfigMapPath { private readonly HttpSimulator _requestSimulation; - + public ConfigMapPath(HttpSimulator simulation) { this._requestSimulation = simulation; diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs index b6e25611a57..da64e927536 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/HttpSimulatorTests.cs @@ -53,31 +53,6 @@ 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() @@ -87,7 +62,7 @@ public void CanDispose() simulator.SimulateRequest(); Assert.IsNotNull(HttpContext.Current); } - + Assert.IsNull(HttpContext.Current); } @@ -133,17 +108,17 @@ public void CanGetQueryString() { var simulator = new HttpSimulator(); simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?param1=value1¶m2=value2¶m3=value3")); - for (var i = 1; i <= 3; i++) - { - Assert.AreEqual("value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); - } - + for (var i = 1; i <= 3; i++) + { + Assert.AreEqual("value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); + } + simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?param1=new-value1¶m2=new-value2¶m3=new-value3¶m4=new-value4")); - for (var i = 1; i <= 4; i++) - { - Assert.AreEqual("new-value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); - } - + for (var i = 1; i <= 4; i++) + { + Assert.AreEqual("new-value" + i, HttpContext.Current.Request.QueryString["param" + i], "Could not find query string field 'param{0}'", i); + } + simulator.SimulateRequest(new Uri("http://localhost/Test.aspx?")); Assert.AreEqual(string.Empty, HttpContext.Current.Request.QueryString.ToString()); Assert.AreEqual(0, HttpContext.Current.Request.QueryString.Count); @@ -156,9 +131,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 +154,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 +164,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(); @@ -277,7 +252,7 @@ public void CanMapPath(string virtualPath, string appPath, string expectedMapPat var o = ReflectionHelper.GetPrivateInstanceFieldValue("_configMapPath", environment); Console.WriteLine("_configMapPath: {0}", o ?? "{null}"); - + var mappedPath = ReflectionHelper.InvokeNonPublicMethod(environment, "MapPathActual", vpath, false); Console.WriteLine("MAPPED: " + mappedPath); Assert.AreEqual(expectedMapPath, HttpContext.Current.Request.MapPath(virtualPath)); @@ -321,6 +296,31 @@ public void CanStripTrailing() { Assert.AreEqual(@"c:\blah\blah2", HttpSimulatorTester.CallStripTrailingBackSlashes(@"c:\blah\blah2\")); } + + 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); + } + } } internal class HttpSimulatorTester : HttpSimulator diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs index fdbe2e5fd0c..4afe693f4b3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/ReflectionHelper.cs @@ -16,7 +16,7 @@ public static class ReflectionHelper /// Returns the value of the private member specified. /// /// Name of the member. - /// Type of the member. + /// Type of the member. /// public static T GetStaticFieldValue(string fieldName, Type type) { @@ -25,7 +25,7 @@ public static T GetStaticFieldValue(string fieldName, Type type) { return (T)field.GetValue(type); } - + return default(T); } @@ -33,7 +33,7 @@ public static T GetStaticFieldValue(string fieldName, Type type) /// Returns the value of the private member specified. /// /// Name of the member. - /// + /// /// public static T GetStaticFieldValue(string fieldName, string typeName) { @@ -43,7 +43,7 @@ public static T GetStaticFieldValue(string fieldName, string typeName) { return (T)field.GetValue(type); } - + return default(T); } @@ -56,11 +56,11 @@ public static T GetStaticFieldValue(string fieldName, string typeName) public static void SetStaticFieldValue(string fieldName, Type type, T value) { var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); - if (field == null) - { - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); - } - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); + } + field.SetValue(null, value); } @@ -74,11 +74,11 @@ public static void SetStaticFieldValue(string fieldName, string typeName, T v { var type = Type.GetType(typeName, true); var field = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static); - if (field == null) - { - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); - } - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", fieldName)); + } + field.SetValue(null, value); } @@ -86,7 +86,7 @@ public static void SetStaticFieldValue(string fieldName, string typeName, T v /// Returns the value of the private member specified. /// /// Name of the member. - /// The object that contains the member. + /// The object that contains the member. /// public static T GetPrivateInstanceFieldValue(string fieldName, object source) { @@ -95,7 +95,7 @@ public static T GetPrivateInstanceFieldValue(string fieldName, object source) { return (T)field.GetValue(source); } - + return default(T); } @@ -108,11 +108,11 @@ public static T GetPrivateInstanceFieldValue(string fieldName, object source) public static void SetPrivateInstanceFieldValue(string memberName, object source, object value) { var field = source.GetType().GetField(memberName, BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance); - if (field == null) - { - throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", memberName)); - } - + if (field == null) + { + throw new ArgumentException(string.Format("Could not find the private instance field '{0}'", memberName)); + } + field.SetValue(source, value); } @@ -145,11 +145,11 @@ public static TReturn InvokeNonPublicMethod(Type type, string methodNam var paramTypes = Array.ConvertAll(parameters, o => o.GetType()); var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static, null, paramTypes, null); - if (method == null) - { - throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); - } - + if (method == null) + { + throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); + } + return (TReturn)method.Invoke(null, parameters); } @@ -158,44 +158,44 @@ public static TReturn InvokeNonPublicMethod(object source, string metho var paramTypes = Array.ConvertAll(parameters, o => o.GetType()); var method = source.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, paramTypes, null); - if (method == null) - { - throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); - } - + if (method == null) + { + throw new ArgumentException(string.Format("Could not find a method with the name '{0}'", methodName), "methodName"); + } + return (TReturn)method.Invoke(source, parameters); } public static TReturn InvokeProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName); - if (propertyInfo == null) - { - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - } - + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + return (TReturn)propertyInfo.GetValue(source, null); } public static TReturn InvokeNonPublicProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance, null, typeof(TReturn), new Type[0], null); - if (propertyInfo == null) - { - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - } - + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + return (TReturn)propertyInfo.GetValue(source, null); } public static object InvokeNonPublicProperty(object source, string propertyName) { var propertyInfo = source.GetType().GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance); - if (propertyInfo == null) - { - throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); - } - + if (propertyInfo == null) + { + throw new ArgumentException(string.Format("Could not find a propertyName with the name '{0}'", propertyName), "propertyName"); + } + return propertyInfo.GetValue(source, null); } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs index 106cba4bfc6..066b096b1f4 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/HttpSimulator/SimulatedHttpRequest.cs @@ -16,13 +16,13 @@ namespace DotNetNuke.Tests.Instance.Utilities.HttpSimulator /// public class SimulatedHttpRequest : SimpleWorkerRequest { - private Uri _referer; private readonly string _host; private readonly string _verb; private readonly int _port; - private readonly string _physicalFilePath; - - /// + private readonly string _physicalFilePath; + private Uri _referer; + + /// /// Initializes a new instance of the class. /// Creates a new instance. /// @@ -35,26 +35,26 @@ public class SimulatedHttpRequest : SimpleWorkerRequest /// Host. /// Port to request. /// The HTTP Verb to use. - public SimulatedHttpRequest(string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) + public SimulatedHttpRequest(string applicationPath, string physicalAppPath, string physicalFilePath, string page, string query, TextWriter output, string host, int port, string verb) : base(applicationPath, physicalAppPath, page, query, output) { this.Form = new NameValueCollection(); this.Headers = new NameValueCollection(); - if (host == null) - { - throw new ArgumentNullException("host", "Host cannot be null."); - } - - if (host.Length == 0) - { - throw new ArgumentException("Host cannot be empty.", "host"); - } - - if (applicationPath == null) - { - throw new ArgumentNullException("applicationPath", "Can't create a request with a null application path. Try empty string."); - } - + if (host == null) + { + throw new ArgumentNullException("host", "Host cannot be null."); + } + + if (host.Length == 0) + { + throw new ArgumentException("Host cannot be empty.", "host"); + } + + if (applicationPath == null) + { + throw new ArgumentNullException("applicationPath", "Can't create a request with a null application path. Try empty string."); + } + this._host = host; this._verb = verb; this._port = port; @@ -99,11 +99,6 @@ public override string GetServerName() return this._host; } - internal void SetReferer(Uri referer) - { - this._referer = referer; - } - public override int GetLocalPort() { return this._port; @@ -124,7 +119,7 @@ public override string[][] GetUnknownRequestHeaders() { return null; } - + var headersArray = new string[this.Headers.Count][]; for (var i = 0; i < this.Headers.Count; i++) { @@ -132,22 +127,22 @@ public override string[][] GetUnknownRequestHeaders() headersArray[i][0] = this.Headers.Keys[i]; headersArray[i][1] = this.Headers[i]; } - + return headersArray; } public override string GetKnownRequestHeader(int index) { - if (index == 0x24) - { - return this._referer == null ? string.Empty : this._referer.ToString(); - } - - if (index == 12 && this._verb == "POST") - { - return "application/x-www-form-urlencoded"; - } - + if (index == 0x24) + { + return this._referer == null ? string.Empty : this._referer.ToString(); + } + + if (index == 12 && this._verb == "POST") + { + return "application/x-www-form-urlencoded"; + } + return base.GetKnownRequestHeader(index); } @@ -177,5 +172,10 @@ public override bool IsEntireEntityBodyIsPreloaded() { return true; } + + internal void SetReferer(Uri referer) + { + this._referer = referer; + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs index 1af19ebfbb6..2adcc933c46 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/MailAssert.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Tests.Utilities using NUnit.Framework; public static class MailAssert - { + { public static void Base64EncodedContentLineContains(string expectedValue, string toAddress, string findByText) { var contentLine = ConvertEmailContentFromBase64ToUnicode(GetEmailFileName(toAddress, findByText)); @@ -26,7 +26,40 @@ public static void ContentLineContains(string expectedValue, string toAddress, s Assert.IsFalse(string.IsNullOrEmpty(contentLine)); } - + + public static void FromLineContains(string expectedValue, string toAddress, string findByText) + { + string fromLine = FindEmailLineUsingRegex("From", GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(fromLine.Contains(expectedValue)); + } + + public static void MessageSent(string expectedValue, string toAddress, string message) + { + GetEmailFileName(toAddress, expectedValue); + } + + public static void ReplyToLineContains(string expectedValue, string toAddress, string findByText) + { + string replyToLine = FindEmailLineUsingRegex("Reply-To", GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(replyToLine.Contains(expectedValue)); + } + + public static void SubjectLineContains(string expectedValue, string toAddress, string findByText) + { + string subjectLine = FindEmailLineUsingRegex("Subject", GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(subjectLine.Contains(expectedValue)); + } + + public static void ToLineContains(string expectedValue, string toAddress, string findByText) + { + string toLine = FindEmailLineUsingRegex("To", GetEmailFileName(toAddress, findByText)); + + Assert.IsTrue(toLine.Contains(expectedValue)); + } + private static string ConvertEmailContentFromBase64ToUnicode(string emailFileName) { string emailContent = File.ReadAllText(emailFileName); @@ -95,43 +128,10 @@ private static string GetEmailFileName(string toAddress, string findByText, stri break; } } - + Assert.IsTrue(emailFileName != null, message + " The test was searching in: " + emailPath); return emailFileName; - } - - public static void FromLineContains(string expectedValue, string toAddress, string findByText) - { - string fromLine = FindEmailLineUsingRegex("From", GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(fromLine.Contains(expectedValue)); - } - - public static void MessageSent(string expectedValue, string toAddress, string message) - { - GetEmailFileName(toAddress, expectedValue); - } - - public static void ReplyToLineContains(string expectedValue, string toAddress, string findByText) - { - string replyToLine = FindEmailLineUsingRegex("Reply-To", GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(replyToLine.Contains(expectedValue)); } - - public static void SubjectLineContains(string expectedValue, string toAddress, string findByText) - { - string subjectLine = FindEmailLineUsingRegex("Subject", GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(subjectLine.Contains(expectedValue)); - } - - public static void ToLineContains(string expectedValue, string toAddress, string findByText) - { - string toLine = FindEmailLineUsingRegex("To", GetEmailFileName(toAddress, findByText)); - - Assert.IsTrue(toLine.Contains(expectedValue)); - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs index 0bb20ebb5ce..90372fc9d79 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Mocks/MockComponentProvider.cs @@ -16,8 +16,8 @@ namespace DotNetNuke.Tests.Utilities.Mocks public class MockComponentProvider { - public static Mock CreateNew() - where T : class + public static Mock CreateNew() + where T : class { if (ComponentFactory.Container == null) { @@ -42,8 +42,8 @@ public static Mock CreateNew() return mockComp; } - public static Mock CreateNew(string name) - where T : class + public static Mock CreateNew(string name) + where T : class { if (ComponentFactory.Container == null) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs index 9409ab16bdc..630e2b69309 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/SimulatedHttpRequest.cs @@ -13,9 +13,9 @@ namespace DotNetNuke.Tests.Instance.Utilities /// public class SimulatedHttpRequest : SimpleWorkerRequest { - private readonly string _host; - - /// + private readonly string _host; + + /// /// Initializes a new instance of the class. /// Creates a new instance. /// @@ -25,14 +25,14 @@ public class SimulatedHttpRequest : SimpleWorkerRequest /// Query. /// Output. /// Host. - public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host) + public SimulatedHttpRequest(string appVirtualDir, string appPhysicalDir, string page, string query, TextWriter output, string host) : base(appVirtualDir, appPhysicalDir, page, query, output) { - if (string.IsNullOrEmpty(host)) - { - throw new ArgumentNullException("host", "Host cannot be null nor empty."); - } - + if (string.IsNullOrEmpty(host)) + { + throw new ArgumentNullException("host", "Host cannot be null nor empty."); + } + this._host = host; } @@ -55,11 +55,11 @@ public override string MapPath(string virtualPath) var path = string.Empty; var appPath = this.GetAppPath(); - if (appPath != null) - { - path = Path.Combine(appPath, virtualPath); - } - + if (appPath != null) + { + path = Path.Combine(appPath, virtualPath); + } + return path; } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs index 776d67d1a0c..9ce22c26ed3 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Utilities/Util.cs @@ -18,7 +18,7 @@ public static List CreateIntegerList(int count) { list.Add(i); } - + return list; } @@ -83,7 +83,7 @@ public static Stream GetFileStream(string testFilesFolder, string fileName) { stream = new FileStream(GetFileName(testFilesFolder, fileName), FileMode.Open, FileAccess.Read); } - + return stream; } @@ -98,7 +98,7 @@ public static string ReadStream(string testFilesFolder, string fileName) text = reader.ReadToEnd(); } } - + return text; } @@ -124,7 +124,7 @@ public static void ReadStream(string testFilesFolder, string fileName, Action - { - 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() { @@ -223,5 +200,28 @@ public void RegisteredUser_IsDenied_If_IncludedIn_StaticRoles() // Assert 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; + } } } 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 f0cc2ae5171..eee6d94a2ee 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/DnnWebViewPageTests.cs @@ -23,9 +23,9 @@ 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; 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 3d35584e2a1..38b77160d60 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Framework/ModuleDelegatingViewEngineTests.cs @@ -36,10 +36,10 @@ public void Should_Forward_FindPartialView_To_Current_ModuleApplication_ViewEngi var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); - + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; - + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindPartialView(context, viewName)) .Returns(result); @@ -67,11 +67,11 @@ public void Should_Forward_FindView_To_Current_ModuleApplication_ViewEngineColle var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); - + // ReSharper disable ConvertToConstant.Local var viewName = "Foo"; var masterName = "Bar"; - + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindView(context, viewName, masterName)) .Returns(result); @@ -101,11 +101,11 @@ public void Should_Track_ViewEngine_View_Pairs_On_FindView_And_Releases_View_App var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); - + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; string masterName = "Bar"; - + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindView(context, viewName, masterName)) .Returns(result); @@ -133,10 +133,10 @@ public void Should_Track_ViewEngine_View_Pairs_On_FindPartialView_And_Releases_V var controller = new Mock(); controller.SetupAllProperties(); var context = MockHelper.CreateMockControllerContext(controller.Object); - + // ReSharper disable ConvertToConstant.Local string viewName = "Foo"; - + // ReSharper restore ConvertToConstant.Local mockEngines.Setup(e => e.FindPartialView(context, viewName)) .Returns(result); @@ -197,9 +197,9 @@ 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 44ad62612f0..af71811a030 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,11 +246,11 @@ 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 de56ea753e5..423a79f08b9 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,15 +90,15 @@ 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()); - + // Arrange viewResultMock.Verify(v => v.ExecuteResult(It.IsAny(), It.IsAny())); } @@ -114,15 +114,15 @@ 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()); - + // Arrange viewResultMock.Verify(v => v.ExecuteResult(controllerContext, It.IsAny())); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs index d74836eee2a..830e70e18cb 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/Helpers/DnnUrlHelperTests.cs @@ -268,7 +268,7 @@ public void GenerateUrl_Method_Passes_Correct_RouteValueCollection_To_ModuleRout // Arrange var expectedContext = new ModuleInstanceContext(); var helper = ArrangeHelper(expectedContext); - + RouteValueDictionary routeValues = null; var mockRouteProvider = new Mock(); mockRouteProvider.Setup(p => p.GenerateUrl(It.IsAny(), expectedContext)) @@ -306,11 +306,11 @@ private static DnnUrlHelper ArrangeHelper(ModuleInstanceContext expectedContext, { var viewContext = new ViewContext { Controller = mockController.Object }; - if (!string.IsNullOrEmpty(url)) - { - viewContext.RequestContext = new RequestContext(MockHelper.CreateMockHttpContext(url), routeData); - } - + if (!string.IsNullOrEmpty(url)) + { + viewContext.RequestContext = new RequestContext(MockHelper.CreateMockHttpContext(url), routeData); + } + return new DnnUrlHelper(viewContext); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs index 51389f7565a..a4daaeefd8e 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/MockHelper.cs @@ -97,11 +97,11 @@ public static ViewContext CreateViewContext(string url) routeData.Values["controller"] = "Controller"; routeData.Values["action"] = "Action"; routeData.Values["id"] = "Id"; - var controllerContext = new ControllerContext( + var controllerContext = new ControllerContext( CreateMockHttpContext(url), routeData, new Mock().Object); - return new ViewContext( + return new ViewContext( controllerContext, new Mock().Object, new ViewDataDictionary(), diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs index 6c3f39a54ef..d998b903389 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web.Mvc/ResultAssert.cs @@ -36,9 +36,9 @@ public static void IsView(ActionResult result, string viewName, string masterNam DictionaryAssert.ContainsEntries(expectedViewData, viewResult.ViewData); } - - private static TCast AssertCast(this ActionResult result) - where TCast : class + + private static TCast AssertCast(this ActionResult result) + where TCast : class { var castResult = result as TCast; Assert.IsNotNull(castResult); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs index 74bf3ab3cda..4cfdc08cbb8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/BasicAuthMessageHandlerTests.cs @@ -34,7 +34,7 @@ public void SetsWwwAuthenticateHeaderOn401() public void OmitsWwwAuthenticateHeaderOn401FromXmlHttpRequest() { // Arrange - var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) + var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = new HttpRequestMessage() }; response.RequestMessage.Headers.Add("X-REQUESTED-WITH", "XmlHttpRequest"); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs index 5272f04399c..04138f4b99f 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/DnnApiControllerTests.cs @@ -63,31 +63,30 @@ public void GetsPortalSettingsViaTestablePortalController() // 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); - // } + } + + 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 9c96ab95922..3595a969ec2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/Internals/DnnDependencyResolverTests.cs @@ -19,9 +19,8 @@ public class DnnDependencyResolverTests private IServiceProvider _serviceProvider; private IDependencyResolver _dependencyResolver; - private interface ITestService - { - } + private interface ITestService + {} [TestFixtureSetUp] public void FixtureSetUp() @@ -39,11 +38,11 @@ public void FixtureTearDown() { this._dependencyResolver = null; - if (this._serviceProvider is IDisposable disposable) - { - disposable.Dispose(); - } - + if (this._serviceProvider is IDisposable disposable) + { + disposable.Dispose(); + } + this._serviceProvider = null; } @@ -113,10 +112,9 @@ public void BeginScope_GetServices() Assert.AreEqual(1, actual.Length); Assert.AreEqual(expected.GetType(), actual[0].GetType()); } - - private class TestService : ITestService - { - } + + private class TestService : ITestService + {} private class FakeScopeAccessor : IScopeAccessor { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs index c61b8e80007..929025c8431 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/JwtAuthMessageHandlerTests.cs @@ -28,11 +28,11 @@ 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; @@ -72,10 +72,10 @@ public void SetupMockServices() UserController.SetTestableInstance(this._mockUserController.Object); this._mockUserController.Setup(x => x.GetUserById(It.IsAny(), It.IsAny())).Returns( (int portalId, int userId) => GetUserByIdCallback(portalId, userId)); - + // _mockUserController.Setup(x => x.ValidateUser(It.IsAny(), It.IsAny(), It.IsAny())).Returns(UserValidStatus.VALID); } - + [Test] public void ReturnsResponseAsReceived() { @@ -104,6 +104,84 @@ public void MissingAuthoizationHeaderReturnsNullResponse() Assert.IsNull(response); } + [Test] + public void WrongAuthoizationSchemeReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + request.Headers.Authorization = AuthenticationHeaderValue.Parse("Basic "); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } + + [Test] + public void MissingAuthoizationTokenReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer "); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } + + [Test] + public void AuthoizationTokenWithMissingComponentsReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + request.Headers.Authorization = AuthenticationHeaderValue.Parse( + "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0"); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } + + [Test] + public void AuthoizationTokenWithWrongSchemeTypeReturnsNullResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + request.Headers.Authorization = AuthenticationHeaderValue.Parse( + "Bearer eyJ0eXBlIjoieHh4IiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"); + + // Act + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } + + [Test] + public void AuthoizationTokenWithoorResponse() + { + // Arrange + var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); + request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer " + ValidToken); + + // Act + this.SetupMockServices(); + var handler = new JwtAuthMessageHandler(true, false); + var response = handler.OnInboundRequest(request, CancellationToken.None); + + // Assert + Assert.IsNull(response); + } + private static IDataReader GetUser() { var table = new DataTable("Users"); @@ -175,28 +253,10 @@ 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)) - { + if ("0123456789ABCDEF".Equals(sessionId)) + { return new PersistedToken { TokenId = sessionId, @@ -205,9 +265,9 @@ private static PersistedToken GetPersistedToken(string sessionId) UserId = 1, TokenHash = GetHashedStr(ValidToken), RenewalHash = "renewal-hash", - }; - } - + }; + } + return null; } @@ -227,97 +287,19 @@ private static UserInfo GetUserByIdCallback(int portalId, int userId) } return null; - } - - [Test] - public void WrongAuthoizationSchemeReturnsNullResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - request.Headers.Authorization = AuthenticationHeaderValue.Parse("Basic "); - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); } - [Test] - public void MissingAuthoizationTokenReturnsNullResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer "); - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); - } - - [Test] - public void AuthoizationTokenWithMissingComponentsReturnsNullResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - request.Headers.Authorization = AuthenticationHeaderValue.Parse( - "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0"); - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); - } - - [Test] - public void AuthoizationTokenWithWrongSchemeTypeReturnsNullResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - request.Headers.Authorization = AuthenticationHeaderValue.Parse( - "Bearer eyJ0eXBlIjoieHh4IiwiYWxnIjoiSFMyNTYifQ.eyJzdWIiOiJ1c2VybmFtZSIsIm5iZiI6MSwiZXhwIjo0MTAyNDQ0Nzk5LCJzaWQiOiIwMTIzNDU2Nzg5QUJDREVGIn0.nfWCOVNk5M7L7EPDe3i3j4aAPRerbxgmcjOxaC-LWUQ"); - - // Act - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); - } - - [Test] - public void AuthoizationTokenWithoorResponse() - { - // Arrange - var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/anyuri"); - request.Headers.Authorization = AuthenticationHeaderValue.Parse("Bearer " + ValidToken); - - // Act - this.SetupMockServices(); - var handler = new JwtAuthMessageHandler(true, false); - var response = handler.OnInboundRequest(request, CancellationToken.None); - - // Assert - Assert.IsNull(response); - } - - // todo unit test actual authentication code - // very hard to unit test inbound authentication code as it dips into untestable bits of - // UserController, etc. Need to write controllers with interfaces and ServiceLocator<>. - - // private static string DecodeBase64(string b64Str) - // { - // // fix Base64 string padding - // var mod = b64Str.Length % 4; - // if (mod != 0) b64Str += new string('=', 4 - mod); - // return Encoding.UTF8.GetString(Convert.FromBase64String(b64Str)); - // } + // todo unit test actual authentication code + // very hard to unit test inbound authentication code as it dips into untestable bits of + // UserController, etc. Need to write controllers with interfaces and ServiceLocator<>. + + // private static string DecodeBase64(string b64Str) + // { + // // fix Base64 string padding + // var mod = b64Str.Length % 4; + // if (mod != 0) b64Str += new string('=', 4 - mod); + // return Encoding.UTF8.GetString(Convert.FromBase64String(b64Str)); + // } private static string EncodeBase64(byte[] data) { return Convert.ToBase64String(data).TrimEnd('='); @@ -329,6 +311,24 @@ private static string GetHashedStr(string data) { return EncodeBase64(hasher.ComputeHash(Encoding.UTF8.GetBytes(data))); } - } + } + + 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(); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs index 2498ae861f2..064c87384f2 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/PortalAliasRouteManagerTests.cs @@ -36,7 +36,7 @@ public void TearDown() PortalAliasController.ClearInstance(); TestableGlobals.ClearInstance(); } - + [Test] [TestCase("mfn", "url", 0, "API/mfn/url")] [TestCase("mfn", "url", 1, "{prefix0}/API/mfn/url")] @@ -45,7 +45,7 @@ public void TearDown() public void GetRouteUrl(string moduleFolderName, string url, int count, string expected) { // Arrange - + // Act string result = new PortalAliasRouteManager().GetRouteUrl(moduleFolderName, url, count); @@ -59,7 +59,7 @@ public void GetRouteUrl(string moduleFolderName, string url, int count, string e public void GetRouteUrlThrowsOnBadArguments(string moduleFolderName, int count, Type expectedException, string message) { // Arrange - + // Act try { @@ -89,8 +89,8 @@ public void ParentPortalOnVirtualDirReturnsAnEmptyPrefix() var mockPortalAliasController = new Mock(); mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] - { - new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" } + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me/vdir" } }); PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); @@ -116,8 +116,8 @@ public void SingleParentPortalReturnsAnEmptyPrefix() var mockPortalAliasController = new Mock(); mockPortalAliasController.Setup(x => x.GetPortalAliasesByPortalId(It.IsAny())).Returns(new[] - { - new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } + { + new PortalAliasInfo { HTTPAlias = "valid.lvh.me" } }); PortalAliasController.SetTestableInstance(mockPortalAliasController.Object); @@ -220,7 +220,7 @@ public void VirtralDirWithChildPortalHasABlankAndASinglePrefix() public void GetRouteNameHashesNameInCorrectFormat(string moduleFolderName, string routeName, int count, string expected) { // Arrange - + // Act var result = new PortalAliasRouteManager().GetRouteName(moduleFolderName, routeName, count); @@ -235,7 +235,7 @@ public void GetRouteNameHashesNameInCorrectFormat(string moduleFolderName, strin public void GetRouteNameWithPortalAliasInfoHashesNameInCorrectFormat(string moduleFolderName, string routeName, string httpAlias, string expected) { // Arrange - + // Act var result = new PortalAliasRouteManager().GetRouteName(moduleFolderName, routeName, new PortalAliasInfo { HTTPAlias = httpAlias }); @@ -250,7 +250,7 @@ public void GetRouteNameWithPortalAliasInfoHashesNameInCorrectFormat(string modu public void GetRouteNameThrowsOnEmptyModuleFolderName(string moduleFolderName) { // Arrange - + // Act new PortalAliasRouteManager().GetRouteName(moduleFolderName, string.Empty, 0); @@ -262,7 +262,7 @@ public void GetRouteNameThrowsOnEmptyModuleFolderName(string moduleFolderName) public void GetRouteNameThrowsOnCountLessThan0() { // Arrange - + // Act new PortalAliasRouteManager().GetRouteName("foo", string.Empty, -1); @@ -273,7 +273,7 @@ public void GetRouteNameThrowsOnCountLessThan0() public void GetAllRouteValuesWorksWithNullRouteValues() { // Arrange - + // Act new PortalAliasRouteManager().GetAllRouteValues(new PortalAliasInfo { HTTPAlias = string.Empty }, null); @@ -285,9 +285,9 @@ public void GetAllRouteValuesWorksWithNullRouteValues() public void GetAllRouteValuesPreservesPassedInRouteValues() { // Arrange - + // Act - var result = new PortalAliasRouteManager().GetAllRouteValues( + var result = new PortalAliasRouteManager().GetAllRouteValues( new PortalAliasInfo { HTTPAlias = string.Empty }, new { value1 = 1, value2 = 2 }); @@ -300,10 +300,10 @@ public void GetAllRouteValuesPreservesPassedInRouteValues() public void GetAllRouteValuesExtractsChildPortalParams() { // Arrange - + // Act var result = - new PortalAliasRouteManager().GetAllRouteValues( + new PortalAliasRouteManager().GetAllRouteValues( new PortalAliasInfo { HTTPAlias = "ce.lvh.me/child" }, null); @@ -316,10 +316,10 @@ public void GetAllRouteValuesExtractsChildPortalParams() public void GetAllRouteValuesExtractsManyChildPortalParamsAndPreservesRouteValues() { // Arrange - + // Act var result = - new PortalAliasRouteManager().GetAllRouteValues( + new PortalAliasRouteManager().GetAllRouteValues( new PortalAliasInfo { HTTPAlias = "ce.lvh.me/child0/child1/child2/child3" }, new { value1 = 1, value2 = 2 }); diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs index b36709b0bc5..4da2b9001a7 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ReflectedServiceRouteMappers.cs @@ -11,14 +11,14 @@ namespace DotNetNuke.Tests.Web.Api // various ServiceRouteMappers that will be reflected upon by the tests public class ReflectedServiceRouteMappers - { + { public class EmbeddedServiceRouteMapper : IServiceRouteMapper - { + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } - } + } + } } public class ExceptionOnCreateInstanceServiceRouteMapper : IServiceRouteMapper @@ -27,45 +27,45 @@ public ExceptionOnCreateInstanceServiceRouteMapper(int i) { // no default constructor prevents Activator.CreateInstance from working Debug.WriteLine(i); - } - + } + public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } + } } public class ExceptionOnRegisterServiceRouteMapper : IServiceRouteMapper - { + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } + } } public class FakeServiceRouteMapper : IServiceRouteMapper { - public static int RegistrationCalls { get; set; } - + public static int RegistrationCalls { get; set; } + public void RegisterRoutes(IMapRoute mapRouteManager) { RegistrationCalls++; - } + } } public abstract class AbstractServiceRouteMapper : IServiceRouteMapper - { + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } + } } internal class InternalServiceRouteMapper : IServiceRouteMapper - { + { public void RegisterRoutes(IMapRoute mapRouteManager) { throw new NotImplementedException(); - } + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs index 0c4c27776b2..2a5d8921ba8 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ServiceRoutingManagerTests.cs @@ -28,7 +28,7 @@ public class ServiceRoutingManagerTests // ReSharper disable UnusedMember.Local private readonly List _emptyStringArrays = new List { null, new string[0], new[] { string.Empty }, new string[] { null } }; - + // ReSharper restore UnusedMember.Local private Mock _mockPortalController; private IPortalController _portalController; @@ -53,11 +53,11 @@ public void TearDown() { PortalController.ClearInstance(); - if (Globals.DependencyProvider is IDisposable disposable) - { - disposable.Dispose(); - } - + if (Globals.DependencyProvider is IDisposable disposable) + { + disposable.Dispose(); + } + Globals.DependencyProvider = null; } @@ -87,7 +87,7 @@ public void LocatesAllServiceRouteMappers() typeof(ExceptionOnRegisterServiceRouteMapper), }, types); } - + [Test] public void NameSpaceRequiredOnMapRouteCalls([ValueSource("_emptyStringArrays")] string[] namespaces) { diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs index 90df3a9b156..fe1df42901a 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/StandardTabAndModuleInfoProviderTests.cs @@ -24,7 +24,12 @@ public class StandardTabAndModuleInfoProviderTests { private const int ValidPortalId = 0; private const int ValidTabModuleId = 999; - + private const int ValidModuleId = 456; + private const int ValidTabId = 46; + + private const string MonikerSettingName = "Moniker"; + private const string MonikerSettingValue = "TestMoniker"; + private Mock _mockModuleController; private IModuleController _moduleController; private Mock _mockTabController; @@ -35,11 +40,6 @@ public class StandardTabAndModuleInfoProviderTests private ITabModulesController _tabModuleController; private TabInfo _tabInfo; private ModuleInfo _moduleInfo; - private const int ValidModuleId = 456; - private const int ValidTabId = 46; - - private const string MonikerSettingName = "Moniker"; - private const string MonikerSettingValue = "TestMoniker"; [SetUp] public void Setup() @@ -56,9 +56,9 @@ public void Setup() this._tabInfo = new TabInfo { TabID = ValidTabId }; this._moduleInfo = new ModuleInfo { - TabModuleID = ValidTabModuleId, - TabID = ValidTabId, - ModuleID = ValidModuleId, + TabModuleID = ValidTabModuleId, + TabID = ValidTabId, + ModuleID = ValidModuleId, PortalID = ValidPortalId, }; @@ -111,53 +111,6 @@ public void ExistingMonikerValueInHeaderShouldFindTheCorrectModuleInfo() Assert.AreSame(this._moduleInfo, returnedModuleInfo); } - private static IDataReader GetPortalsCallBack(string culture) - { - return GetPortalCallBack(0, culture); - } - - private static IDataReader GetPortalCallBack(int portalId, string culture) - { - var table = new DataTable("Portal"); - - var cols = new[] - { - "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", - "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", - "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", - "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", - "ProcessorUserId", - "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", - "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", - "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", - "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", - "CultureCode", - }; - - foreach (var col in cols) - { - table.Columns.Add(col); - } - - const int homePage = 1; - table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright (c) 2018 DNN Corp.", null, - "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", - "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", - null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, - homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", - "-1", "2011-08-25 07:34:29", culture); - - return table.CreateDataReader(); - } - - private void RegisterMock(Action register, out Mock mock, out T instance) - where T : class - { - mock = new Mock(); - instance = mock.Object; - register(instance); - } - [Test] public void ExistingMonikerValueInQueryStringShouldFindTheCorrectModuleInfo() { @@ -403,5 +356,52 @@ public void NoModuleIdInRequestReturnsNoModuleId() Assert.IsFalse(result); Assert.AreEqual(-1, moduleId); } + + private static IDataReader GetPortalsCallBack(string culture) + { + return GetPortalCallBack(0, culture); + } + + private static IDataReader GetPortalCallBack(int portalId, string culture) + { + var table = new DataTable("Portal"); + + var cols = new[] + { + "PortalID", "PortalGroupID", "PortalName", "LogoFile", "FooterText", "ExpiryDate", + "UserRegistration", "BannerAdvertising", "AdministratorId", "Currency", "HostFee", + "HostSpace", "PageQuota", "UserQuota", "AdministratorRoleId", "RegisteredRoleId", + "Description", "KeyWords", "BackgroundFile", "GUID", "PaymentProcessor", + "ProcessorUserId", + "ProcessorPassword", "SiteLogHistory", "Email", "DefaultLanguage", "TimezoneOffset", + "AdminTabId", "HomeDirectory", "SplashTabId", "HomeTabId", "LoginTabId", "RegisterTabId", + "UserTabId", "SearchTabId", "Custom404TabId", "Custom500TabId", "TermsTabId", "PrivacyTabId", "SuperTabId", + "CreatedByUserID", "CreatedOnDate", "LastModifiedByUserID", "LastModifiedOnDate", + "CultureCode", + }; + + foreach (var col in cols) + { + table.Columns.Add(col); + } + + const int homePage = 1; + table.Rows.Add(portalId, null, "My Website", "Logo.png", "Copyright (c) 2018 DNN Corp.", null, + "2", "0", "2", "USD", "0", "0", "0", "0", "0", "1", "My Website", + "DotNetNuke, DNN, Content, Management, CMS", null, "1057AC7A-3C08-4849-A3A6-3D2AB4662020", + null, null, null, "0", "admin@changeme.invalid", "en-US", "-8", "58", "Portals/0", null, + homePage.ToString(), null, null, "57", "56", "-1", "-1", null, null, "7", "-1", "2011-08-25 07:34:11", + "-1", "2011-08-25 07:34:29", culture); + + return table.CreateDataReader(); + } + + private void RegisterMock(Action register, out Mock mock, out T instance) + where T : class + { + mock = new Mock(); + instance = mock.Object; + register(instance); + } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs index 0b6278f91c6..7b7c05884e0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Api/ValidateAntiForgeryTokenAttributeTests.cs @@ -33,9 +33,9 @@ public void LocateCookies(string cookieFormat) { this.LocatesCookie(cookieFormat, "__RequestVerificationToken_thiscanbemany_characters_in_some_cases", "some text goes here"); } - + [Test] - + // real world data from a request that fails when using the WebAPI .GetCookies method [TestCase("StayInEditMode=NO; ASP.NET_SessionId=yumytgeltkonngafni2h3i55; __RequestVerificationToken_LzYyMA__=dL23/UED9k98Xl4yO6jaXu6Oa29D6dLtjucfyukq7nV2ET6hBznoTS74x0yXuj8TS8qIoXcYa+6FkeE38qKQkR9KUq48oEeikLLdhIOZSkaDYsmgXQ7uKwNFK4k=; Panel-FriendlyUrl=false; dnnSitePanel-LoadFiles=true; dnnSitePanel-SEOSettings=true; dnnSitePanel-GeneralSettings=true; dnnSitePanel-EntryOptions=true; dnnSitePanel-AdvancedSettings=true; __RequestVerificationToken_L05lYnVsYQ__=C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=; SuggestionCustom=false; SuggestionTemplate=false; dnnTabs-dnnEditRole=0; dnnTabs-dnnBlogOptions=0; dnnSitePanel-RSSSettings=false; dnnSitePanel-CommentSettings=false; dnnTabs-dnnRecycleBin=0; dnnTabs-dnnManageUsers=0; Panel-Authentication Systems=false; .DOTNETNUKECTP270=63191FCE95736673FF53435768B2BB9838233821C4653EA0F3940432D05EF501878DE0A353C4B5474D52F5A28638BDDE1FB4269AB674C8283361C56A8CEC70243424414BB3871EB0918B840C6092CBD348A714BDD7D12A6B0441BC3BB96FC1DF963AA7A7; Panel-HostDetails=false; Panel-SMTP=false; .NEBULAX12=4C3B5C2B5C1DA13493A114CDE53CF487907FAF66AAAF04972CBF4E63E779580FE385D0759DDCA946775D0B0300A712052D4169DC93CC0B380D3970238B80E2850077573B22C9D1B8FB119867874667CA350057F392EE89E2205184FE53F3AB949578298E; __RequestVerificationToken_LzYyMw__=RtpaumwI56fNPCA7js90MRMECcEkR78oHrHn82YQOHXy3O3p53dEklX/485E+GMGGN/D/pzhN4UUI3eJs7be/1Tbkv8mwsMO9WAfFulwZazuktqwlmAyuI5BOj4=; dnnSitePanel-SiteDetails=false; dnnSitePanel-Appearance=true; dnnPanel-ViewLog=true; .ASPXANONYMOUS=N2HauUbbzQEkAAAAZWRmODRjODEtODBhOS00NGJhLTlhYTAtZDk5YTcxZTgzYzlm0; dnnSitePanel-Usability=true; dnnPanel-ExtensionPackageSettings=false; dnnSitePanel-Pages=true; dnnPanel-TabsOtherSettings=false; dnnPanel-TabsCacheSettings=false; dnnPanel-TabsAppearance=true; __RequestVerificationToken_L0NUUA2=rXptF4iP2vio-YQMbnxOp66oECpG2DQe6llUiWmiyjJvYjtWcx9XrjymOMwCheiGNogAbrv0RTPDGe2VGxswX0NVX02PZ-U2RwViRYhATUvcymdrc9jV3ygC0_w1; __RequestVerificationToken_LzcwMA2=LDfpU-HI96zNfH6FfLc45T9v8Ltr0OzwYWsaUVs-hGW1gVnLzYoVUm9xcQDkwjjrve_MbAQx6WuNq5Om2C8TEPRk_tXGDe7d3ibvXZVd0iUXYmSjoapYZ6FnjA41; undefined=false; dnn_ctr345_EditExtension_ModuleEditor_moduleSettingsHead=false; Panel-Widgets=false; Panel-Skin Objects=false; Panel-Skins=false; Panel-Providers=false; dnnPanel-LogSendExceptions=false; dnnPanel-ModuleAppearance=false; dnnPanel-ModuleOtherSettings=true; dnnTabs-dnnModuleSettings=3; dnnTabs-dnnHostSettings=0; Panel-Configuration=false; .DOTNETNUKE7PEBETA=197F580A056BEFB9E793BA8629133538298764AD055A68BABD9B93BD80F15A2B8734CD12D6CCA5B2BD8154319B932286A886074B57EAF06FA1E5E8DFA89FBF4192AA0E2F099554E5220DE12A632D5D58AA0272250CE67F93DD33CD3A4A411603252D0CB2; __RequestVerificationToken_LzdQRQ2=IKW7w2KnSu53WEJR0RKvhOcb2f_tyrxeSNuxOGoKmRIyvNFHnj4V_yZsE3J4cJILVeOP15sPmFbukzCpejZL7Ltmlx_XxDFRknrN-xJ4_5cPcppIGFCrl7o0akE1; .DOTNETNUKE=A43776EA5CEDF9E63B890A79E803F54FF72FD3718F9633C80C94C60EA43990EC24A7791B354E21A3CDDDF81F6AE0602A332770B6BA2AF48CED1973061A15F72CF78E8D9A1D33ED882B8E66E3CF9588325709E287FBA83CD11D58A84D03923716EC74B0FF; authentication=DNN; Panel-Libraries=false; dnnTabs-dnnExtensions=0; Panel-Modules=true; 51D=3155378975999999999; __RequestVerificationToken_L09yaW9u0=erx2uolpjtcgKYekq_Blw9bjJTsGB78wa-HREzGMXgpNM6fKGv1MvQ5mHj2KQLfBwyUzkHR3rC6XlTgf4NlcMhm2FyInWqaiPfU9w6lBj5EQeu-Wl3YXLuQrDgM1; .ORIONNEBULA7=1B487CE9A95CC1E925AEA02D9535E3E27F7536663EF7DD451996E3D7ADD474C410352960C16D7B38E19ECF2056927C2DEB23DABE85BB90EF0CC80226D00B6D90C21D45BA77F4D62C0C58FD5303672812C1A58783A50B58D34C245CC56694C176EA8F2541; __RequestVerificationToken_L1ZlaWw1=aAOphH6E9pSOu9yjGvTGhlaXHDL-Z5RQtPcb9-aAYSOJ674286gvW65ui7tm7iBr6COrjRN2UXeI6fQQyiL7Q8ctc59K5YQ5jM2K09l3fnag-3FZ1zz3W6d6iGE1; dnnTabs-dnnSiteSettings=1; dnnTabs-tabSettingsForm=0; .VeilNebula7=7DE1D60FF03633EF8611505BBB7201942C6C236AD8C289B22FE2BE48647D2626D55DF84ACA02094C3D253A1EBBABD48C0A008538E0C3AB4DA96ABC95EFA947DC2D74FF79D9478674D0BA35D3D2EAE94E2B5CDDC43915E11B90B361CEE799F3C421ECE499; language=en-US; LastPageId=0:64; dnnTabs-smMainContent=0", "__RequestVerificationToken_L05lYnVsYQ__", "C7z6azjbbWwBMjonTt/Np7Dm52/xvN3NS0G0mpCUy7cPiMB+1g6rt1ifKlaTDlRO8RsniY2DIAeMjet0nOPNwWJ6sByiWttFsPnbVlAV9qZ0YwFSsYge9dASbrQ=")] public void LocatesCookie(string cookieFormat, string cookieName, string cookieValue) @@ -54,7 +54,7 @@ public void LocatesCookie(string cookieFormat, string cookieName, string cookieV // Act var vaft = new ValidateAntiForgeryTokenAttribute(); - + // Assert.IsTrue(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); Assert.DoesNotThrow(() => { vaft.OnActionExecuting(authFilterContext.ActionContext); }); @@ -79,7 +79,7 @@ public void MissingTokenDoesnotPassValidationTest(string cookieFormat, string co // Act, Assert var vaft = new ValidateAntiForgeryTokenAttribute(); - + // Assert.IsFalse(ValidateAntiForgeryTokenAttribute.IsAuthorized(authFilterContext)); Assert.Throws(() => { vaft.OnActionExecuting(authFilterContext.ActionContext); }); } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs index ac785903539..1db927851a5 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/FakeModuleCrawlerController.cs @@ -13,7 +13,7 @@ namespace DotNetNuke.Tests.Web.InternalServices /// /// public class FakeResultController : BaseResultController - { + { public override bool HasViewPermission(SearchResult searchResult) { return true; @@ -21,9 +21,9 @@ 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"; - } + } } public class NoPermissionFakeResultController : FakeResultController diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs index 79c6e0edc9c..9c7ce458aff 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/SearchServiceControllerTests.cs @@ -40,7 +40,7 @@ namespace DotNetNuke.Tests.Web.InternalServices /// [TestFixture] public class SearchServiceControllerTests - { + { private const int ModuleSearchTypeId = 1; private const int TabSearchTypeId = 2; private const int UserSearchTypeId = 3; @@ -73,8 +73,8 @@ public class SearchServiceControllerTests private const string CultureEnUs = "en-US"; private const string SearchIndexFolder = @"App_Data\SearchTests"; - private const int DefaultSearchRetryTimes = 5; - + private const int DefaultSearchRetryTimes = 5; + private readonly double _readerStaleTimeSpan = TimeSpan.FromMilliseconds(100).TotalSeconds; private Mock _mockCBO; private Mock _mockHostController; @@ -87,8 +87,8 @@ public class SearchServiceControllerTests private Mock _mockTabController; private SearchServiceController _searchServiceController; private IInternalSearchController _internalSearchController; - private LuceneControllerImpl _luceneController; - + private LuceneControllerImpl _luceneController; + [SetUp] public void SetUp() { @@ -134,7 +134,7 @@ public void SetUp() this.CreateNewLuceneControllerInstance(); } - + [TearDown] public void TearDown() { @@ -146,7 +146,7 @@ public void TearDown() UserController.ClearInstance(); PortalController.ClearInstance(); ModuleController.ClearInstance(); - } + } [Test] public void GetSearchResultsDetailed() @@ -236,7 +236,7 @@ public void GetSearchResultsBasic() // 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()); @@ -250,7 +250,79 @@ public void GetSearchResultsBasic() // 2 Tabs results Assert.AreEqual(2, groupedBasicViews.Single(x => x.DocumentTypeName == "tab").Results.Count()); } - + + [Test] + public void ModifyingDocumentsDoesNotCreateDuplicates() + { + // Arrange + const string tabUrl = "mysite/ContentUrl"; + const string title = "content title"; + const string contentBody = "content body"; + const string titleModified = title + " modified"; + var uniqueKey = Guid.NewGuid().ToString(); + var now = DateTime.UtcNow; + + var originalDocument = new SearchDocument + { + UniqueKey = uniqueKey, + TabId = TabId1, + Url = tabUrl, + Title = title, + Body = contentBody, + SearchTypeId = TabSearchTypeId, + ModifiedTimeUtc = now, + PortalId = PortalId0, + RoleId = RoleId731, + Keywords = { { "description", "mycontent" } }, + NumericKeys = { { "points", 5 } }, + }; + + this._internalSearchController.AddSearchDocument(originalDocument); + this._internalSearchController.Commit(); + + var modifiedDocument = new SearchDocument + { + UniqueKey = uniqueKey, + TabId = TabId1, + Url = tabUrl, + Title = titleModified, + Body = contentBody + " modified", + SearchTypeId = TabSearchTypeId, + ModifiedTimeUtc = now, + PortalId = PortalId0, + RoleId = RoleId731, + Keywords = { { "description", "mycontent_modified" }, { "description2", "mycontent_modified" } }, + NumericKeys = { { "points", 8 }, { "point2", 7 } }, + }; + + this._internalSearchController.AddSearchDocument(modifiedDocument); + this._internalSearchController.Commit(); + + var query = new SearchQuery + { + KeyWords = title, + 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 searchResults = this.GetGroupedDetailViewResults(query).ToList(); + + // Assert + Assert.AreEqual(1, searchResults.Count()); + Assert.AreEqual(1, searchResults.First().Results.Count); + Assert.AreEqual(tabUrl, searchResults.First().Results.First().DocumentUrl); + Assert.AreEqual(titleModified, searchResults.First().Results.First().Title); + } + private void CreateNewLuceneControllerInstance() { if (this._luceneController != null) @@ -258,18 +330,18 @@ private void CreateNewLuceneControllerInstance() LuceneController.ClearInstance(); this._luceneController.Dispose(); } - + this._luceneController = new LuceneControllerImpl(); LuceneController.SetTestableInstance(this._luceneController); } - + private void SetupUserController() { this._mockUserController.Setup(c => c.GetUserById(It.IsAny(), It.IsAny())).Returns( new UserInfo { UserID = UserId1, Username = UserName1, Profile = new UserProfile { } }); UserController.SetTestableInstance(this._mockUserController.Object); } - + private void SetupHostController() { this._mockHostController.Setup(c => c.GetString(Constants.SearchIndexFolderKey, It.IsAny())).Returns( @@ -294,7 +366,7 @@ private void SetupHostController() DefaultSearchRetryTimes); HostController.RegisterInstance(this._mockHostController.Object); } - + private void SetupDataProvider() { // Standard DataProvider Path for Logging @@ -310,14 +382,14 @@ private void SetupDataProvider() DataService.RegisterInstance(this._mockDataService.Object); } - + private void SetupPortalSettings() { var mockPortalController = new Mock(); mockPortalController.Setup(x => x.GetPortal(It.IsAny())).Returns(new PortalInfo { PortalID = PortalId0, PortalGroupID = -1, UserTabId = TabId1, }); PortalController.SetTestableInstance(mockPortalController.Object); } - + private void SetupModuleController() { this._mockModuleController.Setup(mc => mc.GetModule(It.Is(m => m == HtmlModuleId1), It.Is(p => p == PortalId0), false)).Returns( @@ -331,22 +403,22 @@ private void SetupModuleController() new ModuleInfo { ModuleID = HtmlModuleId4, ModuleDefID = HtmlModDefId, ModuleTitle = HtmlModuleTitle4 }); ModuleController.SetTestableInstance(this._mockModuleController.Object); } - + private void DeleteIndexFolder() { try { - if (Directory.Exists(SearchIndexFolder)) - { - Directory.Delete(SearchIndexFolder, true); - } + if (Directory.Exists(SearchIndexFolder)) + { + Directory.Delete(SearchIndexFolder, true); + } } catch (Exception ex) { Console.WriteLine(ex); } } - + private IDataReader GetUser() { var table = new DataTable("Users"); @@ -378,7 +450,7 @@ private IDataReader GetUser() -1, DateTime.Now); return table.CreateDataReader(); } - + private IDataReader GetPortalGroups() { var table = new DataTable("ModuleDefinitions"); @@ -396,7 +468,7 @@ private IDataReader GetPortalGroups() table.Rows.Add(0, 0, "test", "descr", "domain", -1, DateTime.Now, -1, DateTime.Now); return table.CreateDataReader(); } - + // return 2 test tabs(TabId 56 - Home, TabId 57 - AboutUs) private IDataReader GetTabs() { @@ -446,10 +518,10 @@ private IDataReader GetTabs() 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(); } - + // return 4 html modules (TabId 56 - Home: ModuleIDs:367, 368, 370 TabId 57 - AboutUs: 378//) private IDataReader GetSearchModules() { @@ -551,7 +623,7 @@ private IDataReader GetSearchModules() "664BAA98-7E24-461F-8180-36527619D042", string.Empty); return table.CreateDataReader(); } - + // returns 2 moduledefinitions - Text/HTML and Journal private IDataReader GetModuleDefinitions() { @@ -572,7 +644,7 @@ private IDataReader GetModuleDefinitions() return table.CreateDataReader(); } - + // returns all search types - 3 SearchTypes - module, tab, user private IDataReader GetAllSearchTypes() { @@ -588,12 +660,12 @@ private IDataReader GetAllSearchTypes() table.Rows.Add(3, "user", FakeResultControllerClass, 0); return table.CreateDataReader(); } - + private IDataReader GetPortalsCallBack(string culture) { return this.GetPortalCallBack(PortalId0, CultureEnUs); } - + private IDataReader GetPortalCallBack(int portalId, string culture) { DataTable table = new DataTable("Portal"); @@ -626,8 +698,8 @@ private IDataReader GetPortalCallBack(int portalId, string culture) "-1", "2011-08-25 07:34:29", culture); return table.CreateDataReader(); - } - + } + private IEnumerable GetGroupBasicViewResults(SearchQuery query) { var userSearchContentSource = new SearchContentSource @@ -649,77 +721,5 @@ private IEnumerable GetGroupedDetailViewResults(SearchQuery s var results = this._searchServiceController.GetGroupedDetailViews(searchQuery, UserSearchTypeId, out totalHits, out more); return results; } - - [Test] - public void ModifyingDocumentsDoesNotCreateDuplicates() - { - // Arrange - const string tabUrl = "mysite/ContentUrl"; - const string title = "content title"; - const string contentBody = "content body"; - const string titleModified = title + " modified"; - var uniqueKey = Guid.NewGuid().ToString(); - var now = DateTime.UtcNow; - - var originalDocument = new SearchDocument - { - UniqueKey = uniqueKey, - TabId = TabId1, - Url = tabUrl, - Title = title, - Body = contentBody, - SearchTypeId = TabSearchTypeId, - ModifiedTimeUtc = now, - PortalId = PortalId0, - RoleId = RoleId731, - Keywords = { { "description", "mycontent" } }, - NumericKeys = { { "points", 5 } }, - }; - - this._internalSearchController.AddSearchDocument(originalDocument); - this._internalSearchController.Commit(); - - var modifiedDocument = new SearchDocument - { - UniqueKey = uniqueKey, - TabId = TabId1, - Url = tabUrl, - Title = titleModified, - Body = contentBody + " modified", - SearchTypeId = TabSearchTypeId, - ModifiedTimeUtc = now, - PortalId = PortalId0, - RoleId = RoleId731, - Keywords = { { "description", "mycontent_modified" }, { "description2", "mycontent_modified" } }, - NumericKeys = { { "points", 8 }, { "point2", 7 } }, - }; - - this._internalSearchController.AddSearchDocument(modifiedDocument); - this._internalSearchController.Commit(); - - var query = new SearchQuery - { - KeyWords = title, - 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 searchResults = this.GetGroupedDetailViewResults(query).ToList(); - - // Assert - Assert.AreEqual(1, searchResults.Count()); - Assert.AreEqual(1, searchResults.First().Results.Count); - Assert.AreEqual(tabUrl, searchResults.First().Results.First().DocumentUrl); - Assert.AreEqual(titleModified, searchResults.First().Results.First().Title); - } } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs index 436e343de39..6f0f488cd7c 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/InternalServices/TabVersionControllerTests.cs @@ -23,37 +23,12 @@ public class TabVersionControllerTests { private const int UserID = 1; private const int TabID = 99; - + private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); + private Mock _mockCBO; private Mock _mockUserController; private Mock _mockHostController; - - private class TabVersionControllerTestable : TabVersionController - { - } - - private class DateUtilsTestable : DateUtils - { - public static new TimeZoneInfo GetDatabaseDateTimeOffset() - { - var timeZoneId = "UTC"; - return TimeZoneInfo.CreateCustomTimeZone(timeZoneId, new TimeSpan(0, 0, 0), timeZoneId, timeZoneId); - } - } - - private class TestCaseFactory - { - public static IEnumerable TestCases() - { - yield return new TestCaseData("Central European Standard Time", new DateTime(2018, 08, 15, 14, 0, 0)); - yield return new TestCaseData("Russian Standard Time", new DateTime(2018, 08, 15, 15, 0, 0)); - yield return new TestCaseData("SE Asia Standard Time", new DateTime(2018, 08, 15, 19, 0, 0)); - } - } - // Assuming 12:00 Aug 15, 2018 server local time - private readonly DateTime ServerCreateOnDate = new DateTime(2018, 08, 15, 12, 0, 0, DateTimeKind.Unspecified); - [SetUp] public void Setup() { @@ -62,7 +37,7 @@ public void Setup() this.SetupHostController(); } - [Test] + [Test] [TestCaseSource(typeof(TestCaseFactory), "TestCases")] public void GetTabVersions_Verify_User_Preferred_TimeZone(string userPreferredTimeZone, DateTime expectedDateTime) { @@ -99,7 +74,7 @@ private void SetupUserController(string timeZoneId) private UserInfo GetMockedUser(string timeZoneId) { - var profile = new UserProfile() + var profile = new UserProfile() { PreferredTimeZone = this.GetMockedUserTimeZone(timeZoneId), }; @@ -156,5 +131,29 @@ private void SetupHostController() this._mockHostController.Setup(c => c.GetString(It.IsRegex("PerformanceSetting"))).Returns(Globals.PerformanceSettings.LightCaching.ToString()); HostController.RegisterInstance(this._mockHostController.Object); } + + private class TabVersionControllerTestable : TabVersionController + {} + + private class DateUtilsTestable : DateUtils + { + public static new TimeZoneInfo GetDatabaseDateTimeOffset() + { + var timeZoneId = "UTC"; + return TimeZoneInfo.CreateCustomTimeZone(timeZoneId, new TimeSpan(0, 0, 0), timeZoneId, timeZoneId); + } + } + + private class TestCaseFactory + { + public static IEnumerable TestCases() + { + yield return new TestCaseData("Central European Standard Time", new DateTime(2018, 08, 15, 14, 0, 0)); + yield return new TestCaseData("Russian Standard Time", new DateTime(2018, 08, 15, 15, 0, 0)); + yield return new TestCaseData("SE Asia Standard Time", new DateTime(2018, 08, 15, 19, 0, 0)); + } + } + + // Assuming 12:00 Aug 15, 2018 server local time } } diff --git a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs index 7c01201f655..bc5ee0353b0 100644 --- a/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs +++ b/DNN Platform/Tests/DotNetNuke.Tests.Web/Mvp/ModuleSettingsPresenterTests.cs @@ -15,15 +15,15 @@ namespace DotNetNuke.Tests.Web.Mvp [TestFixture] public class ModuleSettingsPresenterTests - { + { private const int _moduleSettingCount = 2; private const string _moduleSettingName = "moduleKey{0}"; private const string _moduleSettingValue = "value{0}"; private const int _tabModuleSettingCount = 3; private const string _tabModuleSettingName = "tabModuleKey{0}"; - private const string _tabModuleSettingValue = "value{0}"; - + private const string _tabModuleSettingValue = "value{0}"; + [Test] public void ModuleSettingsPresenter_Load_Initialises_Both_Dictionaries_On_PostBack() { @@ -85,14 +85,6 @@ 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() @@ -102,7 +94,7 @@ public void ModuleSettingsPresenter_SaveSettings_Saves_ModuleSettings() view.SetupGet(v => v.Model).Returns(new SettingsModel()); var controller = new Mock(); - + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = true; view.Raise(v => v.Load += null, EventArgs.Empty); @@ -127,7 +119,7 @@ public void ModuleSettingsPresenter_SaveSettings_Saves_TabModuleSettings() view.SetupGet(v => v.Model).Returns(new SettingsModel()); var controller = new Mock(); - + var presenter = new TestSettingsPresenter(view.Object) { ModuleContext = this.CreateModuleContext() }; presenter.IsPostBack = true; view.Raise(v => v.Load += null, EventArgs.Empty); @@ -151,13 +143,21 @@ private ModuleInstanceContext CreateModuleContext() { context.Configuration.ModuleSettings.Add(string.Format(_moduleSettingName, i), string.Format(_moduleSettingValue, i)); } - + for (int i = 1; i <= _tabModuleSettingCount; i++) { context.Configuration.TabModuleSettings.Add(string.Format(_tabModuleSettingName, i), string.Format(_tabModuleSettingValue, i)); } return context; - } + } + + public class TestSettingsPresenter : ModuleSettingsPresenter, SettingsModel> + { + public TestSettingsPresenter(ISettingsView view) + : base(view) + { + } + } } } diff --git a/DNN Platform/Website/Default.aspx.cs b/DNN Platform/Website/Default.aspx.cs index 46cbd57c23f..0ee040e5e7e 100644 --- a/DNN Platform/Website/Default.aspx.cs +++ b/DNN Platform/Website/Default.aspx.cs @@ -64,6 +64,14 @@ public DefaultPage() this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + public string CurrentSkinPath + { + get + { + return ((PortalSettings)HttpContext.Current.Items["PortalSettings"]).ActiveTab.SkinPath; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets property to allow the programmatic assigning of ScrollTop position. @@ -91,14 +99,6 @@ 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 @@ -316,6 +316,88 @@ protected override void OnInit(EventArgs e) } } + /// ----------------------------------------------------------------------------- + /// + /// Initialize the Scrolltop html control which controls the open / closed nature of each module. + /// + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.ManageInstallerFiles(); + + if (!string.IsNullOrEmpty(this.ScrollTop.Value)) + { + DNNClientAPI.SetScrollTop(this.Page); + this.ScrollTop.Value = this.ScrollTop.Value; + } + } + + protected override void OnPreRender(EventArgs evt) + { + base.OnPreRender(evt); + + // Set the Head tags + this.metaPanel.Visible = !UrlUtils.InPopUp(); + if (!UrlUtils.InPopUp()) + { + this.MetaGenerator.Content = this.Generator; + this.MetaGenerator.Visible = !string.IsNullOrEmpty(this.Generator); + this.MetaAuthor.Content = this.PortalSettings.PortalName; + /* + * Never show to be html5 compatible and stay backward compatible + * + * MetaCopyright.Content = Copyright; + * MetaCopyright.Visible = (!String.IsNullOrEmpty(Copyright)); + */ + this.MetaKeywords.Content = this.KeyWords; + this.MetaKeywords.Visible = !string.IsNullOrEmpty(this.KeyWords); + this.MetaDescription.Content = this.Description; + this.MetaDescription.Visible = !string.IsNullOrEmpty(this.Description); + } + + this.Page.Header.Title = this.Title; + if (!string.IsNullOrEmpty(this.PortalSettings.AddCompatibleHttpHeader) && !this.HeaderIsWritten) + { + this.Page.Response.AddHeader("X-UA-Compatible", this.PortalSettings.AddCompatibleHttpHeader); + } + + if (!string.IsNullOrEmpty(this.CanonicalLinkUrl)) + { + // Add Canonical using the primary alias + var canonicalLink = new HtmlLink(); + canonicalLink.Href = this.CanonicalLinkUrl; + canonicalLink.Attributes.Add("rel", "canonical"); + + // Add the HtmlLink to the Head section of the page. + this.Page.Header.Controls.Add(canonicalLink); + } + } + + protected override void Render(HtmlTextWriter writer) + { + if (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) + { + var editClass = "dnnEditState"; + + var bodyClass = this.Body.Attributes["class"]; + if (!string.IsNullOrEmpty(bodyClass)) + { + this.Body.Attributes["class"] = string.Format("{0} {1}", bodyClass, editClass); + } + else + { + this.Body.Attributes["class"] = editClass; + } + } + + base.Render(writer); + } + /// ----------------------------------------------------------------------------- /// /// @@ -695,87 +777,5 @@ private IFileInfo GetBackgroundFileInfoCallBack(CacheItemArgs itemArgs) { return FileManager.Instance.GetFile(this.PortalSettings.PortalId, this.PortalSettings.BackgroundFile); } - - /// ----------------------------------------------------------------------------- - /// - /// Initialize the Scrolltop html control which controls the open / closed nature of each module. - /// - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.ManageInstallerFiles(); - - if (!string.IsNullOrEmpty(this.ScrollTop.Value)) - { - DNNClientAPI.SetScrollTop(this.Page); - this.ScrollTop.Value = this.ScrollTop.Value; - } - } - - protected override void OnPreRender(EventArgs evt) - { - base.OnPreRender(evt); - - // Set the Head tags - this.metaPanel.Visible = !UrlUtils.InPopUp(); - if (!UrlUtils.InPopUp()) - { - this.MetaGenerator.Content = this.Generator; - this.MetaGenerator.Visible = !string.IsNullOrEmpty(this.Generator); - this.MetaAuthor.Content = this.PortalSettings.PortalName; - /* - * Never show to be html5 compatible and stay backward compatible - * - * MetaCopyright.Content = Copyright; - * MetaCopyright.Visible = (!String.IsNullOrEmpty(Copyright)); - */ - this.MetaKeywords.Content = this.KeyWords; - this.MetaKeywords.Visible = !string.IsNullOrEmpty(this.KeyWords); - this.MetaDescription.Content = this.Description; - this.MetaDescription.Visible = !string.IsNullOrEmpty(this.Description); - } - - this.Page.Header.Title = this.Title; - if (!string.IsNullOrEmpty(this.PortalSettings.AddCompatibleHttpHeader) && !this.HeaderIsWritten) - { - this.Page.Response.AddHeader("X-UA-Compatible", this.PortalSettings.AddCompatibleHttpHeader); - } - - if (!string.IsNullOrEmpty(this.CanonicalLinkUrl)) - { - // Add Canonical using the primary alias - var canonicalLink = new HtmlLink(); - canonicalLink.Href = this.CanonicalLinkUrl; - canonicalLink.Attributes.Add("rel", "canonical"); - - // Add the HtmlLink to the Head section of the page. - this.Page.Header.Controls.Add(canonicalLink); - } - } - - protected override void Render(HtmlTextWriter writer) - { - if (this.PortalSettings.UserMode == PortalSettings.Mode.Edit) - { - var editClass = "dnnEditState"; - - var bodyClass = this.Body.Attributes["class"]; - if (!string.IsNullOrEmpty(bodyClass)) - { - this.Body.Attributes["class"] = string.Format("{0} {1}", bodyClass, editClass); - } - else - { - this.Body.Attributes["class"] = editClass; - } - } - - base.Render(writer); - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs index c07f32af88b..a5878db7d3e 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Authentication.ascx.cs @@ -92,7 +92,7 @@ protected void OnUpdateClick(object sender, EventArgs e) break; } } - + if (!enabled) { // Display warning diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs index 3e129830198..82bb539ade3 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Login.ascx.cs @@ -54,6 +54,7 @@ public partial class Login : UserModuleBase { private const string LOGIN_PATH = "/login"; private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Login)); + private static readonly Regex UserLanguageRegex = new Regex( "(.*)(&|\\?)(language=)([^&\\?]+)(.*)", RegexOptions.IgnoreCase | RegexOptions.Compiled); @@ -69,91 +70,6 @@ public Login() this._navigationManager = this.DependencyProvider.GetRequiredService(); } - /// - /// Gets or sets and sets the current AuthenticationType. - /// - protected string AuthenticationType - { - get - { - var authenticationType = Null.NullString; - if (this.ViewState["AuthenticationType"] != null) - { - authenticationType = Convert.ToString(this.ViewState["AuthenticationType"]); - } - - return authenticationType; - } - - set - { - this.ViewState["AuthenticationType"] = value; - } - } - - /// - /// Gets or sets a value indicating whether gets and sets a flag that determines whether the user should be automatically registered. - /// - protected bool AutoRegister - { - get - { - var autoRegister = Null.NullBoolean; - if (this.ViewState["AutoRegister"] != null) - { - autoRegister = Convert.ToBoolean(this.ViewState["AutoRegister"]); - } - - return autoRegister; - } - - set - { - this.ViewState["AutoRegister"] = value; - } - } - - protected NameValueCollection ProfileProperties - { - get - { - var profile = new NameValueCollection(); - if (this.ViewState["ProfileProperties"] != null) - { - profile = (NameValueCollection)this.ViewState["ProfileProperties"]; - } - - return profile; - } - - set - { - this.ViewState["ProfileProperties"] = value; - } - } - - /// - /// Gets or sets and sets the current Page No. - /// - protected int PageNo - { - get - { - var pageNo = 0; - if (this.ViewState["PageNo"] != null) - { - pageNo = Convert.ToInt32(this.ViewState["PageNo"]); - } - - return pageNo; - } - - set - { - this.ViewState["PageNo"] = value; - } - } - /// /// Gets the Redirect URL (after successful login). /// @@ -256,83 +172,141 @@ protected string RedirectURL } /// - /// Gets or sets a value indicating whether gets and sets a flag that determines whether a permanent auth cookie should be created. + /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. /// - protected bool RememberMe + protected bool UseCaptcha { get { - var rememberMe = Null.NullBoolean; - if (this.ViewState["RememberMe"] != null) + object setting = GetSetting(this.PortalId, "Security_CaptchaLogin"); + return Convert.ToBoolean(setting); + } + } + + /// + /// Gets or sets and sets the current AuthenticationType. + /// + protected string AuthenticationType + { + get + { + var authenticationType = Null.NullString; + if (this.ViewState["AuthenticationType"] != null) { - rememberMe = Convert.ToBoolean(this.ViewState["RememberMe"]); + authenticationType = Convert.ToString(this.ViewState["AuthenticationType"]); } - return rememberMe; + return authenticationType; } set { - this.ViewState["RememberMe"] = value; + this.ViewState["AuthenticationType"] = value; } } /// - /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. + /// Gets or sets a value indicating whether gets and sets a flag that determines whether the user should be automatically registered. /// - protected bool UseCaptcha + protected bool AutoRegister { get { - object setting = GetSetting(this.PortalId, "Security_CaptchaLogin"); - return Convert.ToBoolean(setting); + var autoRegister = Null.NullBoolean; + if (this.ViewState["AutoRegister"] != null) + { + autoRegister = Convert.ToBoolean(this.ViewState["AutoRegister"]); + } + + return autoRegister; + } + + set + { + this.ViewState["AutoRegister"] = value; } } - protected UserLoginStatus LoginStatus + protected NameValueCollection ProfileProperties { get { - UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; - if (this.ViewState["LoginStatus"] != null) + var profile = new NameValueCollection(); + if (this.ViewState["ProfileProperties"] != null) { - loginStatus = (UserLoginStatus)this.ViewState["LoginStatus"]; + profile = (NameValueCollection)this.ViewState["ProfileProperties"]; } - return loginStatus; + return profile; } set { - this.ViewState["LoginStatus"] = value; + this.ViewState["ProfileProperties"] = value; } } - private bool NeedRedirectAfterLogin => - this.LoginStatus == UserLoginStatus.LOGIN_SUCCESS - || this.LoginStatus == UserLoginStatus.LOGIN_SUPERUSER - || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD - || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; + /// + /// Gets or sets and sets the current Page No. + /// + protected int PageNo + { + get + { + var pageNo = 0; + if (this.ViewState["PageNo"] != null) + { + pageNo = Convert.ToInt32(this.ViewState["PageNo"]); + } + + return pageNo; + } + + set + { + this.ViewState["PageNo"] = value; + } + } /// - /// Replaces the original language with user language. + /// Gets or sets a value indicating whether gets and sets a flag that determines whether a permanent auth cookie should be created. /// - /// - /// - /// - /// - private static string ReplaceLanguage(string Url, string originalLanguage, string newLanguage) + protected bool RememberMe { - var returnValue = Host.UseFriendlyUrls - ? Regex.Replace(Url, "(.*)(/" + originalLanguage + "/)(.*)", "$1/" + newLanguage + "/$3", RegexOptions.IgnoreCase) - : UserLanguageRegex.Replace(Url, "$1$2$3" + newLanguage + "$5"); - return returnValue; + get + { + var rememberMe = Null.NullBoolean; + if (this.ViewState["RememberMe"] != null) + { + rememberMe = Convert.ToBoolean(this.ViewState["RememberMe"]); + } + + return rememberMe; + } + + set + { + this.ViewState["RememberMe"] = value; + } } - private bool IsRedirectingFromLoginUrl() + protected UserLoginStatus LoginStatus { - return this.Request.UrlReferrer != null && - this.Request.UrlReferrer.LocalPath.ToLowerInvariant().EndsWith(LOGIN_PATH); + get + { + UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; + if (this.ViewState["LoginStatus"] != null) + { + loginStatus = (UserLoginStatus)this.ViewState["LoginStatus"]; + } + + return loginStatus; + } + + set + { + this.ViewState["LoginStatus"] = value; + } } /// @@ -379,6 +353,12 @@ protected string UserName } } + private bool NeedRedirectAfterLogin => + this.LoginStatus == UserLoginStatus.LOGIN_SUCCESS + || this.LoginStatus == UserLoginStatus.LOGIN_SUPERUSER + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREHOSTPASSWORD + || this.LoginStatus == UserLoginStatus.LOGIN_INSECUREADMINPASSWORD; + /// /// Page_Init runs when the control is initialised. /// @@ -511,929 +491,950 @@ protected override void OnLoad(EventArgs e) } } - private void AddLoginControlAttributes(AuthenticationLoginBase loginControl) + /// + /// cmdAssociate_Click runs when the associate button is clicked. + /// + /// + /// + protected void cmdAssociate_Click(object sender, EventArgs e) { - // search selected authentication control for username and password fields - // and inject autocomplete=off so browsers do not remember sensitive details - var username = loginControl.FindControl("txtUsername") as WebControl; - if (username != null) + if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || (!this.UseCaptcha)) { - username.Attributes.Add("AUTOCOMPLETE", "off"); - } + UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; + var userRequestIpAddressController = UserRequestIPAddressController.Instance; + var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); + UserInfo objUser = UserController.ValidateUser( + this.PortalId, + this.txtUsername.Text, + this.txtPassword.Text, + "DNN", + string.Empty, + this.PortalSettings.PortalName, + ipAddress, + ref loginStatus); + if (loginStatus == UserLoginStatus.LOGIN_SUCCESS) + { + // Assocate alternate Login with User and proceed with Login + AuthenticationController.AddUserAuthentication(objUser.UserID, this.AuthenticationType, this.UserToken); + if (objUser != null) + { + this.UpdateProfile(objUser, true); + } - var password = loginControl.FindControl("txtPassword") as WebControl; - if (password != null) - { - password.Attributes.Add("AUTOCOMPLETE", "off"); + this.ValidateUser(objUser, true); + } + else + { + this.AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true); + } } } - private void BindLogin() + /// + /// cmdCreateUser runs when the register (as new user) button is clicked. + /// + /// + /// + protected void cmdCreateUser_Click(object sender, EventArgs e) { - List authSystems = AuthenticationController.GetEnabledAuthenticationServices(); - AuthenticationLoginBase defaultLoginControl = null; - var defaultAuthProvider = PortalController.GetPortalSetting("DefaultAuthProvider", this.PortalId, "DNN"); - foreach (AuthenticationInfo authSystem in authSystems) - { - try - { - // Figure out if known Auth types are enabled (so we can improve perf and stop loading the control) - bool enabled = true; - if (authSystem.AuthenticationType.Equals("Facebook") || authSystem.AuthenticationType.Equals("Google") - || authSystem.AuthenticationType.Equals("Live") || authSystem.AuthenticationType.Equals("Twitter")) - { - enabled = AuthenticationController.IsEnabledForPortal(authSystem, this.PortalSettings.PortalId); - } + this.User.Membership.Password = UserController.GeneratePassword(); - if (enabled) - { - var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); - this.BindLoginControl(authLoginControl, authSystem); - if (authSystem.AuthenticationType == "DNN") - { - defaultLoginControl = authLoginControl; - } + if (this.AutoRegister) + { + this.ctlUser.User = this.User; - // Check if AuthSystem is Enabled - if (authLoginControl.Enabled) - { - var oAuthLoginControl = authLoginControl as OAuthLoginBase; - if (oAuthLoginControl != null) - { - // Add Login Control to List - this._oAuthControls.Add(oAuthLoginControl); - } - else - { - if (authLoginControl.AuthenticationType == defaultAuthProvider) - { - this._defaultauthLogin.Add(authLoginControl); - } - else - { - // Add Login Control to List - this._loginControls.Add(authLoginControl); - } - } - } - } - } - catch (Exception ex) - { - Exceptions.LogException(ex); - } + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); } - - int authCount = this._loginControls.Count + this._defaultauthLogin.Count; - switch (authCount) + else { - case 0: - // No enabled controls - inject default dnn control - if (defaultLoginControl == null) - { - // No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN) - AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN"); - var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); - this.BindLoginControl(authLoginControl, authSystem); - this.DisplayLoginControl(authLoginControl, false, false); - } - else - { - // if there are social authprovider only - if (this._oAuthControls.Count == 0) - { - // Portal has no login controls enabled so load default DNN control - this.DisplayLoginControl(defaultLoginControl, false, false); - } - } - - break; - case 1: - // We don't want the control to render with tabbed interface - this.DisplayLoginControl( - this._defaultauthLogin.Count == 1 - ? this._defaultauthLogin[0] - : this._loginControls.Count == 1 - ? this._loginControls[0] - : this._oAuthControls[0], - false, - false); - break; - default: - // make sure defaultAuth provider control is diplayed first - if (this._defaultauthLogin.Count > 0) - { - this.DisplayTabbedLoginControl(this._defaultauthLogin[0], this.tsLogin.Tabs); - } - - foreach (AuthenticationLoginBase authLoginControl in this._loginControls) - { - this.DisplayTabbedLoginControl(authLoginControl, this.tsLogin.Tabs); - } - - break; + if (this.ctlUser.IsValid) + { + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); + } } - - this.BindOAuthControls(); } - private void BindOAuthControls() + /// + /// cmdProceed_Click runs when the Proceed Anyway button is clicked. + /// + /// + /// + protected void cmdProceed_Click(object sender, EventArgs e) { - foreach (OAuthLoginBase oAuthLoginControl in this._oAuthControls) - { - this.socialLoginControls.Controls.Add(oAuthLoginControl); - } + var user = this.ctlPassword.User; + this.ValidateUser(user, true); } - private void BindLoginControl(AuthenticationLoginBase authLoginControl, AuthenticationInfo authSystem) + /// + /// PasswordUpdated runs when the password is updated. + /// + /// + /// + protected void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) { - // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) - // this is necessary for the Localization in PageBase - authLoginControl.AuthenticationType = authSystem.AuthenticationType; - authLoginControl.ID = Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc) + "_" + authSystem.AuthenticationType; - authLoginControl.LocalResourceFile = authLoginControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + - Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc); - authLoginControl.RedirectURL = this.RedirectURL; - authLoginControl.ModuleConfiguration = this.ModuleConfiguration; - if (authSystem.AuthenticationType != "DNN") + PasswordUpdateStatus status = e.UpdateStatus; + if (status == PasswordUpdateStatus.Success) { - authLoginControl.ViewStateMode = ViewStateMode.Enabled; + this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); + var user = this.ctlPassword.User; + user.Membership.LastPasswordChangeDate = DateTime.Now; + user.Membership.UpdatePassword = false; + this.LoginStatus = user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS; + UserLoginStatus userstatus = UserLoginStatus.LOGIN_FAILURE; + UserController.CheckInsecurePassword(user.Username, user.Membership.Password, ref userstatus); + this.LoginStatus = userstatus; + this.ValidateUser(user, true); } - - // attempt to inject control attributes - this.AddLoginControlAttributes(authLoginControl); - authLoginControl.UserAuthenticated += this.UserAuthenticated; - } - - private void BindRegister() - { - this.lblType.Text = this.AuthenticationType; - this.lblToken.Text = this.UserToken; - - // Verify that the current user has access to this page - if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && this.Request.IsAuthenticated == false) + else { - this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); } + } - this.lblRegisterHelp.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); - switch (this.PortalSettings.UserRegistration) + /// + /// DataConsentCompleted runs after the user has gone through the data consent screen. + /// + /// + /// + protected void DataConsentCompleted(object sender, DataConsent.DataConsentEventArgs e) + { + switch (e.Status) { - case (int)Globals.PortalRegistrationType.PrivateRegistration: - this.lblRegisterHelp.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); + case DataConsent.DataConsentStatus.Consented: + this.ValidateUser(this.ctlDataConsent.User, true); break; - case (int)Globals.PortalRegistrationType.PublicRegistration: - this.lblRegisterHelp.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); + case DataConsent.DataConsentStatus.Cancelled: + case DataConsent.DataConsentStatus.RemovedAccount: + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); break; - case (int)Globals.PortalRegistrationType.VerifiedRegistration: - this.lblRegisterHelp.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); + case DataConsent.DataConsentStatus.FailedToRemoveAccount: + this.AddModuleMessage("FailedToRemoveAccount", ModuleMessage.ModuleMessageType.RedError, true); break; } + } - if (this.AutoRegister) - { - this.InitialiseUser(); - } - - bool UserValid = true; - if (string.IsNullOrEmpty(this.User.Username) || string.IsNullOrEmpty(this.User.Email) || string.IsNullOrEmpty(this.User.FirstName) || string.IsNullOrEmpty(this.User.LastName)) - { - UserValid = Null.NullBoolean; - } - - if (this.AutoRegister && UserValid) - { - this.ctlUser.Visible = false; - this.lblRegisterTitle.Text = Localization.GetString("CreateTitle", this.LocalResourceFile); - this.cmdCreateUser.Text = Localization.GetString("cmdCreate", this.LocalResourceFile); - } - else - { - this.lblRegisterHelp.Text += Localization.GetString("Required", Localization.SharedResourceFile); - this.lblRegisterTitle.Text = Localization.GetString("RegisterTitle", this.LocalResourceFile); - this.cmdCreateUser.Text = Localization.GetString("cmdRegister", this.LocalResourceFile); - this.ctlUser.ShowPassword = false; - this.ctlUser.ShowUpdate = false; - this.ctlUser.User = this.User; - this.ctlUser.DataBind(); - } + /// + /// ProfileUpdated runs when the profile is updated. + /// + protected void ProfileUpdated(object sender, EventArgs e) + { + // Authorize User + this.ValidateUser(this.ctlProfile.User, true); } - private void DisplayLoginControl(AuthenticationLoginBase authLoginControl, bool addHeader, bool addFooter) + /// + /// UserAuthenticated runs when the user is authenticated by one of the child + /// Authentication controls. + /// + protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) { - // Create a
    to hold the control - var container = new HtmlGenericControl { TagName = "div", ID = authLoginControl.AuthenticationType, ViewStateMode = ViewStateMode.Disabled }; + this.LoginStatus = e.LoginStatus; - // Add Settings Control to Container - container.Controls.Add(authLoginControl); - - // Add a Section Header - SectionHeadControl sectionHeadControl; - if (addHeader) + // Check the Login Status + switch (this.LoginStatus) { - sectionHeadControl = (SectionHeadControl)this.LoadControl("~/controls/SectionHeadControl.ascx"); - sectionHeadControl.IncludeRule = true; - sectionHeadControl.CssClass = "Head"; - sectionHeadControl.Text = Localization.GetString("Title", authLoginControl.LocalResourceFile); + case UserLoginStatus.LOGIN_USERNOTAPPROVED: + switch (e.Message) + { + case "UnverifiedUser": + if (e.User != null) + { + // First update the profile (if any properties have been passed) + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.RememberMe = e.RememberMe; + this.UpdateProfile(e.User, true); + this.ValidateUser(e.User, false); + } - sectionHeadControl.Section = container.ID; + break; + case "EnterCode": + this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true); + break; + case "InvalidCode": + case "UserNotAuthorized": + this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + break; + default: + this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + break; + } - // Add Section Head Control to Container - this.pnlLoginContainer.Controls.Add(sectionHeadControl); - } + break; + case UserLoginStatus.LOGIN_USERLOCKEDOUT: + if (Host.AutoAccountUnlockDuration > 0) + { + this.AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", this.LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true); + } + else + { + this.AddLocalizedModuleMessage(Localization.GetString("UserLockedOut_ContactAdmin", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError, true); + } - // Add Container to Controls - this.pnlLoginContainer.Controls.Add(container); + // notify administrator about account lockout ( possible hack attempt ) + var Custom = new ArrayList { e.UserToken }; - // Add LineBreak - if (addFooter) - { - this.pnlLoginContainer.Controls.Add(new LiteralControl("
    ")); - } + var message = new Message + { + FromUserID = this.PortalSettings.AdministratorId, + ToUserID = this.PortalSettings.AdministratorId, + Subject = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom), + Body = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom), + Status = MessageStatusType.Unread, + }; - // Display the container - this.pnlLoginContainer.Visible = true; - } + // _messagingController.SaveMessage(_message); + Mail.SendEmail(this.PortalSettings.Email, this.PortalSettings.Email, message.Subject, message.Body); + break; + case UserLoginStatus.LOGIN_FAILURE: + // A Login Failure can mean one of two things: + // 1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account + // 2 - User was not authenticated + if (e.Authenticated) + { + this.AutoRegister = e.AutoRegister; + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.UserToken = e.UserToken; + this.UserName = e.UserName; + if (this.AutoRegister) + { + this.InitialiseUser(); + this.User.Membership.Password = UserController.GeneratePassword(); - private void DisplayTabbedLoginControl(AuthenticationLoginBase authLoginControl, TabStripTabCollection Tabs) - { - var tab = new DNNTab(Localization.GetString("Title", authLoginControl.LocalResourceFile)) { ID = authLoginControl.AuthenticationType }; + this.ctlUser.User = this.User; - tab.Controls.Add(authLoginControl); - Tabs.Add(tab); + // Call the Create User method of the User control so that it can create + // the user and raise the appropriate event(s) + this.ctlUser.CreateUser(); + } + else + { + this.PageNo = 1; + this.ShowPanel(); + } + } + else + { + if (string.IsNullOrEmpty(e.Message)) + { + this.AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true); + } + else + { + this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); + } + } - this.tsLogin.Visible = true; + break; + default: + if (e.User != null) + { + // First update the profile (if any properties have been passed) + this.AuthenticationType = e.AuthenticationType; + this.ProfileProperties = e.Profile; + this.RememberMe = e.RememberMe; + this.UpdateProfile(e.User, true); + this.ValidateUser(e.User, e.AuthenticationType != "DNN"); + } + + break; + } } - private void InitialiseUser() + /// + /// UserCreateCompleted runs when a new user has been Created. + /// + /// + /// + protected void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedEventArgs e) { - // Load any Profile properties that may have been returned - this.UpdateProfile(this.User, false); + var strMessage = string.Empty; + try + { + if (e.CreateStatus == UserCreateStatus.Success) + { + // Assocate alternate Login with User and proceed with Login + AuthenticationController.AddUserAuthentication(e.NewUser.UserID, this.AuthenticationType, this.UserToken); - // Set UserName to authentication Token - this.User.Username = this.GenerateUserName(); + strMessage = this.CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, true); + if (string.IsNullOrEmpty(strMessage)) + { + // First update the profile (if any properties have been passed) + this.UpdateProfile(e.NewUser, true); - // Set DisplayName to UserToken if null - if (string.IsNullOrEmpty(this.User.DisplayName)) - { - this.User.DisplayName = this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); + this.ValidateUser(e.NewUser, true); + } + } + else + { + this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); + } } - - // Parse DisplayName into FirstName/LastName - if (this.User.DisplayName.IndexOf(' ') > 0) + catch (Exception exc) // Module failed to load { - this.User.FirstName = this.User.DisplayName.Substring(0, this.User.DisplayName.IndexOf(' ')); - this.User.LastName = this.User.DisplayName.Substring(this.User.DisplayName.IndexOf(' ') + 1); + Exceptions.ProcessModuleLoadException(this, exc); } + } - // Set FirstName to Authentication Type (if null) - if (string.IsNullOrEmpty(this.User.FirstName)) + /// + /// 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); + } + + private void AddLoginControlAttributes(AuthenticationLoginBase loginControl) + { + // search selected authentication control for username and password fields + // and inject autocomplete=off so browsers do not remember sensitive details + var username = loginControl.FindControl("txtUsername") as WebControl; + if (username != null) { - this.User.FirstName = this.AuthenticationType; + username.Attributes.Add("AUTOCOMPLETE", "off"); } - // Set FirstName to "User" (if null) - if (string.IsNullOrEmpty(this.User.LastName)) + var password = loginControl.FindControl("txtPassword") as WebControl; + if (password != null) { - this.User.LastName = "User"; + password.Attributes.Add("AUTOCOMPLETE", "off"); } } - private string GenerateUserName() + private void BindLogin() { - if (!string.IsNullOrEmpty(this.UserName)) - { - return this.UserName; - } - - // Try Email prefix - var emailPrefix = string.Empty; - if (!string.IsNullOrEmpty(this.User.Email)) + List authSystems = AuthenticationController.GetEnabledAuthenticationServices(); + AuthenticationLoginBase defaultLoginControl = null; + var defaultAuthProvider = PortalController.GetPortalSetting("DefaultAuthProvider", this.PortalId, "DNN"); + foreach (AuthenticationInfo authSystem in authSystems) { - if (this.User.Email.IndexOf("@", StringComparison.Ordinal) != -1) + try { - emailPrefix = this.User.Email.Substring(0, this.User.Email.IndexOf("@", StringComparison.Ordinal)); - var user = UserController.GetUserByName(this.PortalId, emailPrefix); - if (user == null) + // Figure out if known Auth types are enabled (so we can improve perf and stop loading the control) + bool enabled = true; + if (authSystem.AuthenticationType.Equals("Facebook") || authSystem.AuthenticationType.Equals("Google") + || authSystem.AuthenticationType.Equals("Live") || authSystem.AuthenticationType.Equals("Twitter")) { - return emailPrefix; + enabled = AuthenticationController.IsEnabledForPortal(authSystem, this.PortalSettings.PortalId); } - } - } - // Try First Name - if (!string.IsNullOrEmpty(this.User.FirstName)) - { - var user = UserController.GetUserByName(this.PortalId, this.User.FirstName); - if (user == null) - { - return this.User.FirstName; - } - } + if (enabled) + { + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + this.BindLoginControl(authLoginControl, authSystem); + if (authSystem.AuthenticationType == "DNN") + { + defaultLoginControl = authLoginControl; + } - // Try Last Name - if (!string.IsNullOrEmpty(this.User.LastName)) - { - var user = UserController.GetUserByName(this.PortalId, this.User.LastName); - if (user == null) - { - return this.User.LastName; - } - } - - // Try First Name + space + First letter last name - if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) - { - var newUserName = this.User.FirstName + " " + this.User.LastName.Substring(0, 1); - var user = UserController.GetUserByName(this.PortalId, newUserName); - if (user == null) - { - return newUserName; + // Check if AuthSystem is Enabled + if (authLoginControl.Enabled) + { + var oAuthLoginControl = authLoginControl as OAuthLoginBase; + if (oAuthLoginControl != null) + { + // Add Login Control to List + this._oAuthControls.Add(oAuthLoginControl); + } + else + { + if (authLoginControl.AuthenticationType == defaultAuthProvider) + { + this._defaultauthLogin.Add(authLoginControl); + } + else + { + // Add Login Control to List + this._loginControls.Add(authLoginControl); + } + } + } + } } - } - - // Try First letter of First Name + lastname - if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) - { - var newUserName = this.User.FirstName.Substring(0, 1) + this.User.LastName; - var user = UserController.GetUserByName(this.PortalId, newUserName); - if (user == null) + catch (Exception ex) { - return newUserName; + Exceptions.LogException(ex); } } - // Try Email Prefix + incremental numbers until unique name found - if (!string.IsNullOrEmpty(emailPrefix)) + int authCount = this._loginControls.Count + this._defaultauthLogin.Count; + switch (authCount) { - for (var i = 1; i < 10000; i++) - { - var newUserName = emailPrefix + i; - var user = UserController.GetUserByName(this.PortalId, newUserName); - if (user == null) + case 0: + // No enabled controls - inject default dnn control + if (defaultLoginControl == null) { - return newUserName; + // No controls enabled for portal, and default DNN control is not enabled by host, so load system default (DNN) + AuthenticationInfo authSystem = AuthenticationController.GetAuthenticationServiceByType("DNN"); + var authLoginControl = (AuthenticationLoginBase)this.LoadControl("~/" + authSystem.LoginControlSrc); + this.BindLoginControl(authLoginControl, authSystem); + this.DisplayLoginControl(authLoginControl, false, false); + } + else + { + // if there are social authprovider only + if (this._oAuthControls.Count == 0) + { + // Portal has no login controls enabled so load default DNN control + this.DisplayLoginControl(defaultLoginControl, false, false); + } } - } - } - - return this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); - } - /// ----------------------------------------------------------------------------- - /// - /// ShowPanel controls what "panel" is to be displayed. - /// - /// ----------------------------------------------------------------------------- - private void ShowPanel() - { - bool showLogin = this.PageNo == 0; - bool showRegister = this.PageNo == 1; - bool showPassword = this.PageNo == 2; - bool showProfile = this.PageNo == 3; - bool showDataConsent = this.PageNo == 4; - this.pnlProfile.Visible = showProfile; - this.pnlPassword.Visible = showPassword; - this.pnlLogin.Visible = showLogin; - this.pnlRegister.Visible = showRegister; - this.pnlAssociate.Visible = showRegister; - this.pnlDataConsent.Visible = showDataConsent; - switch (this.PageNo) - { - case 0: - this.BindLogin(); break; case 1: - this.BindRegister(); - break; - case 2: - this.ctlPassword.UserId = this.UserId; - this.ctlPassword.DataBind(); - break; - case 3: - this.ctlProfile.UserId = this.UserId; - this.ctlProfile.DataBind(); + // We don't want the control to render with tabbed interface + this.DisplayLoginControl( + this._defaultauthLogin.Count == 1 + ? this._defaultauthLogin[0] + : this._loginControls.Count == 1 + ? this._loginControls[0] + : this._oAuthControls[0], + false, + false); break; - case 4: - this.ctlDataConsent.UserId = this.UserId; - this.ctlDataConsent.DataBind(); + default: + // make sure defaultAuth provider control is diplayed first + if (this._defaultauthLogin.Count > 0) + { + this.DisplayTabbedLoginControl(this._defaultauthLogin[0], this.tsLogin.Tabs); + } + + foreach (AuthenticationLoginBase authLoginControl in this._loginControls) + { + this.DisplayTabbedLoginControl(authLoginControl, this.tsLogin.Tabs); + } + break; } - if (showProfile && UrlUtils.InPopUp()) + this.BindOAuthControls(); + } + + private void BindOAuthControls() + { + foreach (OAuthLoginBase oAuthLoginControl in this._oAuthControls) { - ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ResizePopup", "if(parent.$('#iPopUp').length > 0 && parent.$('#iPopUp').dialog('isOpen')){parent.$('#iPopUp').dialog({width: 950, height: 550}).dialog({position: 'center'});};", true); + this.socialLoginControls.Controls.Add(oAuthLoginControl); } } - private void UpdateProfile(UserInfo objUser, bool update) + private void BindLoginControl(AuthenticationLoginBase authLoginControl, AuthenticationInfo authSystem) { - bool bUpdateUser = false; - if (this.ProfileProperties.Count > 0) + // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) + // this is necessary for the Localization in PageBase + authLoginControl.AuthenticationType = authSystem.AuthenticationType; + authLoginControl.ID = Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc) + "_" + authSystem.AuthenticationType; + authLoginControl.LocalResourceFile = authLoginControl.TemplateSourceDirectory + "/" + Localization.LocalResourceDirectory + "/" + + Path.GetFileNameWithoutExtension(authSystem.LoginControlSrc); + authLoginControl.RedirectURL = this.RedirectURL; + authLoginControl.ModuleConfiguration = this.ModuleConfiguration; + if (authSystem.AuthenticationType != "DNN") { - foreach (string key in this.ProfileProperties) - { - switch (key) - { - case "FirstName": - if (objUser.FirstName != this.ProfileProperties[key]) - { - objUser.FirstName = this.ProfileProperties[key]; - bUpdateUser = true; - } - - break; - case "LastName": - if (objUser.LastName != this.ProfileProperties[key]) - { - objUser.LastName = this.ProfileProperties[key]; - bUpdateUser = true; - } - - break; - case "Email": - if (objUser.Email != this.ProfileProperties[key]) - { - objUser.Email = this.ProfileProperties[key]; - bUpdateUser = true; - } + authLoginControl.ViewStateMode = ViewStateMode.Enabled; + } - break; - case "DisplayName": - if (objUser.DisplayName != this.ProfileProperties[key]) - { - objUser.DisplayName = this.ProfileProperties[key]; - bUpdateUser = true; - } + // attempt to inject control attributes + this.AddLoginControlAttributes(authLoginControl); + authLoginControl.UserAuthenticated += this.UserAuthenticated; + } - break; - default: - objUser.Profile.SetProfileProperty(key, this.ProfileProperties[key]); - break; - } - } + private void BindRegister() + { + this.lblType.Text = this.AuthenticationType; + this.lblToken.Text = this.UserToken; - if (update) - { - if (bUpdateUser) - { - UserController.UpdateUser(this.PortalId, objUser); - } + // Verify that the current user has access to this page + if (this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.NoRegistration && this.Request.IsAuthenticated == false) + { + this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); + } - ProfileController.UpdateUserProfile(objUser); - } + this.lblRegisterHelp.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_REGISTRATION_INSTRUCTIONS"); + switch (this.PortalSettings.UserRegistration) + { + case (int)Globals.PortalRegistrationType.PrivateRegistration: + this.lblRegisterHelp.Text += Localization.GetString("PrivateMembership", Localization.SharedResourceFile); + break; + case (int)Globals.PortalRegistrationType.PublicRegistration: + this.lblRegisterHelp.Text += Localization.GetString("PublicMembership", Localization.SharedResourceFile); + break; + case (int)Globals.PortalRegistrationType.VerifiedRegistration: + this.lblRegisterHelp.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); + break; } - } - /// ----------------------------------------------------------------------------- - /// - /// ValidateUser runs when the user has been authorized by the data store. It validates for - /// things such as an expiring password, valid profile, or missing DNN User Association. - /// - /// The logged in User. - /// Ignore the situation where the password is expiring (but not yet expired). - /// ----------------------------------------------------------------------------- - private void ValidateUser(UserInfo objUser, bool ignoreExpiring) - { - UserValidStatus validStatus = UserValidStatus.VALID; - string strMessage = Null.NullString; - DateTime expiryDate = Null.NullDate; - bool okToShowPanel = true; + if (this.AutoRegister) + { + this.InitialiseUser(); + } - validStatus = UserController.ValidateUser(objUser, this.PortalId, ignoreExpiring); + bool UserValid = true; + if (string.IsNullOrEmpty(this.User.Username) || string.IsNullOrEmpty(this.User.Email) || string.IsNullOrEmpty(this.User.FirstName) || string.IsNullOrEmpty(this.User.LastName)) + { + UserValid = Null.NullBoolean; + } - if (PasswordConfig.PasswordExpiry > 0) + if (this.AutoRegister && UserValid) { - expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); + this.ctlUser.Visible = false; + this.lblRegisterTitle.Text = Localization.GetString("CreateTitle", this.LocalResourceFile); + this.cmdCreateUser.Text = Localization.GetString("cmdCreate", this.LocalResourceFile); } + else + { + this.lblRegisterHelp.Text += Localization.GetString("Required", Localization.SharedResourceFile); + this.lblRegisterTitle.Text = Localization.GetString("RegisterTitle", this.LocalResourceFile); + this.cmdCreateUser.Text = Localization.GetString("cmdRegister", this.LocalResourceFile); + this.ctlUser.ShowPassword = false; + this.ctlUser.ShowUpdate = false; + this.ctlUser.User = this.User; + this.ctlUser.DataBind(); + } + } - this.UserId = objUser.UserID; + private void DisplayLoginControl(AuthenticationLoginBase authLoginControl, bool addHeader, bool addFooter) + { + // Create a
    to hold the control + var container = new HtmlGenericControl { TagName = "div", ID = authLoginControl.AuthenticationType, ViewStateMode = ViewStateMode.Disabled }; - // Check if the User has valid Password/Profile - switch (validStatus) - { - case UserValidStatus.VALID: - // check if the user is an admin/host and validate their IP - if (Host.EnableIPChecking) - { - bool isAdminUser = objUser.IsSuperUser || objUser.IsInRole(this.PortalSettings.AdministratorRoleName); - if (isAdminUser) - { - var clientIp = NetworkUtils.GetClientIpAddress(this.Request); - if (IPFilterController.Instance.IsIPBanned(clientIp)) - { - PortalSecurity.Instance.SignOut(); - this.AddModuleMessage("IPAddressBanned", ModuleMessage.ModuleMessageType.RedError, true); - okToShowPanel = false; - break; - } - } - } + // Add Settings Control to Container + container.Controls.Add(authLoginControl); - // Set the Page Culture(Language) based on the Users Preferred Locale - if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null) && this.LocaleEnabled(objUser.Profile.PreferredLocale)) - { - Localization.SetLanguage(objUser.Profile.PreferredLocale); - } - else - { - Localization.SetLanguage(this.PortalSettings.DefaultLanguage); - } + // Add a Section Header + SectionHeadControl sectionHeadControl; + if (addHeader) + { + sectionHeadControl = (SectionHeadControl)this.LoadControl("~/controls/SectionHeadControl.ascx"); + sectionHeadControl.IncludeRule = true; + sectionHeadControl.CssClass = "Head"; + sectionHeadControl.Text = Localization.GetString("Title", authLoginControl.LocalResourceFile); - // Set the Authentication Type used - AuthenticationController.SetAuthenticationType(this.AuthenticationType); + sectionHeadControl.Section = container.ID; - // Complete Login - var userRequestIpAddressController = UserRequestIPAddressController.Instance; - var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); - UserController.UserLogin(this.PortalId, objUser, this.PortalSettings.PortalName, ipAddress, this.RememberMe); + // Add Section Head Control to Container + this.pnlLoginContainer.Controls.Add(sectionHeadControl); + } - // check whether user request comes with IPv6 and log it to make sure admin is aware of that - if (string.IsNullOrWhiteSpace(ipAddress)) - { - var ipAddressV6 = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request), IPAddressFamily.IPv6); + // Add Container to Controls + this.pnlLoginContainer.Controls.Add(container); - if (!string.IsNullOrWhiteSpace(ipAddressV6)) - { - this.AddEventLog(objUser.UserID, objUser.Username, this.PortalId, "IPv6", ipAddressV6); - } - } + // Add LineBreak + if (addFooter) + { + this.pnlLoginContainer.Controls.Add(new LiteralControl("
    ")); + } - // redirect browser - var redirectUrl = this.RedirectURL; + // Display the container + this.pnlLoginContainer.Visible = true; + } - // Clear the cookie - HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", string.Empty) - { - Expires = DateTime.Now.AddDays(-1), - Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", - }); + private void DisplayTabbedLoginControl(AuthenticationLoginBase authLoginControl, TabStripTabCollection Tabs) + { + var tab = new DNNTab(Localization.GetString("Title", authLoginControl.LocalResourceFile)) { ID = authLoginControl.AuthenticationType }; - this.Response.Redirect(redirectUrl, true); - break; - case UserValidStatus.PASSWORDEXPIRED: - strMessage = string.Format(Localization.GetString("PasswordExpired", this.LocalResourceFile), expiryDate.ToLongDateString()); - this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); - this.PageNo = 2; - this.pnlProceed.Visible = false; - break; - case UserValidStatus.PASSWORDEXPIRING: - strMessage = string.Format(Localization.GetString("PasswordExpiring", this.LocalResourceFile), expiryDate.ToLongDateString()); - this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); - this.PageNo = 2; - this.pnlProceed.Visible = true; - break; - case UserValidStatus.UPDATEPASSWORD: - var portalAlias = Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias); - if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) - { - UserController.ResetPasswordToken(this.User); - objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); - } + tab.Controls.Add(authLoginControl); + Tabs.Add(tab); - var redirTo = string.Format("{0}/default.aspx?ctl=PasswordReset&resetToken={1}&forced=true", portalAlias, objUser.PasswordResetToken); - this.Response.Redirect(redirTo); - break; - case UserValidStatus.UPDATEPROFILE: - // Save UserID in ViewState so that can update profile later. - this.UserId = objUser.UserID; + this.tsLogin.Visible = true; + } - // When the user need update its profile to complete login, we need clear the login status because if the logrin is from - // 3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation. - PortalSecurity.Instance.SignOut(); + private void InitialiseUser() + { + // Load any Profile properties that may have been returned + this.UpdateProfile(this.User, false); - // Admin has forced profile update - this.AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true); - this.PageNo = 3; - break; - case UserValidStatus.MUSTAGREETOTERMS: - if (this.PortalSettings.DataConsentConsentRedirect == -1) - { - this.UserId = objUser.UserID; - this.AddModuleMessage("MustConsent", ModuleMessage.ModuleMessageType.YellowWarning, true); - this.PageNo = 4; - } - else - { - // Use the reset password token to identify the user during the redirect - UserController.ResetPasswordToken(objUser); - objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); - this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.DataConsentConsentRedirect, string.Empty, string.Format("token={0}", objUser.PasswordResetToken))); - } + // Set UserName to authentication Token + this.User.Username = this.GenerateUserName(); - break; + // Set DisplayName to UserToken if null + if (string.IsNullOrEmpty(this.User.DisplayName)) + { + this.User.DisplayName = this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); } - if (okToShowPanel) + // Parse DisplayName into FirstName/LastName + if (this.User.DisplayName.IndexOf(' ') > 0) { - this.ShowPanel(); + this.User.FirstName = this.User.DisplayName.Substring(0, this.User.DisplayName.IndexOf(' ')); + this.User.LastName = this.User.DisplayName.Substring(this.User.DisplayName.IndexOf(' ') + 1); } - } - private bool UserNeedsVerification() - { - var userInfo = UserController.Instance.GetCurrentUserInfo(); + // Set FirstName to Authentication Type (if null) + if (string.IsNullOrEmpty(this.User.FirstName)) + { + this.User.FirstName = this.AuthenticationType; + } - return !userInfo.IsSuperUser && userInfo.IsInRole("Unverified Users") && - this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration && - !string.IsNullOrEmpty(this.Request.QueryString["verificationcode"]); + // Set FirstName to "User" (if null) + if (string.IsNullOrEmpty(this.User.LastName)) + { + this.User.LastName = "User"; + } } - private bool LocaleEnabled(string locale) + private string GenerateUserName() { - return LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).ContainsKey(locale); - } + if (!string.IsNullOrEmpty(this.UserName)) + { + return this.UserName; + } - /// - /// cmdAssociate_Click runs when the associate button is clicked. - /// - /// - /// - protected void cmdAssociate_Click(object sender, EventArgs e) - { - if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || (!this.UseCaptcha)) + // Try Email prefix + var emailPrefix = string.Empty; + if (!string.IsNullOrEmpty(this.User.Email)) { - UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE; - var userRequestIpAddressController = UserRequestIPAddressController.Instance; - var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); - UserInfo objUser = UserController.ValidateUser( - this.PortalId, - this.txtUsername.Text, - this.txtPassword.Text, - "DNN", - string.Empty, - this.PortalSettings.PortalName, - ipAddress, - ref loginStatus); - if (loginStatus == UserLoginStatus.LOGIN_SUCCESS) + if (this.User.Email.IndexOf("@", StringComparison.Ordinal) != -1) { - // Assocate alternate Login with User and proceed with Login - AuthenticationController.AddUserAuthentication(objUser.UserID, this.AuthenticationType, this.UserToken); - if (objUser != null) + emailPrefix = this.User.Email.Substring(0, this.User.Email.IndexOf("@", StringComparison.Ordinal)); + var user = UserController.GetUserByName(this.PortalId, emailPrefix); + if (user == null) { - this.UpdateProfile(objUser, true); + return emailPrefix; } - - this.ValidateUser(objUser, true); } - else + } + + // Try First Name + if (!string.IsNullOrEmpty(this.User.FirstName)) + { + var user = UserController.GetUserByName(this.PortalId, this.User.FirstName); + if (user == null) { - this.AddModuleMessage("AssociationFailed", ModuleMessage.ModuleMessageType.RedError, true); + return this.User.FirstName; } } - } - /// - /// cmdCreateUser runs when the register (as new user) button is clicked. - /// - /// - /// - protected void cmdCreateUser_Click(object sender, EventArgs e) - { - this.User.Membership.Password = UserController.GeneratePassword(); + // Try Last Name + if (!string.IsNullOrEmpty(this.User.LastName)) + { + var user = UserController.GetUserByName(this.PortalId, this.User.LastName); + if (user == null) + { + return this.User.LastName; + } + } - if (this.AutoRegister) + // Try First Name + space + First letter last name + if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) { - this.ctlUser.User = this.User; + var newUserName = this.User.FirstName + " " + this.User.LastName.Substring(0, 1); + var user = UserController.GetUserByName(this.PortalId, newUserName); + if (user == null) + { + return newUserName; + } + } - // Call the Create User method of the User control so that it can create - // the user and raise the appropriate event(s) - this.ctlUser.CreateUser(); + // Try First letter of First Name + lastname + if (!string.IsNullOrEmpty(this.User.LastName) && !string.IsNullOrEmpty(this.User.FirstName)) + { + var newUserName = this.User.FirstName.Substring(0, 1) + this.User.LastName; + var user = UserController.GetUserByName(this.PortalId, newUserName); + if (user == null) + { + return newUserName; + } } - else + + // Try Email Prefix + incremental numbers until unique name found + if (!string.IsNullOrEmpty(emailPrefix)) { - if (this.ctlUser.IsValid) + for (var i = 1; i < 10000; i++) { - // Call the Create User method of the User control so that it can create - // the user and raise the appropriate event(s) - this.ctlUser.CreateUser(); + var newUserName = emailPrefix + i; + var user = UserController.GetUserByName(this.PortalId, newUserName); + if (user == null) + { + return newUserName; + } } } - } - /// - /// cmdProceed_Click runs when the Proceed Anyway button is clicked. - /// - /// - /// - protected void cmdProceed_Click(object sender, EventArgs e) - { - var user = this.ctlPassword.User; - this.ValidateUser(user, true); + return this.UserToken.Replace("http://", string.Empty).TrimEnd('/'); } + /// ----------------------------------------------------------------------------- /// - /// PasswordUpdated runs when the password is updated. + /// ShowPanel controls what "panel" is to be displayed. /// - /// - /// - protected void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) + /// ----------------------------------------------------------------------------- + private void ShowPanel() { - PasswordUpdateStatus status = e.UpdateStatus; - if (status == PasswordUpdateStatus.Success) + bool showLogin = this.PageNo == 0; + bool showRegister = this.PageNo == 1; + bool showPassword = this.PageNo == 2; + bool showProfile = this.PageNo == 3; + bool showDataConsent = this.PageNo == 4; + this.pnlProfile.Visible = showProfile; + this.pnlPassword.Visible = showPassword; + this.pnlLogin.Visible = showLogin; + this.pnlRegister.Visible = showRegister; + this.pnlAssociate.Visible = showRegister; + this.pnlDataConsent.Visible = showDataConsent; + switch (this.PageNo) { - this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); - var user = this.ctlPassword.User; - user.Membership.LastPasswordChangeDate = DateTime.Now; - user.Membership.UpdatePassword = false; - this.LoginStatus = user.IsSuperUser ? UserLoginStatus.LOGIN_SUPERUSER : UserLoginStatus.LOGIN_SUCCESS; - UserLoginStatus userstatus = UserLoginStatus.LOGIN_FAILURE; - UserController.CheckInsecurePassword(user.Username, user.Membership.Password, ref userstatus); - this.LoginStatus = userstatus; - this.ValidateUser(user, true); + case 0: + this.BindLogin(); + break; + case 1: + this.BindRegister(); + break; + case 2: + this.ctlPassword.UserId = this.UserId; + this.ctlPassword.DataBind(); + break; + case 3: + this.ctlProfile.UserId = this.UserId; + this.ctlProfile.DataBind(); + break; + case 4: + this.ctlDataConsent.UserId = this.UserId; + this.ctlDataConsent.DataBind(); + break; } - else + + if (showProfile && UrlUtils.InPopUp()) { - this.AddModuleMessage(status.ToString(), ModuleMessage.ModuleMessageType.RedError, true); + ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "ResizePopup", "if(parent.$('#iPopUp').length > 0 && parent.$('#iPopUp').dialog('isOpen')){parent.$('#iPopUp').dialog({width: 950, height: 550}).dialog({position: 'center'});};", true); } } - /// - /// DataConsentCompleted runs after the user has gone through the data consent screen. - /// - /// - /// - protected void DataConsentCompleted(object sender, DataConsent.DataConsentEventArgs e) + private void UpdateProfile(UserInfo objUser, bool update) { - switch (e.Status) + bool bUpdateUser = false; + if (this.ProfileProperties.Count > 0) { - case DataConsent.DataConsentStatus.Consented: - this.ValidateUser(this.ctlDataConsent.User, true); - break; - case DataConsent.DataConsentStatus.Cancelled: - case DataConsent.DataConsentStatus.RemovedAccount: - this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId), true); - break; - case DataConsent.DataConsentStatus.FailedToRemoveAccount: - this.AddModuleMessage("FailedToRemoveAccount", ModuleMessage.ModuleMessageType.RedError, true); - break; + foreach (string key in this.ProfileProperties) + { + switch (key) + { + case "FirstName": + if (objUser.FirstName != this.ProfileProperties[key]) + { + objUser.FirstName = this.ProfileProperties[key]; + bUpdateUser = true; + } + + break; + case "LastName": + if (objUser.LastName != this.ProfileProperties[key]) + { + objUser.LastName = this.ProfileProperties[key]; + bUpdateUser = true; + } + + break; + case "Email": + if (objUser.Email != this.ProfileProperties[key]) + { + objUser.Email = this.ProfileProperties[key]; + bUpdateUser = true; + } + + break; + case "DisplayName": + if (objUser.DisplayName != this.ProfileProperties[key]) + { + objUser.DisplayName = this.ProfileProperties[key]; + bUpdateUser = true; + } + + break; + default: + objUser.Profile.SetProfileProperty(key, this.ProfileProperties[key]); + break; + } + } + + if (update) + { + if (bUpdateUser) + { + UserController.UpdateUser(this.PortalId, objUser); + } + + ProfileController.UpdateUserProfile(objUser); + } } } + /// ----------------------------------------------------------------------------- /// - /// ProfileUpdated runs when the profile is updated. + /// ValidateUser runs when the user has been authorized by the data store. It validates for + /// things such as an expiring password, valid profile, or missing DNN User Association. /// - protected void ProfileUpdated(object sender, EventArgs e) + /// The logged in User. + /// Ignore the situation where the password is expiring (but not yet expired). + /// ----------------------------------------------------------------------------- + private void ValidateUser(UserInfo objUser, bool ignoreExpiring) { - // Authorize User - this.ValidateUser(this.ctlProfile.User, true); - } + UserValidStatus validStatus = UserValidStatus.VALID; + string strMessage = Null.NullString; + DateTime expiryDate = Null.NullDate; + bool okToShowPanel = true; - /// - /// UserAuthenticated runs when the user is authenticated by one of the child - /// Authentication controls. - /// - protected void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) - { - this.LoginStatus = e.LoginStatus; + validStatus = UserController.ValidateUser(objUser, this.PortalId, ignoreExpiring); - // Check the Login Status - switch (this.LoginStatus) + if (PasswordConfig.PasswordExpiry > 0) { - case UserLoginStatus.LOGIN_USERNOTAPPROVED: - switch (e.Message) + expiryDate = objUser.Membership.LastPasswordChangeDate.AddDays(PasswordConfig.PasswordExpiry); + } + + this.UserId = objUser.UserID; + + // Check if the User has valid Password/Profile + switch (validStatus) + { + case UserValidStatus.VALID: + // check if the user is an admin/host and validate their IP + if (Host.EnableIPChecking) { - case "UnverifiedUser": - if (e.User != null) + bool isAdminUser = objUser.IsSuperUser || objUser.IsInRole(this.PortalSettings.AdministratorRoleName); + if (isAdminUser) + { + var clientIp = NetworkUtils.GetClientIpAddress(this.Request); + if (IPFilterController.Instance.IsIPBanned(clientIp)) { - // First update the profile (if any properties have been passed) - this.AuthenticationType = e.AuthenticationType; - this.ProfileProperties = e.Profile; - this.RememberMe = e.RememberMe; - this.UpdateProfile(e.User, true); - this.ValidateUser(e.User, false); + PortalSecurity.Instance.SignOut(); + this.AddModuleMessage("IPAddressBanned", ModuleMessage.ModuleMessageType.RedError, true); + okToShowPanel = false; + break; } - - break; - case "EnterCode": - this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.YellowWarning, true); - break; - case "InvalidCode": - case "UserNotAuthorized": - this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); - break; - default: - this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); - break; + } } - break; - case UserLoginStatus.LOGIN_USERLOCKEDOUT: - if (Host.AutoAccountUnlockDuration > 0) + // Set the Page Culture(Language) based on the Users Preferred Locale + if ((objUser.Profile != null) && (objUser.Profile.PreferredLocale != null) && this.LocaleEnabled(objUser.Profile.PreferredLocale)) { - this.AddLocalizedModuleMessage(string.Format(Localization.GetString("UserLockedOut", this.LocalResourceFile), Host.AutoAccountUnlockDuration), ModuleMessage.ModuleMessageType.RedError, true); + Localization.SetLanguage(objUser.Profile.PreferredLocale); } else { - this.AddLocalizedModuleMessage(Localization.GetString("UserLockedOut_ContactAdmin", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError, true); + Localization.SetLanguage(this.PortalSettings.DefaultLanguage); } - // notify administrator about account lockout ( possible hack attempt ) - var Custom = new ArrayList { e.UserToken }; + // Set the Authentication Type used + AuthenticationController.SetAuthenticationType(this.AuthenticationType); - var message = new Message - { - FromUserID = this.PortalSettings.AdministratorId, - ToUserID = this.PortalSettings.AdministratorId, - Subject = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_SUBJECT", Localization.GlobalResourceFile, Custom), - Body = Localization.GetSystemMessage(this.PortalSettings, "EMAIL_USER_LOCKOUT_BODY", Localization.GlobalResourceFile, Custom), - Status = MessageStatusType.Unread, - }; + // Complete Login + var userRequestIpAddressController = UserRequestIPAddressController.Instance; + var ipAddress = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request)); + UserController.UserLogin(this.PortalId, objUser, this.PortalSettings.PortalName, ipAddress, this.RememberMe); - // _messagingController.SaveMessage(_message); - Mail.SendEmail(this.PortalSettings.Email, this.PortalSettings.Email, message.Subject, message.Body); - break; - case UserLoginStatus.LOGIN_FAILURE: - // A Login Failure can mean one of two things: - // 1 - User was authenticated by the Authentication System but is not "affiliated" with a DNN Account - // 2 - User was not authenticated - if (e.Authenticated) + // check whether user request comes with IPv6 and log it to make sure admin is aware of that + if (string.IsNullOrWhiteSpace(ipAddress)) { - this.AutoRegister = e.AutoRegister; - this.AuthenticationType = e.AuthenticationType; - this.ProfileProperties = e.Profile; - this.UserToken = e.UserToken; - this.UserName = e.UserName; - if (this.AutoRegister) - { - this.InitialiseUser(); - this.User.Membership.Password = UserController.GeneratePassword(); - - this.ctlUser.User = this.User; + var ipAddressV6 = userRequestIpAddressController.GetUserRequestIPAddress(new HttpRequestWrapper(this.Request), IPAddressFamily.IPv6); - // Call the Create User method of the User control so that it can create - // the user and raise the appropriate event(s) - this.ctlUser.CreateUser(); - } - else + if (!string.IsNullOrWhiteSpace(ipAddressV6)) { - this.PageNo = 1; - this.ShowPanel(); + this.AddEventLog(objUser.UserID, objUser.Username, this.PortalId, "IPv6", ipAddressV6); } } - else + + // redirect browser + var redirectUrl = this.RedirectURL; + + // Clear the cookie + HttpContext.Current.Response.Cookies.Set(new HttpCookie("returnurl", string.Empty) { - if (string.IsNullOrEmpty(e.Message)) - { - this.AddModuleMessage("LoginFailed", ModuleMessage.ModuleMessageType.RedError, true); - } - else - { - this.AddLocalizedModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); - } - } + Expires = DateTime.Now.AddDays(-1), + Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", + }); + this.Response.Redirect(redirectUrl, true); break; - default: - if (e.User != null) + case UserValidStatus.PASSWORDEXPIRED: + strMessage = string.Format(Localization.GetString("PasswordExpired", this.LocalResourceFile), expiryDate.ToLongDateString()); + this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 2; + this.pnlProceed.Visible = false; + break; + case UserValidStatus.PASSWORDEXPIRING: + strMessage = string.Format(Localization.GetString("PasswordExpiring", this.LocalResourceFile), expiryDate.ToLongDateString()); + this.AddLocalizedModuleMessage(strMessage, ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 2; + this.pnlProceed.Visible = true; + break; + case UserValidStatus.UPDATEPASSWORD: + var portalAlias = Globals.AddHTTP(this.PortalSettings.PortalAlias.HTTPAlias); + if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { - // First update the profile (if any properties have been passed) - this.AuthenticationType = e.AuthenticationType; - this.ProfileProperties = e.Profile; - this.RememberMe = e.RememberMe; - this.UpdateProfile(e.User, true); - this.ValidateUser(e.User, e.AuthenticationType != "DNN"); + UserController.ResetPasswordToken(this.User); + objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); } + var redirTo = string.Format("{0}/default.aspx?ctl=PasswordReset&resetToken={1}&forced=true", portalAlias, objUser.PasswordResetToken); + this.Response.Redirect(redirTo); break; - } - } + case UserValidStatus.UPDATEPROFILE: + // Save UserID in ViewState so that can update profile later. + this.UserId = objUser.UserID; - /// - /// UserCreateCompleted runs when a new user has been Created. - /// - /// - /// - protected void UserCreateCompleted(object sender, UserUserControlBase.UserCreatedEventArgs e) - { - var strMessage = string.Empty; - try - { - if (e.CreateStatus == UserCreateStatus.Success) - { - // Assocate alternate Login with User and proceed with Login - AuthenticationController.AddUserAuthentication(e.NewUser.UserID, this.AuthenticationType, this.UserToken); + // When the user need update its profile to complete login, we need clear the login status because if the logrin is from + // 3rd party login provider, it may call UserController.UserLogin because they doesn't check this situation. + PortalSecurity.Instance.SignOut(); - strMessage = this.CompleteUserCreation(e.CreateStatus, e.NewUser, e.Notify, true); - if (string.IsNullOrEmpty(strMessage)) + // Admin has forced profile update + this.AddModuleMessage("ProfileUpdate", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 3; + break; + case UserValidStatus.MUSTAGREETOTERMS: + if (this.PortalSettings.DataConsentConsentRedirect == -1) { - // First update the profile (if any properties have been passed) - this.UpdateProfile(e.NewUser, true); - - this.ValidateUser(e.NewUser, true); + this.UserId = objUser.UserID; + this.AddModuleMessage("MustConsent", ModuleMessage.ModuleMessageType.YellowWarning, true); + this.PageNo = 4; } - } - else - { - this.AddLocalizedModuleMessage(UserController.GetUserCreateStatus(e.CreateStatus), ModuleMessage.ModuleMessageType.RedError, true); - } + else + { + // Use the reset password token to identify the user during the redirect + UserController.ResetPasswordToken(objUser); + objUser = UserController.GetUserById(objUser.PortalID, objUser.UserID); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.DataConsentConsentRedirect, string.Empty, string.Format("token={0}", objUser.PasswordResetToken))); + } + + break; } - catch (Exception exc) // Module failed to load + + if (okToShowPanel) { - Exceptions.ProcessModuleLoadException(this, exc); + this.ShowPanel(); } } + private bool UserNeedsVerification() + { + var userInfo = UserController.Instance.GetCurrentUserInfo(); + + return !userInfo.IsSuperUser && userInfo.IsInRole("Unverified Users") && + this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration && + !string.IsNullOrEmpty(this.Request.QueryString["verificationcode"]); + } + + private bool LocaleEnabled(string locale) + { + return LocaleController.Instance.GetLocales(this.PortalSettings.PortalId).ContainsKey(locale); + } + private void AddEventLog(int userId, string username, int portalId, string propertyName, string propertyValue) { var log = new LogInfo diff --git a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs index 2f789068b47..b0759f59bc1 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Authentication/Logoff.ascx.cs @@ -20,7 +20,7 @@ namespace DotNetNuke.Modules.Admin.Authentication /// /// public partial class Logoff : UserModuleBase - { + { /// /// Page_Load runs when the control is loaded. /// @@ -73,7 +73,12 @@ protected void UserLogOff(object sender, EventArgs e) { this.DoLogoff(); } - + + protected void UserRedirect(object sender, EventArgs e) + { + this.Redirect(); + } + private void Redirect() { // Redirect browser back to portal @@ -89,7 +94,7 @@ private void DoLogoff() { DataCache.ClearUserCache(this.PortalSettings.PortalId, this.Context.User.Identity.Name); } - + var objPortalSecurity = PortalSecurity.Instance; objPortalSecurity.SignOut(); } @@ -97,11 +102,6 @@ private void DoLogoff() { Exceptions.ProcessPageLoadException(exc); } - } - - protected void UserRedirect(object sender, EventArgs e) - { - this.Redirect(); - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/AuthenticationEditor.ascx.cs index e71ab60b7d8..1b6dbfc8951 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; + private AuthenticationSettingsBase _SettingsControl; public AuthenticationEditor() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); - } - + } + protected AuthenticationInfo AuthSystem { get @@ -40,7 +40,7 @@ protected AuthenticationInfo AuthSystem { this._AuthSystem = AuthenticationController.GetAuthenticationServiceByPackageID(this.PackageID); } - + return this._AuthSystem; } } @@ -61,11 +61,11 @@ protected AuthenticationSettingsBase SettingsControl { this._SettingsControl = (AuthenticationSettingsBase)this.LoadControl("~/" + this.AuthSystem.SettingsControlSrc); } - + return this._SettingsControl; } - } - + } + public override void Initialize() { this.pnlSettings.Visible = !this.IsSuperTab; @@ -84,7 +84,7 @@ public override void Initialize() this.lblHelp.Text = Localization.GetString("AdminHelp", this.LocalResourceFile); } } - + this.BindAuthentication(); } @@ -98,8 +98,30 @@ public override void UpdatePackage() AuthenticationController.UpdateAuthentication(authInfo); } } - } - + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cmdUpdate.Click += this.cmdUpdate_Click; + var displayMode = this.DisplayMode; + if (displayMode == "editor" || displayMode == "settings") + { + this.AuthEditorHead.Visible = this.AuthEditorHead.EnableViewState = false; + } + } + + protected void cmdUpdate_Click(object sender, EventArgs e) + { + this.SettingsControl?.UpdateSettings(); + + var displayMode = this.DisplayMode; + if (displayMode != "editor" && displayMode != "settings") + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + } + /// ----------------------------------------------------------------------------- /// /// This routine Binds the Authentication System. @@ -119,10 +141,10 @@ private void BindAuthentication() this.authenticationForm.DataSource = this.AuthSystem; this.authenticationForm.DataBind(); } - + this.authenticationFormReadOnly.Visible = this.IsSuperTab && (this.AuthSystem.AuthenticationType == "DNN"); this.authenticationForm.Visible = this.IsSuperTab && this.AuthSystem.AuthenticationType != "DNN"; - + if (this.SettingsControl != null) { // set the control ID to the resource file name ( ie. controlname.ascx = controlname ) @@ -137,28 +159,6 @@ private void BindAuthentication() this.cmdUpdate.Visible = false; } } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this.cmdUpdate.Click += this.cmdUpdate_Click; - var displayMode = this.DisplayMode; - if (displayMode == "editor" || displayMode == "settings") - { - this.AuthEditorHead.Visible = this.AuthEditorHead.EnableViewState = false; - } } - - protected void cmdUpdate_Click(object sender, EventArgs e) - { - this.SettingsControl?.UpdateSettings(); - - var displayMode = this.DisplayMode; - if (displayMode != "editor" && displayMode != "settings") - { - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs index b0201888cd4..81d55736b91 100644 --- a/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/EditExtension/EditExtension.ascx.cs @@ -72,12 +72,6 @@ protected bool 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 @@ -122,6 +116,12 @@ protected PropertyEditorMode ViewMode } } + protected string ReturnUrl + { + get { return (string)this.ViewState["ReturnUrl"]; } + set { this.ViewState["ReturnUrl"] = value; } + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -181,6 +181,41 @@ protected override void OnLoad(EventArgs e) } } + protected void OnCancelClick(object sender, EventArgs e) + { + this.Response.Redirect(this.ReturnUrl); + } + + protected void OnDeleteClick(object sender, EventArgs e) + { + this.Response.Redirect(Util.UnInstallURL(this.ModuleContext.TabId, this.PackageID)); + } + + protected void OnPackageClick(object sender, EventArgs e) + { + try + { + this.UpdatePackage(false); + this.Response.Redirect(Util.PackageWriterURL(this.ModuleContext, this.PackageID)); + } + catch (Exception ex) + { + Exceptions.ProcessModuleLoadException(this, ex); + } + } + + protected void OnUpdateClick(object sender, EventArgs e) + { + try + { + this.UpdatePackage(true); + } + catch (Exception ex) + { + Exceptions.ProcessModuleLoadException(this, ex); + } + } + private void BindData() { this.email.ValidationExpression = Globals.glbEmailRegEx; @@ -292,40 +327,5 @@ private void UpdatePackage(bool displayMessage) this.PackageEditor.UpdatePackage(); } } - - protected void OnCancelClick(object sender, EventArgs e) - { - this.Response.Redirect(this.ReturnUrl); - } - - protected void OnDeleteClick(object sender, EventArgs e) - { - this.Response.Redirect(Util.UnInstallURL(this.ModuleContext.TabId, this.PackageID)); - } - - protected void OnPackageClick(object sender, EventArgs e) - { - try - { - this.UpdatePackage(false); - this.Response.Redirect(Util.PackageWriterURL(this.ModuleContext, this.PackageID)); - } - catch (Exception ex) - { - Exceptions.ProcessModuleLoadException(this, ex); - } - } - - protected void OnUpdateClick(object sender, EventArgs e) - { - try - { - this.UpdatePackage(true); - } - catch (Exception ex) - { - Exceptions.ProcessModuleLoadException(this, ex); - } - } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs index 7de9f309c44..e9ff4c08082 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/ResultsSettings.ascx.cs @@ -19,7 +19,7 @@ namespace DotNetNuke.Modules.SearchResults using DotNetNuke.Services.Search.Internals; public partial class ResultsSettings : ModuleSettingsBase - { + { public override void LoadSettings() { try @@ -64,7 +64,7 @@ public override void LoadSettings() this.divPortalGroup.Visible = false; } } - + if (!string.IsNullOrEmpty(Convert.ToString(this.Settings["ScopeForFilters"]))) { var list = Convert.ToString(this.Settings["ScopeForFilters"]).Split('|').ToList(); @@ -146,7 +146,7 @@ public override void UpdateSettings() { maxDescriptionLength = "100"; } - + ModuleController.Instance.UpdateModuleSetting(this.ModuleId, "MaxDescriptionLength", maxDescriptionLength); } } @@ -156,15 +156,15 @@ public override void UpdateSettings() } DataCache.RemoveCache(string.Format("ModuleInfos{0}", this.PortalSettings.PortalId)); - } - + } + 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) + into portals + where portals.Any(x => x.PortalID == PortalSettings.Current.PortalId) select portals.ToArray()).FirstOrDefault(); var result = new List(); @@ -198,7 +198,7 @@ protected IEnumerable LoadSeachContentSourcesList() } } } - + return result; } diff --git a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs index b85dc05f0c0..b848853cd19 100644 --- a/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/SearchResults/SearchResults.ascx.cs @@ -210,31 +210,6 @@ 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)); } @@ -335,6 +310,31 @@ protected string CurrentPageIndexText protected string CultureCode { get; set; } + 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 override void OnLoad(EventArgs e) { base.OnLoad(e); diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs index 0f973ea6d68..b8e385459f4 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/DataConsent.ascx.cs @@ -15,7 +15,7 @@ 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 @@ -24,8 +24,8 @@ public enum DataConsentStatus Cancelled, RemovedAccount, FailedToRemoveAccount, - } - + } + public string DeleteMeConfirmString { get @@ -39,16 +39,16 @@ public string DeleteMeConfirmString case PortalSettings.UserDeleteAction.HardDelete: return this.LocalizeString("HardDelete.Confirm"); } - + return string.Empty; } - } - + } + public void OnDataConsentComplete(DataConsentEventArgs e) { this.DataConsentCompleted?.Invoke(this, e); - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -62,11 +62,11 @@ protected override void OnLoad(EventArgs e) this.cmdSubmit.Enabled = false; this.pnlNoAgreement.Visible = false; } - + this.chkAgree.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled = !this.checked;", this.cmdSubmit.ClientID)); this.cmdDeleteMe.Attributes.Add("onclick", string.Format("if (!confirm('{0}')) this.preventDefault();", this.DeleteMeConfirmString)); } - + private void cmdCancel_Click(object sender, EventArgs e) { this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.Cancelled)); @@ -102,7 +102,7 @@ private void cmdDeleteMe_Click(object sender, EventArgs e) success = UserController.RemoveUser(this.User); break; } - + if (success) { PortalSecurity.Instance.SignOut(); @@ -112,17 +112,17 @@ private void cmdDeleteMe_Click(object sender, EventArgs e) { this.OnDataConsentComplete(new DataConsentEventArgs(DataConsentStatus.FailedToRemoveAccount)); } - } - + } + /// ----------------------------------------------------------------------------- /// /// The DataConsentEventArgs class provides a customised EventArgs class for /// the DataConsent Event. /// public class DataConsentEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new DataConsentEventArgs. /// diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs index fb9f9f69f58..db0611a5a43 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/EditUser.ascx.cs @@ -242,6 +242,106 @@ protected override void OnLoad(EventArgs e) } } + protected void cmdDelete_Click(object sender, EventArgs e) + { + UserInfo user = this.User; + var success = false; + if (this.PortalSettings.DataConsentActive && user.UserID == this.UserInfo.UserID) + { + switch (this.PortalSettings.DataConsentUserDeleteAction) + { + case PortalSettings.UserDeleteAction.Manual: + user.Membership.Approved = false; + UserController.UpdateUser(this.PortalSettings.PortalId, user); + UserController.UserRequestsRemoval(user, true); + success = true; + break; + case PortalSettings.UserDeleteAction.DelayedHardDelete: + success = UserController.DeleteUser(ref user, true, false); + UserController.UserRequestsRemoval(user, true); + break; + case PortalSettings.UserDeleteAction.HardDelete: + success = UserController.RemoveUser(user); + break; + default: // if user delete is switched off under Data Consent then we revert to the old behavior + success = UserController.DeleteUser(ref user, true, false); + break; + } + } + else + { + success = UserController.DeleteUser(ref user, true, false); + } + + if (!success) + { + this.AddModuleMessage("UserDeleteError", ModuleMessage.ModuleMessageType.RedError, true); + } + + // DNN-26777 + PortalSecurity.Instance.SignOut(); + this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)); + } + + protected void cmdUpdate_Click(object sender, EventArgs e) + { + if (this.userForm.IsValid && (this.User != null)) + { + if (this.User.UserID == this.PortalSettings.AdministratorId) + { + // Clear the Portal Cache + DataCache.ClearPortalCache(this.UserPortalID, true); + } + + try + { + // Update DisplayName to conform to Format + this.UpdateDisplayName(); + + // DNN-5874 Check if unique display name is required + if (this.PortalSettings.Registration.RequireUniqueDisplayName) + { + var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName); + if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID)) + { + throw new Exception("Display Name must be unique"); + } + } + + UserController.UpdateUser(this.UserPortalID, this.User); + + // make sure username matches possibly changed email address + if (this.PortalSettings.Registration.UseEmailAsUserName) + { + if (this.User.Username.ToLower() != this.User.Email.ToLower()) + { + UserController.ChangeUsername(this.User.UserID, this.User.Email); + + // after username changed, should redirect to login page to let user authenticate again. + var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(this.Request.RawUrl), false); + var spliter = loginUrl.Contains("?") ? "&" : "?"; + loginUrl = $"{loginUrl}{spliter}username={this.User.Email}&usernameChanged=true"; + this.Response.Redirect(loginUrl, true); + } + } + + this.Response.Redirect(this.Request.RawUrl); + } + catch (Exception exc) + { + Logger.Error(exc); + if (exc.Message == "Display Name must be unique") + { + this.AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); + } + else + { + this.AddModuleMessage("UserUpdatedError", ModuleMessage.ModuleMessageType.RedError, true); + } + } + } + } + private void BindData() { if (this.User != null) @@ -420,106 +520,6 @@ private void UpdateDisplayName() } } - protected void cmdDelete_Click(object sender, EventArgs e) - { - UserInfo user = this.User; - var success = false; - if (this.PortalSettings.DataConsentActive && user.UserID == this.UserInfo.UserID) - { - switch (this.PortalSettings.DataConsentUserDeleteAction) - { - case PortalSettings.UserDeleteAction.Manual: - user.Membership.Approved = false; - UserController.UpdateUser(this.PortalSettings.PortalId, user); - UserController.UserRequestsRemoval(user, true); - success = true; - break; - case PortalSettings.UserDeleteAction.DelayedHardDelete: - success = UserController.DeleteUser(ref user, true, false); - UserController.UserRequestsRemoval(user, true); - break; - case PortalSettings.UserDeleteAction.HardDelete: - success = UserController.RemoveUser(user); - break; - default: // if user delete is switched off under Data Consent then we revert to the old behavior - success = UserController.DeleteUser(ref user, true, false); - break; - } - } - else - { - success = UserController.DeleteUser(ref user, true, false); - } - - if (!success) - { - this.AddModuleMessage("UserDeleteError", ModuleMessage.ModuleMessageType.RedError, true); - } - - // DNN-26777 - PortalSecurity.Instance.SignOut(); - this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId)); - } - - protected void cmdUpdate_Click(object sender, EventArgs e) - { - if (this.userForm.IsValid && (this.User != null)) - { - if (this.User.UserID == this.PortalSettings.AdministratorId) - { - // Clear the Portal Cache - DataCache.ClearPortalCache(this.UserPortalID, true); - } - - try - { - // Update DisplayName to conform to Format - this.UpdateDisplayName(); - - // DNN-5874 Check if unique display name is required - if (this.PortalSettings.Registration.RequireUniqueDisplayName) - { - var usersWithSameDisplayName = (List)MembershipProvider.Instance().GetUsersBasicSearch(this.PortalId, 0, 2, "DisplayName", true, "DisplayName", this.User.DisplayName); - if (usersWithSameDisplayName.Any(user => user.UserID != this.User.UserID)) - { - throw new Exception("Display Name must be unique"); - } - } - - UserController.UpdateUser(this.UserPortalID, this.User); - - // make sure username matches possibly changed email address - if (this.PortalSettings.Registration.UseEmailAsUserName) - { - if (this.User.Username.ToLower() != this.User.Email.ToLower()) - { - UserController.ChangeUsername(this.User.UserID, this.User.Email); - - // after username changed, should redirect to login page to let user authenticate again. - var loginUrl = Globals.LoginURL(HttpUtility.UrlEncode(this.Request.RawUrl), false); - var spliter = loginUrl.Contains("?") ? "&" : "?"; - loginUrl = $"{loginUrl}{spliter}username={this.User.Email}&usernameChanged=true"; - this.Response.Redirect(loginUrl, true); - } - } - - this.Response.Redirect(this.Request.RawUrl); - } - catch (Exception exc) - { - Logger.Error(exc); - if (exc.Message == "Display Name must be unique") - { - this.AddModuleMessage("DisplayNameNotUnique", ModuleMessage.ModuleMessageType.RedError, true); - } - else - { - this.AddModuleMessage("UserUpdatedError", ModuleMessage.ModuleMessageType.RedError, true); - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// PasswordQuestionAnswerUpdated runs when the Password Q and A have been updated. diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs index d70e39d9c6a..ccac6999791 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ManageUsers.ascx.cs @@ -36,35 +36,12 @@ namespace DotNetNuke.Modules.Admin.Users public partial class ManageUsers : UserModuleBase, IActionable { private readonly INavigationManager _navigationManager; - + 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 @@ -74,7 +51,7 @@ public ModuleActionCollection ModuleActions { if (!this.AddUser && !this.IsEdit) { - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, @@ -87,7 +64,7 @@ public ModuleActionCollection ModuleActions false); if (ProfileProviderConfig.CanEditProviderProperties) { - Actions.Add( + Actions.Add( this.GetNextActionID(), Localization.GetString("ManageProfile.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -99,8 +76,8 @@ public ModuleActionCollection ModuleActions true, false); } - - Actions.Add( + + Actions.Add( this.GetNextActionID(), Localization.GetString("Cancel.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -113,11 +90,34 @@ public ModuleActionCollection ModuleActions false); } } - + return Actions; } - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// 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; + } + } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether to display the Manage Services tab. @@ -159,7 +159,7 @@ protected string RedirectURL _RedirectURL = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); } } - + if (string.IsNullOrEmpty(_RedirectURL)) { // redirect to current page @@ -170,7 +170,7 @@ protected string RedirectURL { _RedirectURL = this._navigationManager.NavigateURL(this.PortalSettings.Registration.RedirectAfterRegistration); } - + return _RedirectURL; } } @@ -203,17 +203,17 @@ protected string UserFilter { filterString += "&"; } - + if (!string.IsNullOrEmpty(filterProperty)) { filterString += filterProperty + "&"; } - + if (!string.IsNullOrEmpty(page)) { filterString += page; } - + return filterString; } } @@ -231,8 +231,8 @@ protected bool EditProfileMode && bool.TryParse(this.Request["editProfile"], out editProfile) && editProfile; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Init runs when the control is initialised. @@ -338,7 +338,63 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + + protected void cmdCancel_Click(object sender, EventArgs e) + { + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } + } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } + } + private void BindData() { if (this.User != null) @@ -372,7 +428,7 @@ private void BindData() } } } - + if (!this.Page.IsPostBack) { if (this.Request.QueryString["pageno"] != null) @@ -384,7 +440,7 @@ private void BindData() this.PageNo = 0; } } - + this.ShowPanel(); } else @@ -418,7 +474,7 @@ private bool VerifyUserPermissions() this.DisableForm(); return false; } - + if (this.IsEdit) { // Check if user has admin rights @@ -452,7 +508,7 @@ private bool VerifyUserPermissions() } } } - + return true; } @@ -472,7 +528,7 @@ private void BindUser() this.ctlUser.ShowUpdate = false; this.CheckQuota(); } - + this.ctlUser.User = this.User; this.ctlUser.DataBind(); @@ -528,7 +584,7 @@ private void ShowPanel() this.dnnManageUsers.Visible = true; this.actionsRow.Visible = true; } - + this.BindUser(); this.dnnProfileDetails.Visible = false; } @@ -543,7 +599,7 @@ private void ShowPanel() this.ctlPassword.User = this.User; this.ctlPassword.DataBind(); } - + if (!this.IsEdit || this.User.IsSuperUser) { this.rolesTab.Visible = false; @@ -569,62 +625,6 @@ private void ShowPanel() this.dnnPasswordDetails.Visible = this.actionsRow.Visible = false; } - } - - protected void cmdCancel_Click(object sender, EventArgs e) - { - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - - /// ----------------------------------------------------------------------------- - /// - /// 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); - } - } - } - - /// ----------------------------------------------------------------------------- - /// - /// 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); - } } private bool HasManageUsersModulePermission() @@ -673,7 +673,7 @@ private void MembershipAuthorized(object sender, EventArgs e) { return; } - + try { this.AddModuleMessage("UserAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); @@ -692,7 +692,7 @@ private void MembershipAuthorized(object sender, EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + /// ----------------------------------------------------------------------------- /// /// MembershipPromoteToSuperuser runs when the User has been promoted to a superuser. @@ -706,7 +706,7 @@ private void MembershipPromoteToSuperuser(object sender, EventArgs e) { return; } - + try { this.AddModuleMessage("UserPromotedToSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); @@ -732,7 +732,7 @@ private void MembershipDemoteFromSuperuser(object sender, EventArgs e) { return; } - + try { this.AddModuleMessage("UserDemotedFromSuperuser", ModuleMessage.ModuleMessageType.GreenSuccess, true); @@ -757,7 +757,7 @@ private void MembershipUnAuthorized(object sender, EventArgs e) { return; } - + try { this.AddModuleMessage("UserUnAuthorized", ModuleMessage.ModuleMessageType.GreenSuccess, true); @@ -782,7 +782,7 @@ private void MembershipUnLocked(object sender, EventArgs e) { return; } - + try { this.AddModuleMessage("UserUnLocked", ModuleMessage.ModuleMessageType.GreenSuccess, true); @@ -806,7 +806,7 @@ private void PasswordQuestionAnswerUpdated(object sender, Password.PasswordUpdat { return; } - + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) { @@ -830,7 +830,7 @@ private void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) { return; } - + PasswordUpdateStatus status = e.UpdateStatus; if (status == PasswordUpdateStatus.Success) @@ -849,7 +849,7 @@ private void PasswordUpdated(object sender, Password.PasswordUpdatedEventArgs e) // The User changed his own password Mail.SendMail(this.User, MessageType.UserUpdatedOwnPassword, this.PortalSettings); } - + this.AddModuleMessage("PasswordChanged", ModuleMessage.ModuleMessageType.GreenSuccess, true); } catch (Exception ex) @@ -893,7 +893,7 @@ private void SubscriptionUpdated(object sender, MemberServices.SubscriptionUpdat { message = string.Format(Localization.GetString("UserSubscribed", this.LocalResourceFile), e.RoleName); } - + this.AddLocalizedModuleMessage(message, ModuleMessage.ModuleMessageType.GreenSuccess, true); } @@ -952,7 +952,7 @@ private void UserRestored(object sender, UserUserControlBase.UserRestoredEventAr try { this.Response.Redirect(this.ReturnUrl, true); - + // Module failed to load } catch (Exception exc) @@ -966,7 +966,7 @@ private void UserRemoved(object sender, UserUserControlBase.UserRemovedEventArgs try { this.Response.Redirect(this.ReturnUrl, true); - + // Module failed to load } catch (Exception exc) @@ -990,6 +990,6 @@ private void UserUpdateCompleted(object sender, EventArgs e) private void UserUpdateError(object sender, UserUserControlBase.UserUpdateErrorArgs e) { this.AddModuleMessage(e.Message, ModuleMessage.ModuleMessageType.RedError, true); - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs index c7f81b6342a..b8051af22fa 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/MemberServices.ascx.cs @@ -25,11 +25,11 @@ namespace DotNetNuke.Modules.Admin.Security /// /// ----------------------------------------------------------------------------- public partial class MemberServices : UserModuleBase - { - public delegate void SubscriptionUpdatedEventHandler(object sender, SubscriptionUpdatedEventArgs e); - - public event SubscriptionUpdatedEventHandler SubscriptionUpdated; - + { + public delegate void SubscriptionUpdatedEventHandler(object sender, SubscriptionUpdatedEventArgs e); + + public event SubscriptionUpdatedEventHandler SubscriptionUpdated; + /// ----------------------------------------------------------------------------- /// /// DataBind binds the data to the controls. @@ -46,8 +46,8 @@ public override void DataBind() // if no service available then hide options this.ServicesRow.Visible = this.grdServices.Items.Count > 0; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Raises the SubscriptionUpdated Event. @@ -59,13 +59,13 @@ public void OnSubscriptionUpdated(SubscriptionUpdatedEventArgs e) { return; } - + if (this.SubscriptionUpdated != null) { this.SubscriptionUpdated(this, e); } - } - + } + /// ----------------------------------------------------------------------------- /// /// FormatExpiryDate formats the expiry date and filters out null-values. @@ -96,7 +96,7 @@ protected string FormatExpiryDate(DateTime expiryDate) { Exceptions.ProcessModuleLoadException(this, exc); } - + return formatExpiryDate; } @@ -134,82 +134,10 @@ protected string FormatPrice(float price, int period, string frequency) { Exceptions.ProcessModuleLoadException(this, exc); } - - 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); - } - } + return formatPrice; } - 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); - } - } - /// ----------------------------------------------------------------------------- /// /// FormatTrial formats the Trial Fee amount and filters out null-values. @@ -236,7 +164,7 @@ protected string FormatTrial(float price, int period, string frequency) formatTrial = this.FormatPrice(price); break; default: - formatTrial = string.Format( + formatTrial = string.Format( Localization.GetString("TrialFee", this.LocalResourceFile), this.FormatPrice(price), period, @@ -248,7 +176,7 @@ protected string FormatTrial(float price, int period, string frequency) { Exceptions.ProcessModuleLoadException(this, exc); } - + return formatTrial; } @@ -270,14 +198,14 @@ protected string FormatURL() { serverPath += "/"; } - + formatURL = serverPath + "Register.aspx?tabid=" + this.TabId; } catch (Exception exc) // Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } - + return formatURL; } @@ -316,7 +244,7 @@ protected string ServiceText(bool subscribed, DateTime expiryDate) { Exceptions.ProcessModuleLoadException(this, exc); } - + return serviceText; } @@ -336,7 +264,7 @@ protected bool ShowSubscribe(int roleID) showSubscribe = true; } } - + return showSubscribe; } @@ -357,10 +285,10 @@ protected bool ShowTrial(int roleID) showTrial = true; } } - + return showTrial; - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -399,7 +327,79 @@ protected void grdServices_ItemCommand(object source, DataGridCommandEventArgs e // Rebind Grid this.DataBind(); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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); + } + } /// ----------------------------------------------------------------------------- /// @@ -414,7 +414,7 @@ private void cmdRSVP_Click(object sender, EventArgs e) { return; } - + // Get the RSVP code string code = this.txtRSVPCode.Text; bool rsvpCodeExists = false; @@ -432,11 +432,11 @@ private void cmdRSVP_Click(object sender, EventArgs e) this.OnSubscriptionUpdated(new SubscriptionUpdatedEventArgs(false, objRole.RoleName)); } } - + if (rsvpCodeExists) { this.lblRSVP.Text = Localization.GetString("RSVPSuccess", this.LocalResourceFile); - + // Reset RSVP Code field this.txtRSVPCode.Text = string.Empty; } @@ -445,10 +445,10 @@ private void cmdRSVP_Click(object sender, EventArgs e) this.lblRSVP.Text = Localization.GetString("RSVPFailure", this.LocalResourceFile); } } - + this.DataBind(); } - + /// ----------------------------------------------------------------------------- /// /// The SubscriptionUpdatedEventArgs class provides a customised EventArgs class for @@ -456,9 +456,9 @@ private void cmdRSVP_Click(object sender, EventArgs e) /// /// ----------------------------------------------------------------------------- public class SubscriptionUpdatedEventArgs - { + { /// ----------------------------------------------------------------------------- - /// + /// /// Initializes a new instance of the class. /// Constructs a new SubscriptionUpdatedEventArgs. /// @@ -484,6 +484,6 @@ public SubscriptionUpdatedEventArgs(bool cancel, string roleName) /// /// ----------------------------------------------------------------------------- public string RoleName { get; set; } - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs index 72d616671af..4d87c6eda13 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Membership.ascx.cs @@ -32,23 +32,29 @@ namespace DotNetNuke.Modules.Admin.Users public partial class Membership : UserModuleBase { private readonly INavigationManager _navigationManager; - + public Membership() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Raises the MembershipAuthorized Event /// /// ----------------------------------------------------------------------------- public event EventHandler MembershipAuthorized; - + public event EventHandler MembershipPasswordUpdateChanged; - + public event EventHandler MembershipUnAuthorized; - + + public event EventHandler MembershipUnLocked; + + public event EventHandler MembershipPromoteToSuperuser; + + public event EventHandler MembershipDemoteFromSuperuser; + /// ----------------------------------------------------------------------------- /// /// Gets the UserMembership associated with this control. @@ -63,17 +69,11 @@ public UserMembership UserMembership { membership = this.User.Membership; } - + return membership; } - } - - public event EventHandler MembershipUnLocked; - - public event EventHandler MembershipPromoteToSuperuser; - - public event EventHandler MembershipDemoteFromSuperuser; - + } + /// ----------------------------------------------------------------------------- /// /// Raises the MembershipPromoteToSuperuser Event. @@ -85,7 +85,7 @@ public void OnMembershipPromoteToSuperuser(EventArgs e) { return; } - + if (this.MembershipPromoteToSuperuser != null) { this.MembershipPromoteToSuperuser(this, e); @@ -104,14 +104,14 @@ public void OnMembershipDemoteFromSuperuser(EventArgs e) { return; } - + if (this.MembershipDemoteFromSuperuser != null) { this.MembershipDemoteFromSuperuser(this, e); this.Response.Redirect(this._navigationManager.NavigateURL(), true); } } - + /// ----------------------------------------------------------------------------- /// /// Raises the MembershipAuthorized Event. @@ -123,7 +123,7 @@ public void OnMembershipAuthorized(EventArgs e) { return; } - + if (this.MembershipAuthorized != null) { this.MembershipAuthorized(this, e); @@ -141,7 +141,7 @@ public void OnMembershipPasswordUpdateChanged(EventArgs e) { return; } - + if (this.MembershipPasswordUpdateChanged != null) { this.MembershipPasswordUpdateChanged(this, e); @@ -159,7 +159,7 @@ public void OnMembershipUnAuthorized(EventArgs e) { return; } - + if (this.MembershipUnAuthorized != null) { this.MembershipUnAuthorized(this, e); @@ -177,13 +177,13 @@ public void OnMembershipUnLocked(EventArgs e) { return; } - + if (this.MembershipUnLocked != null) { this.MembershipUnLocked(this, e); } - } - + } + /// ----------------------------------------------------------------------------- /// /// DataBind binds the data to the controls. @@ -206,7 +206,7 @@ public override void DataBind() this.cmdAuthorize.Visible = !this.UserMembership.Approved || this.User.IsInRole("Unverified Users"); this.cmdPassword.Visible = !this.UserMembership.UpdatePassword; } - + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser && UserController.Instance.GetCurrentUserInfo().UserID != this.User.UserID) { this.cmdToggleSuperuser.Visible = true; @@ -219,17 +219,17 @@ public override void DataBind() { this.cmdToggleSuperuser.Text = Localization.GetString("PromoteToSuperUser", this.LocalResourceFile); } - + if (PortalController.GetPortalsByUser(this.User.UserID).Count == 0) { this.cmdToggleSuperuser.Visible = false; } } - + this.lastLockoutDate.Value = this.UserMembership.LastLockoutDate.Year > 2000 ? (object)this.UserMembership.LastLockoutDate : this.LocalizeString("Never"); - + // ReSharper disable SpecifyACultureInStringConversionExplicitly this.isOnLine.Value = this.LocalizeString(this.UserMembership.IsOnLine.ToString()); this.lockedOut.Value = this.LocalizeString(this.UserMembership.LockedOut.ToString()); @@ -247,8 +247,8 @@ public override void DataBind() // ReSharper restore SpecifyACultureInStringConversionExplicitly this.membershipForm.DataSource = this.UserMembership; this.membershipForm.DataBind(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Load runs when the control is loaded. @@ -266,7 +266,7 @@ protected override void OnLoad(EventArgs e) this.cmdUnLock.Click += this.cmdUnLock_Click; this.cmdToggleSuperuser.Click += this.cmdToggleSuperuser_Click; } - + /// ----------------------------------------------------------------------------- /// /// cmdAuthorize_Click runs when the Authorize User Button is clicked. @@ -278,13 +278,13 @@ private void cmdAuthorize_Click(object sender, EventArgs e) { return; } - - if (this.Request.IsAuthenticated != true) - { - return; - } - - // Get the Membership Information from the property editors + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // Get the Membership Information from the property editors this.User.Membership = (UserMembership)this.membershipForm.DataSource; this.User.Membership.Approved = true; @@ -314,12 +314,12 @@ private void cmdPassword_Click(object sender, EventArgs e) { return; } - - if (this.Request.IsAuthenticated != true) - { - return; - } - + + if (this.Request.IsAuthenticated != true) + { + return; + } + bool canSend = Mail.SendMail(this.User, MessageType.PasswordReminder, this.PortalSettings) == string.Empty; var message = string.Empty; if (canSend) @@ -352,13 +352,13 @@ private void cmdUnAuthorize_Click(object sender, EventArgs e) { return; } - - if (this.Request.IsAuthenticated != true) - { - return; - } - - // Get the Membership Information from the property editors + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // Get the Membership Information from the property editors this.User.Membership = (UserMembership)this.membershipForm.DataSource; this.User.Membership.Approved = false; @@ -368,7 +368,7 @@ private void cmdUnAuthorize_Click(object sender, EventArgs e) this.OnMembershipUnAuthorized(EventArgs.Empty); } - + /// /// cmdToggleSuperuser_Click runs when the toggle superuser button is clicked. /// @@ -380,20 +380,20 @@ private void cmdToggleSuperuser_Click(object sender, EventArgs e) { return; } - - if (this.Request.IsAuthenticated != true) - { - return; - } - ////ensure only superusers can change user superuser state - if (UserController.Instance.GetCurrentUserInfo().IsSuperUser != true) - { - return; - } - + + if (this.Request.IsAuthenticated != true) + { + return; + } + ////ensure only superusers can change user superuser state + if (UserController.Instance.GetCurrentUserInfo().IsSuperUser != true) + { + return; + } + var currentSuperUserState = this.User.IsSuperUser; this.User.IsSuperUser = !currentSuperUserState; - + // Update User UserController.UpdateUser(this.PortalId, this.User); DataCache.ClearCache(); @@ -407,7 +407,7 @@ private void cmdToggleSuperuser_Click(object sender, EventArgs e) this.OnMembershipPromoteToSuperuser(EventArgs.Empty); } } - + /// ----------------------------------------------------------------------------- /// /// cmdUnlock_Click runs when the Unlock Account Button is clicked. @@ -419,13 +419,13 @@ private void cmdUnLock_Click(object sender, EventArgs e) { return; } - - if (this.Request.IsAuthenticated != true) - { - return; - } - - // update the user record in the database + + if (this.Request.IsAuthenticated != true) + { + return; + } + + // update the user record in the database bool isUnLocked = UserController.UnLockUser(this.User); if (isUnLocked) @@ -434,6 +434,6 @@ private void cmdUnLock_Click(object sender, EventArgs e) this.OnMembershipUnLocked(EventArgs.Empty); } - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs index 5266992810a..fbeaeeaa2d4 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Profile.ascx.cs @@ -26,51 +26,56 @@ namespace DesktopModules.Admin.Security /// /// ----------------------------------------------------------------------------- public partial class DNNProfile : ProfileUserControlBase - { + { /// ----------------------------------------------------------------------------- /// - /// Gets or sets and sets the EditorMode. + /// Gets a value indicating whether gets whether the User is valid. /// /// ----------------------------------------------------------------------------- - public PropertyEditorMode EditorMode + public bool IsValid { get { - return this.ProfileProperties.EditMode; - } - - set - { - this.ProfileProperties.EditMode = value; + return this.ProfileProperties.IsValid || this.IsAdmin; } } /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether gets whether the User is valid. + /// Gets the UserProfile associated with this control. /// /// ----------------------------------------------------------------------------- - public bool IsValid + public UserProfile UserProfile { get { - return this.ProfileProperties.IsValid || this.IsAdmin; + UserProfile _Profile = null; + if (this.User != null) + { + _Profile = this.User.Profile; + } + + return _Profile; } } - + /// ----------------------------------------------------------------------------- /// - /// Gets a value indicating whether gets whether to display the Visibility controls. + /// Gets or sets and sets the EditorMode. /// /// ----------------------------------------------------------------------------- - protected bool ShowVisibility + public PropertyEditorMode EditorMode { get { - object setting = GetSetting(this.PortalId, "Profile_DisplayVisibility"); - return Convert.ToBoolean(setting) && this.IsUser; + return this.ProfileProperties.EditMode; + } + + set + { + this.ProfileProperties.EditMode = value; } - } + } /// ----------------------------------------------------------------------------- /// @@ -83,7 +88,7 @@ public bool ShowUpdate { return this.actionsRow.Visible; } - + set { this.actionsRow.Visible = value; @@ -92,23 +97,18 @@ public bool ShowUpdate /// ----------------------------------------------------------------------------- /// - /// Gets the UserProfile associated with this control. + /// Gets a value indicating whether gets whether to display the Visibility controls. /// /// ----------------------------------------------------------------------------- - public UserProfile UserProfile + protected bool ShowVisibility { get { - UserProfile _Profile = null; - if (this.User != null) - { - _Profile = this.User.Profile; - } - - return _Profile; + object setting = GetSetting(this.PortalId, "Profile_DisplayVisibility"); + return Convert.ToBoolean(setting) && this.IsUser; } - } - + } + /// ----------------------------------------------------------------------------- /// /// DataBind binds the data to the controls. @@ -136,8 +136,8 @@ public override void DataBind() this.ProfileProperties.ShowVisibility = this.ShowVisibility; this.ProfileProperties.DataSource = properties; this.ProfileProperties.DataBind(); - } - + } + /// ----------------------------------------------------------------------------- /// /// Page_Init runs when the control is initialised. @@ -157,7 +157,7 @@ protected override void OnInit(EventArgs e) // Check if culture is RTL this.ProfileProperties.LabelMode = basePage.PageCulture.TextInfo.IsRightToLeft ? LabelMode.Right : LabelMode.Left; } - + this.ProfileProperties.LocalResourceFile = this.LocalResourceFile; } @@ -225,6 +225,6 @@ private void UpdateDisplayName() { this.User.UpdateDisplayName(this.PortalSettings.Registration.DisplayNameFormat); } - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs index fef019515ca..4ac2f5676ca 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/ProfileDefinitions.ascx.cs @@ -35,16 +35,16 @@ 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 const int COLUMN_MOVE_UP = 3; + private readonly INavigationManager _navigationManager; - + private ProfilePropertyDefinitionCollection _profileProperties; + private bool _requiredColumnHidden = false; + public ProfileDefinitions() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - private const int COLUMN_MOVE_UP = 3; - private ProfilePropertyDefinitionCollection _profileProperties; - private bool _requiredColumnHidden = false; + } /// ----------------------------------------------------------------------------- /// @@ -67,7 +67,7 @@ public string ReturnUrl filterParams.SetValue("filter=" + this.Request.QueryString["filter"], 0); filterParams.SetValue("filterProperty=" + this.Request.QueryString["filterProperty"], 1); } - + if (string.IsNullOrEmpty(this.Request.QueryString["filter"])) { returnURL = this._navigationManager.NavigateURL(this.TabId); @@ -76,17 +76,17 @@ public string ReturnUrl { returnURL = this._navigationManager.NavigateURL(this.TabId, string.Empty, filterParams); } - + return returnURL; } } - + public ModuleActionCollection ModuleActions { get { var actions = new ModuleActionCollection(); - actions.Add( + actions.Add( this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, @@ -97,7 +97,7 @@ public ModuleActionCollection ModuleActions SecurityAccessLevel.Admin, true, false); - actions.Add( + actions.Add( this.GetNextActionID(), Localization.GetString("Cancel.Action", this.LocalResourceFile), ModuleActionType.AddContent, @@ -110,8 +110,8 @@ public ModuleActionCollection ModuleActions false); return actions; } - } - + } + /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether we are dealing with SuperUsers. @@ -152,11 +152,11 @@ protected int UsersPortalId { intPortalId = Null.NullInteger; } - + return intPortalId; } - } - + } + public string DisplayDataType(ProfilePropertyDefinition definition) { string retValue = Null.NullString; @@ -166,7 +166,7 @@ public string DisplayDataType(ProfilePropertyDefinition definition) { retValue = definitionEntry.Value; } - + return retValue; } @@ -177,10 +177,25 @@ public string DisplayDefaultVisibility(ProfilePropertyDefinition definition) { retValue = this.LocalizeString(definition.DefaultVisibility.ToString()) ?? definition.DefaultVisibility.ToString(); } - + return retValue; } - + + public void Update() + { + try + { + this.UpdateProperties(); + + // Redirect to upadte page + this.Response.Redirect(this.Request.RawUrl, true); + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + protected override void LoadViewState(object savedState) { if (savedState != null) @@ -211,8 +226,125 @@ protected override object SaveViewState() allStates[1] = this.ProfileProperties; return allStates; - } - + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Init runs when the control is initialised. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + foreach (DataGridColumn column in this.grdProfileProperties.Columns) + { + if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) + { + var checkBoxColumn = (CheckBoxColumn)column; + if (checkBoxColumn.DataField == "Required" && this.UsersPortalId == Null.NullInteger) + { + checkBoxColumn.Visible = false; + this._requiredColumnHidden = true; + } + + if (this.SupportsRichClient() == false) + { + checkBoxColumn.CheckedChanged += this.grdProfileProperties_ItemCheckedChanged; + } + } + else if (ReferenceEquals(column.GetType(), typeof(ImageCommandColumn))) + { + // Manage Delete Confirm JS + var imageColumn = (ImageCommandColumn)column; + switch (imageColumn.CommandName) + { + case "Delete": + imageColumn.OnClickJS = Localization.GetString("DeleteItem"); + imageColumn.Text = Localization.GetString("Delete", this.LocalResourceFile); + break; + case "Edit": + // The Friendly URL parser does not like non-alphanumeric characters + // so first create the format string with a dummy value and then + // replace the dummy value with the FormatString place holder + string formatString = this.EditUrl("PropertyDefinitionID", "KEYFIELD", "EditProfileProperty"); + formatString = formatString.Replace("KEYFIELD", "{0}"); + imageColumn.NavigateURLFormatString = formatString; + imageColumn.Text = Localization.GetString("Edit", this.LocalResourceFile); + break; + case "MoveUp": + imageColumn.Text = Localization.GetString("MoveUp", this.LocalResourceFile); + break; + case "MoveDown": + imageColumn.Text = Localization.GetString("MoveDown", this.LocalResourceFile); + break; + } + } + } + } + + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + this.cmdRefresh.Click += this.cmdRefresh_Click; + this.grdProfileProperties.ItemCommand += this.grdProfileProperties_ItemCommand; + this.grdProfileProperties.ItemCreated += this.grdProfileProperties_ItemCreated; + this.grdProfileProperties.ItemDataBound += this.grdProfileProperties_ItemDataBound; + + this.cmdAdd.NavigateUrl = this.EditUrl("EditProfileProperty"); + + try + { + if (!this.Page.IsPostBack) + { + Localization.LocalizeDataGrid(ref this.grdProfileProperties, this.LocalResourceFile); + this.BindGrid(); + } + } + catch (Exception exc) // Module failed to load + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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; + } + } + } + } + /// ----------------------------------------------------------------------------- /// /// Helper function that determines whether the client-side functionality is possible. @@ -299,18 +431,18 @@ private void BindGrid() { allRequired = false; } - + if (profProperty.Visible == false) { allVisible = false; } - + if (!allRequired && !allVisible) { break; } } - + foreach (DataGridColumn column in this.grdProfileProperties.Columns) { if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) @@ -321,14 +453,14 @@ private void BindGrid() { checkBoxColumn.Checked = allRequired; } - + if (checkBoxColumn.DataField == "Visible") { checkBoxColumn.Checked = allVisible; } } } - + this.grdProfileProperties.DataSource = this.ProfileProperties; this.grdProfileProperties.DataBind(); } @@ -360,7 +492,7 @@ private void UpdateProperties() { property.Required = false; } - + ProfileController.UpdatePropertyDefinition(property); } } @@ -390,142 +522,10 @@ private void ProcessPostBack() { this.ProfileProperties[Convert.ToInt32(newOrder[i])].ViewOrder = i; } - - this.ProfileProperties.Sort(); - } - - public void Update() - { - try - { - this.UpdateProperties(); - // Redirect to upadte page - this.Response.Redirect(this.Request.RawUrl, true); - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Init runs when the control is initialised. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - foreach (DataGridColumn column in this.grdProfileProperties.Columns) - { - if (ReferenceEquals(column.GetType(), typeof(CheckBoxColumn))) - { - var checkBoxColumn = (CheckBoxColumn)column; - if (checkBoxColumn.DataField == "Required" && this.UsersPortalId == Null.NullInteger) - { - checkBoxColumn.Visible = false; - this._requiredColumnHidden = true; - } - - if (this.SupportsRichClient() == false) - { - checkBoxColumn.CheckedChanged += this.grdProfileProperties_ItemCheckedChanged; - } - } - else if (ReferenceEquals(column.GetType(), typeof(ImageCommandColumn))) - { - // Manage Delete Confirm JS - var imageColumn = (ImageCommandColumn)column; - switch (imageColumn.CommandName) - { - case "Delete": - imageColumn.OnClickJS = Localization.GetString("DeleteItem"); - imageColumn.Text = Localization.GetString("Delete", this.LocalResourceFile); - break; - case "Edit": - // The Friendly URL parser does not like non-alphanumeric characters - // so first create the format string with a dummy value and then - // replace the dummy value with the FormatString place holder - string formatString = this.EditUrl("PropertyDefinitionID", "KEYFIELD", "EditProfileProperty"); - formatString = formatString.Replace("KEYFIELD", "{0}"); - imageColumn.NavigateURLFormatString = formatString; - imageColumn.Text = Localization.GetString("Edit", this.LocalResourceFile); - break; - case "MoveUp": - imageColumn.Text = Localization.GetString("MoveUp", this.LocalResourceFile); - break; - case "MoveDown": - imageColumn.Text = Localization.GetString("MoveDown", this.LocalResourceFile); - break; - } - } - } - } - - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - this.cmdRefresh.Click += this.cmdRefresh_Click; - this.grdProfileProperties.ItemCommand += this.grdProfileProperties_ItemCommand; - this.grdProfileProperties.ItemCreated += this.grdProfileProperties_ItemCreated; - this.grdProfileProperties.ItemDataBound += this.grdProfileProperties_ItemDataBound; - - this.cmdAdd.NavigateUrl = this.EditUrl("EditProfileProperty"); - - try - { - if (!this.Page.IsPostBack) - { - Localization.LocalizeDataGrid(ref this.grdProfileProperties, this.LocalResourceFile); - this.BindGrid(); - } - } - catch (Exception exc) // Module failed to load - { - Exceptions.ProcessModuleLoadException(this, exc); - } + this.ProfileProperties.Sort(); } - /// ----------------------------------------------------------------------------- - /// - /// 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. @@ -581,7 +581,7 @@ private void grdProfileProperties_ItemCheckedChanged(object sender, DNNDataGridC break; } } - + this.BindGrid(); } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs index 8926439b32d..7ae54640bad 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Register.ascx.cs @@ -48,23 +48,8 @@ public partial class Register : UserUserControlBase public Register() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - - protected string AuthenticationType - { - get - { - return this.ViewState.GetValue("AuthenticationType", Null.NullString); - } - - set - { - this.ViewState.SetValue("AuthenticationType", value, Null.NullString); - } } - protected UserCreateStatus CreateStatus { get; set; } - protected string ExcludeTerms { get @@ -74,7 +59,7 @@ protected string ExcludeTerms { regex = @"^(?:(?!" + this.PortalSettings.Registration.ExcludeTerms.Replace(" ", string.Empty).Replace(",", "|") + @").)*$\r?\n?"; } - + return regex; } } @@ -87,21 +72,36 @@ protected bool IsValid } } + protected override bool AddUser { get; } = true; + + protected string AuthenticationType + { + get + { + return this.ViewState.GetValue("AuthenticationType", Null.NullString); + } + + set + { + this.ViewState.SetValue("AuthenticationType", value, Null.NullString); + } + } + + protected UserCreateStatus CreateStatus { get; set; } + protected string UserToken { get { return this.ViewState.GetValue("UserToken", string.Empty); } - + set { this.ViewState.SetValue("UserToken", value, string.Empty); } } - protected override bool AddUser { get; } = true; - protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -168,7 +168,7 @@ protected override void OnInit(EventArgs e) else { var fields = this.PortalSettings.Registration.RegistrationFields.Split(',').ToList(); - + // append question/answer field when RequiresQuestionAndAnswer is enabled in config. if (MembershipProviderConfig.RequiresQuestionAndAnswer) { @@ -176,7 +176,7 @@ protected override void OnInit(EventArgs e) { fields.Add("PasswordQuestion"); } - + if (!fields.Contains("PasswordAnswer")) { fields.Add("PasswordAnswer"); @@ -215,7 +215,7 @@ protected override void OnInit(EventArgs e) { this.AddProperty(property); } - + break; } } @@ -248,7 +248,7 @@ protected override void OnInit(EventArgs e) if (authSystem.AuthenticationType != "DNN") { this.BindLoginControl(authLoginControl, authSystem); - + // Check if AuthSystem is Enabled if (authLoginControl.Enabled && authLoginControl.SupportsRegistration) { @@ -317,7 +317,7 @@ protected override void OnLoad(EventArgs e) this.userHelpLabel.Text += Localization.GetString("VerifiedMembership", Localization.SharedResourceFile); break; } - + this.userHelpLabel.Text += Localization.GetString("Required", this.LocalResourceFile); this.userHelpLabel.Text += Localization.GetString("RegisterWarning", this.LocalResourceFile); @@ -353,8 +353,8 @@ protected override void OnPreRender(EventArgs e) { this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", script, true); } - } - + } + private void AddField(string dataField, string dataMember, bool required, string regexValidator, TextBoxMode textMode) { if (this.userForm.Items.Any(i => i.ID == dataField)) @@ -375,7 +375,7 @@ private void AddField(string dataField, string dataMember, bool required, string { formItem.ValidationExpression = regexValidator; } - + this.userForm.Items.Add(formItem); } @@ -449,18 +449,18 @@ private void AddProperty(ProfilePropertyDefinition property) Visible = property.Visible, Required = property.Required, }; - + // To check if the property has a deafult value if (!string.IsNullOrEmpty(property.DefaultValue)) { formItem.Value = property.DefaultValue; } - + if (!string.IsNullOrEmpty(property.ValidationExpression)) { formItem.ValidationExpression = property.ValidationExpression; } - + this.userForm.Items.Add(formItem); } } @@ -558,7 +558,7 @@ private bool Validate() { this.CreateStatus = UserCreateStatus.InvalidUserName; } - + var valid = UserController.Instance.IsValidUserName(name); if (!valid) @@ -583,14 +583,14 @@ private bool Validate() { this.CreateStatus = UserCreateStatus.InvalidLastName; } - - if (string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) - { - var cleanDisplayName = PortalSecurity.Instance.InputFilter(this.User.DisplayName, filterFlags); - if (!cleanDisplayName.Equals(this.User.DisplayName)) - { - this.CreateStatus = UserCreateStatus.InvalidDisplayName; - } + + if (string.IsNullOrEmpty(this.PortalSettings.Registration.DisplayNameFormat)) + { + var cleanDisplayName = PortalSecurity.Instance.InputFilter(this.User.DisplayName, filterFlags); + if (!cleanDisplayName.Equals(this.User.DisplayName)) + { + this.CreateStatus = UserCreateStatus.InvalidDisplayName; + } } } @@ -674,7 +674,7 @@ private bool Validate() this.CreateStatus = UserCreateStatus.BannedPasswordUsed; } } - + // Validate Profanity if (this.PortalSettings.Registration.UseProfanityFilter) { @@ -682,7 +682,7 @@ private bool Validate() { this.CreateStatus = UserCreateStatus.InvalidUserName; } - + if (!string.IsNullOrEmpty(this.User.DisplayName)) { if (!portalSecurity.ValidateInput(this.User.DisplayName, PortalSecurity.FilterFlag.NoProfanity)) @@ -711,7 +711,7 @@ private bool Validate() user = UserController.GetUserByName(this.PortalId, userName); i++; } - + this.User.Username = userName; } } @@ -731,7 +731,7 @@ private bool Validate() user = UserController.Instance.GetUserByDisplayname(this.PortalId, displayName); i++; } - + this.User.DisplayName = displayName; } } @@ -744,7 +744,7 @@ private bool Validate() // Invalid Question this.CreateStatus = UserCreateStatus.InvalidQuestion; } - + if (this.CreateStatus == UserCreateStatus.AddUser) { if (string.IsNullOrEmpty(this.User.Membership.PasswordAnswer)) @@ -759,7 +759,7 @@ private bool Validate() { _IsValid = false; } - + return _IsValid; } @@ -783,7 +783,7 @@ private string GetRedirectUrl(bool checkSetting = true) if (redirectUrl.Contains("?returnurl")) { - string baseURL = redirectUrl.Substring( + string baseURL = redirectUrl.Substring( 0, redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); string returnURL = @@ -792,7 +792,7 @@ private string GetRedirectUrl(bool checkSetting = true) redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); } } - + if (string.IsNullOrEmpty(redirectUrl)) { // redirect to current page @@ -868,9 +868,9 @@ private void UserAuthenticated(object sender, UserAuthenticatedEventArgs e) { formItem.Visible = formItem.DataField == "Email"; } - + this.userForm.DataBind(); } - } + } } } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs index f84cb3a13c9..9ef56c26276 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/SecurityRoles.ascx.cs @@ -41,7 +41,7 @@ namespace DotNetNuke.Modules.Admin.Security public partial class SecurityRoles : PortalModuleBase, IActionable { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SecurityRoles)); - private readonly INavigationManager _navigationManager; + private readonly INavigationManager _navigationManager; private int RoleId = Null.NullInteger; private new int UserId = Null.NullInteger; private RoleInfo _Role; @@ -49,13 +49,21 @@ public partial class SecurityRoles : PortalModuleBase, IActionable private UserInfo _User; private int _totalPages = 1; - private int _totalRecords; - + private int _totalRecords; + public SecurityRoles() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + + public ModuleActionCollection ModuleActions + { + get + { + return new ModuleActionCollection(); + } + } + /// ----------------------------------------------------------------------------- /// /// Gets or sets and sets the ParentModule (if one exists). @@ -63,16 +71,8 @@ public SecurityRoles() /// /// /// ----------------------------------------------------------------------------- - public PortalModuleBase ParentModule { get; set; } - - public ModuleActionCollection ModuleActions - { - get - { - return new ModuleActionCollection(); - } - } - + public PortalModuleBase ParentModule { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets the Return Url for the page. @@ -96,7 +96,7 @@ protected string ReturnUrl FilterParams.SetValue("filterProperty=" + this.Request.QueryString["filterProperty"], 1); FilterParams.SetValue("currentpage=" + this.Request.QueryString["currentpage"], 2); } - + if (string.IsNullOrEmpty(this.Request.QueryString["filter"])) { _ReturnURL = this._navigationManager.NavigateURL(this.TabId); @@ -105,7 +105,7 @@ protected string ReturnUrl { _ReturnURL = this._navigationManager.NavigateURL(this.TabId, string.Empty, FilterParams); } - + return _ReturnURL; } } @@ -125,7 +125,7 @@ protected RoleInfo Role this._Role = RoleController.Instance.GetRole(this.PortalId, r => r.RoleID == Convert.ToInt32(this.cboRoles.SelectedItem.Value)); } } - + return this._Role; } } @@ -149,21 +149,8 @@ protected UserInfo User this._User = UserController.GetUserById(this.PortalId, Convert.ToInt32(this.cboUsers.SelectedItem.Value)); } } - - return this._User; - } - } - protected int SelectedUserID - { - get - { - return this._SelectedUserID; - } - - set - { - this._SelectedUserID = value; + return this._User; } } @@ -181,8 +168,6 @@ protected UsersControl UsersControl } } - protected int CurrentPage { get; set; } - protected int PageSize { get @@ -190,8 +175,23 @@ protected int PageSize var setting = UserModuleBase.GetSetting(this.PortalId, "Records_PerPage"); return Convert.ToInt32(setting); } - } - + } + + protected int SelectedUserID + { + get + { + return this._SelectedUserID; + } + + set + { + this._SelectedUserID = value; + } + } + + protected int CurrentPage { get; set; } + /// ----------------------------------------------------------------------------- /// /// DataBind binds the data to the controls. @@ -203,7 +203,7 @@ public override void DataBind() { this.Response.Redirect(this._navigationManager.NavigateURL("Access Denied"), true); } - + base.DataBind(); // Localize Headers @@ -223,7 +223,7 @@ public override void DataBind() /// /// /// The ID of the user to check delete button visibility for. - /// The ID of the role to check delete button visibility for. + /// The ID of the role to check delete button visibility for. /// /// ----------------------------------------------------------------------------- public bool DeleteButtonVisible(int UserID, int RoleID) @@ -235,10 +235,178 @@ public bool DeleteButtonVisible(int UserID, int RoleID) // User can only delete if in Admin role canDelete = PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName); } - + return canDelete; } - + + /// ----------------------------------------------------------------------------- + /// + /// FormatExpiryDate formats the expiry/effective date and filters out nulls. + /// + /// + /// + /// The Date object to format. + /// + /// ----------------------------------------------------------------------------- + public string FormatDate(DateTime DateTime) + { + if (!Null.IsNull(DateTime)) + { + return DateTime.ToShortDateString(); + } + else + { + return string.Empty; + } + } + + /// ----------------------------------------------------------------------------- + /// + /// FormatExpiryDate formats the expiry/effective date and filters out nulls. + /// + /// + /// ----------------------------------------------------------------------------- + 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); + } + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Init runs when the control is initialised. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (this.Request.QueryString["RoleId"] != null) + { + this.RoleId = int.Parse(this.Request.QueryString["RoleId"]); + } + + if (this.Request.QueryString["UserId"] != null) + { + int userId; + + // Use Int32.MaxValue as invalid UserId + this.UserId = int.TryParse(this.Request.QueryString["UserId"], out userId) ? userId : int.MaxValue; + } + + this.CurrentPage = 1; + if (this.Request.QueryString["CurrentPage"] != null) + { + var currentPage = 0; + if (int.TryParse(this.Request.QueryString["CurrentPage"], out currentPage) + && currentPage > 0) + { + this.CurrentPage = currentPage; + } + else + { + this.CurrentPage = 1; + } + } + + this.cboRoles.SelectedIndexChanged += this.cboRoles_SelectedIndexChanged; + this.cboUsers.SelectedIndexChanged += this.cboUsers_SelectedIndexChanged; + this.cmdAdd.Click += this.cmdAdd_Click; + this.cmdValidate.Click += this.cmdValidate_Click; + this.grdUserRoles.ItemCreated += this.grdUserRoles_ItemCreated; + this.grdUserRoles.ItemDataBound += this.grdUserRoles_ItemDataBound; + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + + try + { + this.cmdCancel.NavigateUrl = this.ReturnUrl; + if (this.ParentModule == null) + { + this.DataBind(); + } + + if (this.Role == null) + { + return; + } + + this.placeIsOwner.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); + this.placeIsOwnerHeader.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); + } + catch (ThreadAbortException exc) // Do nothing if ThreadAbort as this is caused by a redirect + { + Logger.Debug(exc); + } + catch (Exception exc) // Module failed to load + { + 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); + } + } + } + } + /// ----------------------------------------------------------------------------- /// /// BindData loads the controls from the Database. @@ -266,15 +434,15 @@ private void BindData() roleIndex = roles.IndexOf(tmpRole); } } - + break; } - + if (roleIndex > Null.NullInteger) { roles.RemoveAt(roleIndex); } - + this.cboRoles.DataSource = roles; this.cboRoles.DataBind(); } @@ -290,7 +458,7 @@ private void BindData() this.cboRoles.Items[0].Selected = true; this.lblTitle.Text = string.Format(Localization.GetString("RoleTitle.Text", this.LocalResourceFile), this.Role.RoleName, this.Role.RoleID); } - + this.cboRoles.Visible = false; this.plRoles.Visible = false; } @@ -308,7 +476,7 @@ private void BindData() this.chkNotify.Visible = false; return; } - + if (this.UsersControl == UsersControl.Combo) { if (this.cboUsers.Items.Count == 0) @@ -319,7 +487,7 @@ private void BindData() this.cboUsers.AddItem(objUser.DisplayName + " (" + objUser.Username + ")", objUser.UserID.ToString()); } } - + this.txtUsers.Visible = false; this.cboUsers.Visible = true; this.cmdValidate.Visible = false; @@ -338,7 +506,7 @@ private void BindData() this.txtUsers.Text = this.User.UserID.ToString(); this.lblTitle.Text = string.Format(Localization.GetString("UserTitle.Text", this.LocalResourceFile), this.User.Username, this.User.UserID); } - + this.txtUsers.Visible = false; this.cboUsers.Visible = false; this.cmdValidate.Visible = false; @@ -361,7 +529,7 @@ private void BindGrid() this.grdUserRoles.DataKeyField = "UserId"; this.grdUserRoles.Columns[2].Visible = false; } - + if (this.UserId != Null.NullInteger) { this.cmdAdd.Text = Localization.GetString("AddRole.Text", this.LocalResourceFile); @@ -419,7 +587,7 @@ private void GetDates(int UserId, int RoleId) { effectiveDate = objUserRole.EffectiveDate; } - + if (Null.IsNull(objUserRole.ExpiryDate) == false) { expiryDate = objUserRole.ExpiryDate; @@ -448,179 +616,11 @@ private void GetDates(int UserId, int RoleId) } } } - + this.effectiveDatePicker.SelectedDate = effectiveDate; this.expiryDatePicker.SelectedDate = expiryDate; - } - - /// ----------------------------------------------------------------------------- - /// - /// FormatExpiryDate formats the expiry/effective date and filters out nulls. - /// - /// - /// - /// The Date object to format. - /// - /// ----------------------------------------------------------------------------- - public string FormatDate(DateTime DateTime) - { - if (!Null.IsNull(DateTime)) - { - return DateTime.ToShortDateString(); - } - else - { - return string.Empty; - } - } - - /// ----------------------------------------------------------------------------- - /// - /// FormatExpiryDate formats the expiry/effective date and filters out nulls. - /// - /// - /// ----------------------------------------------------------------------------- - 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); - } - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Init runs when the control is initialised. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (this.Request.QueryString["RoleId"] != null) - { - this.RoleId = int.Parse(this.Request.QueryString["RoleId"]); - } - - if (this.Request.QueryString["UserId"] != null) - { - int userId; - - // Use Int32.MaxValue as invalid UserId - this.UserId = int.TryParse(this.Request.QueryString["UserId"], out userId) ? userId : int.MaxValue; - } - - this.CurrentPage = 1; - if (this.Request.QueryString["CurrentPage"] != null) - { - var currentPage = 0; - if (int.TryParse(this.Request.QueryString["CurrentPage"], out currentPage) - && currentPage > 0) - { - this.CurrentPage = currentPage; - } - else - { - this.CurrentPage = 1; - } - } - - this.cboRoles.SelectedIndexChanged += this.cboRoles_SelectedIndexChanged; - this.cboUsers.SelectedIndexChanged += this.cboUsers_SelectedIndexChanged; - this.cmdAdd.Click += this.cmdAdd_Click; - this.cmdValidate.Click += this.cmdValidate_Click; - this.grdUserRoles.ItemCreated += this.grdUserRoles_ItemCreated; - this.grdUserRoles.ItemDataBound += this.grdUserRoles_ItemDataBound; } - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - - try - { - this.cmdCancel.NavigateUrl = this.ReturnUrl; - if (this.ParentModule == null) - { - this.DataBind(); - } - - if (this.Role == null) - { - return; - } - - this.placeIsOwner.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); - this.placeIsOwnerHeader.Visible = (this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both); - } - catch (ThreadAbortException exc) // Do nothing if ThreadAbort as this is caused by a redirect - { - Logger.Debug(exc); - } - catch (Exception exc) // Module failed to load - { - 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); - } - } - } - } - /// ----------------------------------------------------------------------------- /// /// cboUsers_SelectedIndexChanged runs when the selected User is changed in the @@ -636,7 +636,7 @@ private void cboUsers_SelectedIndexChanged(object sender, EventArgs e) this.SelectedUserID = int.Parse(this.cboUsers.SelectedItem.Value); this.GetDates(this.SelectedUserID, int.Parse(this.cboRoles.SelectedItem.Value)); } - + this.BindGrid(); } @@ -668,7 +668,7 @@ private void cmdValidate_Click(object sender, EventArgs e) this.txtUsers.Text = string.Empty; } } - + this.BindGrid(); } @@ -699,7 +699,7 @@ private void cmdAdd_Click(object sender, EventArgs e) { return; } - + try { if (this.Page.IsValid) @@ -736,16 +736,16 @@ private void cmdAdd_Click(object sender, EventArgs e) // Add User to Role var isOwner = false; - if ((this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both)) - { - isOwner = this.chkIsOwner.Checked; - } - + if ((this.Role.SecurityMode == SecurityMode.SocialGroup) || (this.Role.SecurityMode == SecurityMode.Both)) + { + isOwner = this.chkIsOwner.Checked; + } + RoleController.AddUserRole(this.User, this.Role, this.PortalSettings, RoleStatus.Approved, datEffectiveDate, datExpiryDate, this.chkNotify.Checked, isOwner); this.chkIsOwner.Checked = false; // reset the checkbox } } - + this.BindGrid(); } catch (Exception exc) // Module failed to load @@ -780,7 +780,7 @@ private void grdUserRoles_ItemCreated(object sender, DataGridItemEventArgs e) { ClientAPI.AddButtonConfirm(cmdDeleteUserRole, string.Format(Localization.GetString("DeleteUsersFromRole.Text", this.LocalResourceFile), role.FullName, role.RoleName)); } - + cmdDeleteUserRole.Attributes.Add("roleId", role.RoleID.ToString()); cmdDeleteUserRole.Attributes.Add("userId", role.UserID.ToString()); } diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs index 66005777fbb..ea5d2e18456 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/User.ascx.cs @@ -42,8 +42,6 @@ public partial class User : UserUserControlBase { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(User)); - public UserCreateStatus CreateStatus { get; set; } - /// ----------------------------------------------------------------------------- /// /// Gets a value indicating whether gets whether the User is valid. @@ -56,6 +54,8 @@ public bool IsValid } } + public UserCreateStatus CreateStatus { get; set; } + /// ----------------------------------------------------------------------------- /// /// Gets or sets a value indicating whether gets and sets whether the Password section is displayed. @@ -284,6 +284,80 @@ public override void DataBind() } } + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the control is loaded. + /// + /// + /// + protected override void OnLoad(EventArgs e) + { + base.OnLoad(e); + this.cmdDelete.Click += this.cmdDelete_Click; + this.cmdUpdate.Click += this.cmdUpdate_Click; + this.cmdRemove.Click += this.cmdRemove_Click; + this.cmdRestore.Click += this.cmdRestore_Click; + } + + protected override void OnPreRender(EventArgs e) + { + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); + ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); + ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); + + ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); + + JavaScript.RequestRegistration(CommonJs.DnnPlugins); + + base.OnPreRender(e); + + if (Host.EnableStrengthMeter) + { + this.passwordContainer.CssClass = "password-strength-container"; + this.txtPassword.CssClass = "password-strength"; + this.txtConfirm.CssClass = string.Format("{0} checkStength", this.txtConfirm.CssClass); + + var options = new DnnPaswordStrengthOptions(); + var optionsAsJsonString = Json.Serialize(options); + var passwordScript = string.Format( + "dnn.initializePasswordStrength('.{0}', {1});{2}", + "password-strength", optionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", passwordScript, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", passwordScript, true); + } + } + + var confirmPasswordOptions = new DnnConfirmPasswordOptions() + { + FirstElementSelector = "#" + this.passwordContainer.ClientID + " input[type=password]", + SecondElementSelector = ".password-confirm", + ContainerSelector = ".dnnFormPassword", + UnmatchedCssClass = "unmatched", + MatchedCssClass = "matched", + }; + + var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); + var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); + + if (ScriptManager.GetCurrent(this.Page) != null) + { + // respect MS AJAX + ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", confirmScript, true); + } + else + { + this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", confirmScript, true); + } + } + /// /// 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. @@ -402,80 +476,6 @@ private bool Validate() return _IsValid; } - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the control is loaded. - /// - /// - /// - protected override void OnLoad(EventArgs e) - { - base.OnLoad(e); - this.cmdDelete.Click += this.cmdDelete_Click; - this.cmdUpdate.Click += this.cmdUpdate_Click; - this.cmdRemove.Click += this.cmdRemove_Click; - this.cmdRestore.Click += this.cmdRestore_Click; - } - - protected override void OnPreRender(EventArgs e) - { - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.extensions.js"); - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.jquery.tooltip.js"); - ClientResourceManager.RegisterScript(this.Page, "~/Resources/Shared/scripts/dnn.PasswordStrength.js"); - ClientResourceManager.RegisterScript(this.Page, "~/DesktopModules/Admin/Security/Scripts/dnn.PasswordComparer.js"); - - ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Shared/stylesheets/dnn.PasswordStrength.css", FileOrder.Css.ResourceCss); - - JavaScript.RequestRegistration(CommonJs.DnnPlugins); - - base.OnPreRender(e); - - if (Host.EnableStrengthMeter) - { - this.passwordContainer.CssClass = "password-strength-container"; - this.txtPassword.CssClass = "password-strength"; - this.txtConfirm.CssClass = string.Format("{0} checkStength", this.txtConfirm.CssClass); - - var options = new DnnPaswordStrengthOptions(); - var optionsAsJsonString = Json.Serialize(options); - var passwordScript = string.Format( - "dnn.initializePasswordStrength('.{0}', {1});{2}", - "password-strength", optionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(this.Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "PasswordStrength", passwordScript, true); - } - else - { - this.Page.ClientScript.RegisterStartupScript(this.GetType(), "PasswordStrength", passwordScript, true); - } - } - - var confirmPasswordOptions = new DnnConfirmPasswordOptions() - { - FirstElementSelector = "#" + this.passwordContainer.ClientID + " input[type=password]", - SecondElementSelector = ".password-confirm", - ContainerSelector = ".dnnFormPassword", - UnmatchedCssClass = "unmatched", - MatchedCssClass = "matched", - }; - - var confirmOptionsAsJsonString = Json.Serialize(confirmPasswordOptions); - var confirmScript = string.Format("dnn.initializePasswordComparer({0});{1}", confirmOptionsAsJsonString, Environment.NewLine); - - if (ScriptManager.GetCurrent(this.Page) != null) - { - // respect MS AJAX - ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ConfirmPassword", confirmScript, true); - } - else - { - this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ConfirmPassword", confirmScript, true); - } - } - /// ----------------------------------------------------------------------------- /// /// cmdDelete_Click runs when the delete Button is clicked. diff --git a/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs index 21b52b444a5..6c47b23a17f 100644 --- a/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/Security/Users.ascx.cs @@ -37,6 +37,5 @@ namespace DotNetNuke.Modules.Admin.Users /// /// public partial class Users : UserUserControlBase - { - } + {} } diff --git a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs index 50fc2e80b8b..66f6322e664 100644 --- a/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/UrlManagement/UrlProviderSettings.ascx.cs @@ -16,7 +16,7 @@ namespace DotNetNuke.Modules.UrlManagement public partial class ProviderSettings : ModuleUserControlBase { private readonly INavigationManager _navigationManager; - + private int _providerId; private IExtensionUrlProviderSettingsControl _providerSettingsControl; @@ -24,7 +24,7 @@ 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; - - // ReSharper restore SuspiciousTypeConversion.Global + this.providerSettingsPlaceHolder.Controls.Add(settingsControl); + + // ReSharper disable SuspiciousTypeConversion.Global + this._providerSettingsControl = settingsControl as IExtensionUrlProviderSettingsControl; + + // 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 feff0931bed..5463c3d0d9a 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/Settings.ascx.cs @@ -12,7 +12,7 @@ namespace DotNetNuke.Modules.Admin.Users using DotNetNuke.UI.Utilities; public partial class ViewProfileSettings : ModuleSettingsBase - { + { public override void LoadSettings() { try @@ -26,7 +26,7 @@ public override void LoadSettings() { this.txtTemplate.Text = (string)this.TabModuleSettings["ProfileTemplate"]; } - + if (this.Settings.ContainsKey("IncludeButton")) { this.IncludeButton.Checked = Convert.ToBoolean(this.Settings["IncludeButton"]); @@ -52,14 +52,14 @@ public override void UpdateSettings() // Module failed to load 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) { this.txtTemplate.Text = Localization.GetString("DefaultTemplate", this.LocalResourceFile); diff --git a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs index bae8ffe01ac..e5ef15ff3e2 100644 --- a/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs +++ b/DNN Platform/Website/DesktopModules/Admin/ViewProfile/ViewProfile.ascx.cs @@ -29,7 +29,7 @@ namespace DotNetNuke.Modules.Admin.ViewProfile public partial class ViewProfile : ProfileModuleUserControlBase { private readonly INavigationManager _navigationManager; - + public ViewProfile() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); @@ -52,13 +52,13 @@ public bool IncludeButton { includeButton = Convert.ToBoolean(this.ModuleContext.Settings["IncludeButton"]); } - + return includeButton; } } - public string ProfileProperties { get; set; } - + public string ProfileProperties { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -98,7 +98,7 @@ protected override void OnLoad(EventArgs e) { template = Localization.GetString("DefaultTemplate", this.LocalResourceFile); } - + var editUrl = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=1"); var profileUrl = this._navigationManager.NavigateURL(this.ModuleContext.PortalSettings.ActiveTab.TabID, "Profile", "userId=" + this.ProfileUserId, "pageno=2"); @@ -109,7 +109,7 @@ protected override void OnLoad(EventArgs e) string editHyperLink = string.Format("{1}", profileUrl, this.LocalizeString("Edit")); template = template.Replace("[BUTTON:EDITPROFILE]", editHyperLink); } - + this.buttonPanel.Visible = false; } else @@ -117,7 +117,7 @@ protected override void OnLoad(EventArgs e) this.buttonPanel.Visible = this.IncludeButton; this.editLink.NavigateUrl = editUrl; } - + if (template.Contains("[HYPERLINK:EDITPROFILE]")) { if (this.IsUser) @@ -126,7 +126,7 @@ protected override void OnLoad(EventArgs e) template = template.Replace("[HYPERLINK:EDITPROFILE]", editHyperLink); } } - + if (template.Contains("[HYPERLINK:MYACCOUNT]")) { if (this.IsUser) @@ -134,7 +134,7 @@ protected override void OnLoad(EventArgs e) string editHyperLink = string.Format("{1}", editUrl, this.LocalizeString("MyAccount")); template = template.Replace("[HYPERLINK:MYACCOUNT]", editHyperLink); } - + this.buttonPanel.Visible = false; } @@ -171,14 +171,14 @@ protected override void OnLoad(EventArgs e) foreach (ProfilePropertyDefinition property in this.ProfileUser.Profile.ProfileProperties) { var displayDataType = ProfilePropertyAccess.DisplayDataType(property).ToLowerInvariant(); - string value = propertyAccess.GetProperty( + string value = propertyAccess.GetProperty( property.PropertyName, string.Empty, Thread.CurrentThread.CurrentUICulture, this.ModuleContext.PortalSettings.UserInfo, Scope.DefaultSettings, ref propertyNotFound); - + var clientName = Localization.GetSafeJSString(property.PropertyName); sb.Append("self['" + clientName + "'] = ko.observable("); sb.Append("\""); @@ -193,7 +193,7 @@ protected override void OnLoad(EventArgs e) .Replace("//", string.Empty) .Replace(":||", "://"); // restore http protocols } - + sb.Append(value + "\"" + ");"); sb.Append('\n'); sb.Append("self['" + clientName + "Text'] = '"); @@ -214,7 +214,7 @@ protected override void OnLoad(EventArgs e) sb.Append("self.EmailText = '"); sb.Append(this.LocalizeString("Email") + "';"); sb.Append('\n'); - + this.ProfileProperties = sb.ToString(); } catch (Exception exc) @@ -222,8 +222,8 @@ protected override void OnLoad(EventArgs e) // Module failed to load Exceptions.ProcessModuleLoadException(this, exc); } - } - + } + private string GetRedirectUrl() { // redirect user to default page if not specific the home tab, do this action to prevent loop redirect. @@ -253,12 +253,12 @@ private void ProcessQuerystring() string loginUrl = Common.Globals.LoginURL(this.Request.RawUrl, false); this.Response.Redirect(loginUrl); } - + if (this.Request.IsAuthenticated && !string.IsNullOrEmpty(action)) // only process this for authenticated requests { // current user, i.e. the one that the request was for var currentUser = UserController.Instance.GetCurrentUserInfo(); - + // the initiating user,i.e. the one who wanted to be friend // note that in this case here currentUser is visiting the profile of initiatingUser, most likely from a link in the notification e-mail var initiatingUser = UserController.Instance.GetUserById(PortalSettings.Current.PortalId, Convert.ToInt32(this.Request.QueryString["UserID"])); @@ -299,6 +299,6 @@ private void ProcessQuerystring() this.Response.Redirect(Common.Globals.UserProfileURL(initiatingUser.UserID)); } - } + } } } diff --git a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs index 35f08506e51..1b202efe982 100644 --- a/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs +++ b/DNN Platform/Website/DesktopModules/AuthenticationServices/DNN/Login.ascx.cs @@ -35,8 +35,8 @@ public partial class Login : AuthenticationLoginBase public Login() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + /// /// Gets a value indicating whether check if the Auth System is Enabled (for the Portal). /// @@ -47,8 +47,8 @@ public override bool Enabled { return AuthenticationConfig.GetConfig(this.PortalId).Enabled; } - } - + } + /// /// Gets a value indicating whether gets whether the Captcha control is used to validate the login. /// @@ -58,8 +58,8 @@ protected bool UseCaptcha { return AuthenticationConfig.GetConfig(this.PortalId).UseCaptcha; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -72,7 +72,7 @@ protected override void OnLoad(EventArgs e) { this.liRegister.Visible = false; } - + this.lblLogin.Text = Localization.GetSystemMessage(this.PortalSettings, "MESSAGE_LOGIN_INSTRUCTIONS"); if (string.IsNullOrEmpty(this.lblLogin.Text)) { @@ -92,7 +92,7 @@ protected override void OnLoad(EventArgs e) { returnUrl = this.Request.QueryString["returnurl"]; } - + returnUrl = HttpUtility.UrlEncode(returnUrl); url = Globals.RegisterURL(returnUrl, Null.NullString); @@ -110,7 +110,7 @@ protected override void OnLoad(EventArgs e) // see if the portal supports persistant cookies this.chkCookie.Visible = Host.RememberCheckbox; - + // no need to show password link if feature is disabled, let's check this first if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { @@ -125,7 +125,7 @@ protected override void OnLoad(EventArgs e) { this.passwordLink.Visible = false; } - + if (!this.IsPostBack) { if (!string.IsNullOrEmpty(this.Request.QueryString["verificationcode"]) && this.PortalSettings.UserRegistration == (int)Globals.PortalRegistrationType.VerifiedRegistration) @@ -136,7 +136,7 @@ protected override void OnLoad(EventArgs e) } var verificationCode = this.Request.QueryString["verificationcode"]; - + try { UserController.VerifyUser(verificationCode.Replace(".", "+").Replace("-", "/").Replace("_", "=")); @@ -195,7 +195,7 @@ protected override void OnLoad(EventArgs e) Logger.Error(ex); } } - + try { Globals.SetFormFocus(string.IsNullOrEmpty(this.txtUsername.Text) ? this.txtUsername : this.txtPassword); @@ -224,7 +224,7 @@ 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; @@ -245,7 +245,7 @@ protected string GetRedirectUrl(bool checkSettings = true) if (redirectUrl.Contains("?returnurl")) { - string baseURL = redirectUrl.Substring( + string baseURL = redirectUrl.Substring( 0, redirectUrl.IndexOf("?returnurl", StringComparison.Ordinal)); string returnURL = @@ -254,7 +254,7 @@ protected string GetRedirectUrl(bool checkSettings = true) redirectUrl = string.Concat(baseURL, "?returnurl", HttpUtility.UrlEncode(returnURL)); } } - + if (string.IsNullOrEmpty(redirectUrl)) { // redirect to current page @@ -263,14 +263,14 @@ protected string GetRedirectUrl(bool checkSettings = true) } return redirectUrl; - } + } private void OnLoginClick(object sender, EventArgs e) { if ((this.UseCaptcha && this.ctlCaptcha.IsValid) || !this.UseCaptcha) { var loginStatus = UserLoginStatus.LOGIN_FAILURE; - string userName = PortalSecurity.Instance.InputFilter( + string userName = PortalSecurity.Instance.InputFilter( this.txtUsername.Text, PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoAngleBrackets | @@ -312,14 +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); } - } + } } } diff --git a/DNN Platform/Website/ErrorPage.aspx.cs b/DNN Platform/Website/ErrorPage.aspx.cs index 58de87edc27..791155ae956 100644 --- a/DNN Platform/Website/ErrorPage.aspx.cs +++ b/DNN Platform/Website/ErrorPage.aspx.cs @@ -55,12 +55,12 @@ protected override void OnLoad(EventArgs e) this.headerImage.ImageUrl = FileManager.Instance.GetUrl(fileInfo); } } - + this.headerImage.Visible = !string.IsNullOrEmpty(this.headerImage.ImageUrl); string localizedMessage; var security = PortalSecurity.Instance; - var status = security.InputFilter( + var status = security.InputFilter( this.Request.QueryString["status"], PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.NoMarkup); @@ -96,12 +96,12 @@ protected override void OnLoad(EventArgs e) this.Response.StatusCode = 500; } - + localizedMessage = Localization.GetString("Return.Text", Localization.GlobalResourceFile); this.hypReturn.Text = localizedMessage; } - + private void ManageError(string status) { string errorMode = Config.GetCustomErrorMode(); diff --git a/DNN Platform/Website/Install/Install.aspx.cs b/DNN Platform/Website/Install/Install.aspx.cs index 26ce9cf58f4..5d37a6ac6c8 100644 --- a/DNN Platform/Website/Install/Install.aspx.cs +++ b/DNN Platform/Website/Install/Install.aspx.cs @@ -30,8 +30,8 @@ namespace DotNetNuke.Services.Install public partial class Install : Page { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(Install)); - private static readonly object installLocker = new object(); - + private static readonly object installLocker = new object(); + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -53,7 +53,7 @@ protected override void OnLoad(EventArgs e) { base.OnLoad(e); Config.AddFCNMode(Config.FcnMode.Single); - + // Get current Script time-out int scriptTimeOut = this.Server.ScriptTimeout; @@ -104,7 +104,7 @@ protected override void OnLoad(EventArgs e) this.ExecuteScripts(); break; } - + break; case Globals.UpgradeStatus.Error: this.NoUpgrade(); @@ -114,7 +114,7 @@ protected override void OnLoad(EventArgs e) // restore Script timeout this.Server.ScriptTimeout = scriptTimeOut; } - } + } private static void RegisterInstallBegining() { @@ -125,7 +125,7 @@ private static void RegisterInstallEnd() { InstallBlocker.Instance.RegisterInstallEnd(); } - + private void ExecuteScripts() { // Start Timer @@ -142,7 +142,7 @@ private void ExecuteScripts() { Upgrade.Upgrade.ExecuteScripts(strProviderPath); } - + this.Response.Write("

    Execution Complete

    "); this.Response.Flush(); @@ -200,7 +200,7 @@ private void InstallApplication() { return; } - + // Add the install blocker logic lock (installLocker) { @@ -210,20 +210,20 @@ private void InstallApplication() this.WriteInstallationInProgress(); return; } - + RegisterInstallBegining(); } var installConfig = InstallController.Instance.GetInstallConfig(); - + // Create Folder Mappings config if (!string.IsNullOrEmpty(installConfig.FolderMappingsSettings)) { FolderMappingsConfigController.Instance.SaveConfig(installConfig.FolderMappingsSettings); } - + Upgrade.Upgrade.InstallDNN(strProviderPath); - + // remove en-US from portal if installing in a different language if (!installConfig.InstallCulture.Equals("en-us", StringComparison.InvariantCultureIgnoreCase)) { @@ -298,7 +298,7 @@ private void WriteInstallationHeader() private void WriteInstallationInProgress() { - HtmlUtils.WriteFeedback( + HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, Localization.GetString("ThereIsAInstallationCurrentlyInProgress.Error", Localization.GlobalResourceFile) + "
    "); @@ -308,7 +308,7 @@ private void WriteInstallationInProgress() private bool CheckPermissions() { bool verified = new FileSystemPermissionVerifier(this.Server.MapPath("~")).VerifyAll(); - HtmlUtils.WriteFeedback( + HtmlUtils.WriteFeedback( HttpContext.Current.Response, 0, "Checking File and Folder permissions " + (verified ? "Success" : "Error!") + "
    "); @@ -343,7 +343,7 @@ private void UpgradeApplication() this.WriteInstallationInProgress(); return; } - + RegisterInstallBegining(); } @@ -375,7 +375,7 @@ private void UpgradeApplication() { ignoreWarning = this.Request.QueryString["ignoreWarning"].ToLowerInvariant(); } - + strWarning = Upgrade.Upgrade.CheckUpgrade(); } else @@ -412,7 +412,7 @@ private void UpgradeApplication() { Logger.Error(strError); } - + this.Response.Write("

    Upgrade Complete

    "); this.Response.Write("

    Click Here To Access Your Site



    "); @@ -425,7 +425,7 @@ private void UpgradeApplication() this.Response.Write("

    Click Here To Proceed With The Upgrade."); } - + this.Response.Flush(); } else @@ -537,7 +537,7 @@ private void NoUpgrade() HtmlUtils.WriteHeader(this.Response, "none"); string currentAssembly = DotNetNukeContext.Current.Application.Version.ToString(3); string currentDatabase = dr["Major"] + "." + dr["Minor"] + "." + dr["Build"]; - + // do not show versions if the same to stop information leakage if (currentAssembly == currentDatabase) { @@ -546,7 +546,7 @@ private void NoUpgrade() else { this.Response.Write("

    Current Assembly Version: " + currentAssembly + "

    "); - + // Call Upgrade with the current DB Version to upgrade an // existing DNN installation var strDatabaseVersion = ((int)dr["Major"]).ToString("00") + "." + ((int)dr["Minor"]).ToString("00") + "." + ((int)dr["Build"]).ToString("00"); @@ -566,7 +566,7 @@ private void NoUpgrade() this.Response.Write("

    Click Here To Install DotNetNuke

    "); this.Response.Flush(); } - + dr.Close(); } } @@ -593,6 +593,6 @@ private void NoUpgrade() // Write out Footer HtmlUtils.WriteFooter(this.Response); - } + } } } diff --git a/DNN Platform/Website/Install/InstallWizard.aspx.cs b/DNN Platform/Website/Install/InstallWizard.aspx.cs index ca9e6f153fa..a8420e11096 100644 --- a/DNN Platform/Website/Install/InstallWizard.aspx.cs +++ b/DNN Platform/Website/Install/InstallWizard.aspx.cs @@ -144,6 +144,22 @@ protected XmlDocument InstallTemplate } } + /// + /// Gets a value indicating whether localization is supported. + /// + protected bool SupportLocalization + { + get { return installConfig.SupportLocalization; } + } + + /// + /// Gets a value indicating whether the user needs to accept the license terms. + /// + protected bool NeedAcceptTerms + { + get { return File.Exists(Path.Combine(Globals.ApplicationMapPath, "Licenses\\Dnn_Corp_License.pdf")); } + } + /// /// Gets or sets a value indicating whether the permissions are valid. /// @@ -210,22 +226,6 @@ protected string Versions } } - /// - /// Gets a value indicating whether localization is supported. - /// - protected bool SupportLocalization - { - get { return installConfig.SupportLocalization; } - } - - /// - /// Gets a value indicating whether the user needs to accept the license terms. - /// - protected bool NeedAcceptTerms - { - get { return File.Exists(Path.Combine(Globals.ApplicationMapPath, "Licenses\\Dnn_Corp_License.pdf")); } - } - private static string StatusFile { get diff --git a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs index 7dc8229cf84..7137b10a7ff 100644 --- a/DNN Platform/Website/Install/UpgradeWizard.aspx.cs +++ b/DNN Platform/Website/Install/UpgradeWizard.aspx.cs @@ -36,7 +36,7 @@ namespace DotNetNuke.Services.Install /// /// ----------------------------------------------------------------------------- public partial class UpgradeWizard : PageBase - { + { 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"; @@ -45,13 +45,28 @@ public partial class UpgradeWizard : PageBase private static IInstallationStep _currentStep; private static bool _upgradeRunning; - private static int _upgradeProgress; - - // steps shown in UI + 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(); - + + // Ordered List of Steps (and weight in percentage) to be executed + private static IDictionary _steps = new Dictionary + { + // {new AddFcnModeStep(), 1}, + { iisVerification, 1 }, + { upgradeDatabase, 49 }, + { upgradeExtensions, 49 }, + { new InstallVersionStep(), 1 }, + }; + + static UpgradeWizard() + { + IsAuthenticated = false; + } + protected Version ApplicationVersion { get @@ -71,8 +86,8 @@ protected Version CurrentVersion protected bool NeedAcceptTerms { get { return File.Exists(Path.Combine(Globals.ApplicationMapPath, "Licenses\\Dnn_Corp_License.pdf")); } - } - + } + private static string StatusFile { get @@ -81,8 +96,80 @@ private static string StatusFile } } - private static bool IsAuthenticated { get; set; } - + private static bool IsAuthenticated { get; set; } + + [System.Web.Services.WebMethod] + public static Tuple ValidateInput(Dictionary accountInfo) + { + string errorMsg; + var result = VerifyHostUser(accountInfo, out errorMsg); + + return new Tuple(result, errorMsg); + } + + [System.Web.Services.WebMethod] + public static void RunUpgrade(Dictionary accountInfo) + { + string errorMsg; + var result = VerifyHostUser(accountInfo, out errorMsg); + + if (result == true) + { + _upgradeRunning = false; + LaunchUpgrade(); + + // DNN-8833: Must run this after all other upgrade steps are done; sequence is important. + HostController.Instance.Update("DnnImprovementProgram", accountInfo["dnnImprovementProgram"], false); + + // DNN-9355: reset the installer files check flag after each upgrade, to make sure the installer files removed. + HostController.Instance.Update("InstallerFilesRemoved", "False", true); + } + } + + [System.Web.Services.WebMethod] + public static object GetInstallationLog(int startRow) + { + if (IsAuthenticated == false) + { + return string.Empty; + } + + var data = string.Empty; + string logFile = "InstallerLog" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".resources"; + try + { + var lines = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Portals", "_default", "logs", logFile)); + var errorLogged = false; + if (lines.Length > startRow) + { + var count = lines.Length - startRow > 500 ? 500 : lines.Length - startRow; + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + for (var i = startRow; i < startRow + count; i++) + { + if (lines[i].Contains("[ERROR]")) + { + sb.Append(lines[i]); + sb.Append("
    "); + errorLogged = true; + } + } + + data = sb.ToString(); + } + + if (errorLogged == false) + { + Localization.GetString("NoErrorsLogged", "~/Install/App_LocalResources/InstallWizard.aspx.resx"); + } + } + catch (Exception) + { + // ignore + } + + return data; + } + protected string LocalizeString(string key) { return Localization.GetString(key, LocalResourceFile, _culture); @@ -92,7 +179,65 @@ protected override void OnError(EventArgs e) { HttpContext.Current.Response.Clear(); HttpContext.Current.Server.Transfer("~/ErrorPage.aspx"); - } + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Init runs when the Page is initialised. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnInit(EventArgs e) + { + base.OnInit(e); + + if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) + { + this.Response.Redirect(this.Request.RawUrl, true); + } + + this.SslRequiredCheck(); + GetInstallerLocales(); + } + + /// ----------------------------------------------------------------------------- + /// + /// Page_Load runs when the Page loads. + /// + /// + /// + /// ----------------------------------------------------------------------------- + protected override void OnLoad(EventArgs e) + { + if (InstallBlocker.Instance.IsInstallInProgress()) + { + this.Response.Redirect("Install.aspx", true); + } + + base.OnLoad(e); + + this.pnlAcceptTerms.Visible = this.NeedAcceptTerms; + this.LocalizePage(); + + if (this.Request.RawUrl.EndsWith("?complete")) + { + this.CompleteUpgrade(); + } + + // Create Status Files + if (!this.Page.IsPostBack) + { + // Reset the accept terms flag + HostController.Instance.Update("AcceptDnnTerms", "N"); + if (!File.Exists(StatusFile)) + { + File.CreateText(StatusFile).Close(); + } + + Upgrade.Upgrade.RemoveInvalidAntiForgeryCookie(); + } + } private static void GetInstallerLocales() { @@ -113,7 +258,7 @@ private static void GetInstallerLocales() { _supportedLanguages.SetValue(nav.GetAttribute("key", string.Empty), i); } - + i++; } } @@ -143,30 +288,30 @@ private static void LaunchUpgrade() // Set Script timeout to MAX value HttpContext.Current.Server.ScriptTimeout = int.MaxValue; - if (_culture != null) - { - Thread.CurrentThread.CurrentUICulture = new CultureInfo(_culture); - } - - // bail out early if upgrade is in progress - if (_upgradeRunning) - { - return; - } - + if (_culture != null) + { + Thread.CurrentThread.CurrentUICulture = new CultureInfo(_culture); + } + + // bail out early if upgrade is in progress + if (_upgradeRunning) + { + return; + } + var percentForEachStep = 100 / _steps.Count; var useGenericPercent = false; var totalPercent = _steps.Sum(step => step.Value); - if (totalPercent != 100) - { - useGenericPercent = true; - } - + if (totalPercent != 100) + { + useGenericPercent = true; + } + _upgradeRunning = true; _upgradeProgress = 0; // Output the current time for the user - CurrentStepActivity(string.Concat( + CurrentStepActivity(string.Concat( Localization.GetString("UpgradeStarted", LocalResourceFile), ":", DateTime.Now.ToString())); @@ -185,7 +330,7 @@ private static void LaunchUpgrade() _upgradeRunning = false; return; } - + switch (_currentStep.Status) { case StepStatus.AppRestart: @@ -195,24 +340,24 @@ private static void LaunchUpgrade() default: if (_currentStep.Status != StepStatus.Done) { - CurrentStepActivity(string.Format( + CurrentStepActivity(string.Format( Localization.GetString("ErrorInStep", LocalResourceFile), _currentStep.Errors.Count > 0 ? string.Join(",", _currentStep.Errors.ToArray()) : _currentStep.Details)); _upgradeRunning = false; return; } - + break; } - - if (useGenericPercent) - { - _upgradeProgress += percentForEachStep; - } - else - { - _upgradeProgress += step.Value; - } + + if (useGenericPercent) + { + _upgradeProgress += percentForEachStep; + } + else + { + _upgradeProgress += step.Value; + } } _currentStep = null; @@ -225,7 +370,66 @@ private static void LaunchUpgrade() // restore Script timeout HttpContext.Current.Server.ScriptTimeout = scriptTimeOut; } - + + private static void CurrentStepActivity(string status) + { + var percentage = (_currentStep == null) ? _upgradeProgress : _upgradeProgress + (_currentStep.Percentage / _steps.Count); + var obj = new + { + progress = percentage, + details = status, + check0 = upgradeDatabase.Status.ToString() + (upgradeDatabase.Errors.Count == 0 ? string.Empty : " Errors " + upgradeDatabase.Errors.Count), + check1 = upgradeExtensions.Status.ToString() + (upgradeExtensions.Errors.Count == 0 ? string.Empty : " Errors " + upgradeExtensions.Errors.Count), + }; + + try + { + if (!File.Exists(StatusFile)) + { + File.CreateText(StatusFile); + } + + using (var sw = new StreamWriter(StatusFile, true)) + { + sw.WriteLine(obj.ToJson()); + sw.Close(); + } + } + catch (Exception) + { + // TODO - do something + } + } + + 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; + } + private void LocalizePage() { this.SetBrowserLanguage(); @@ -269,36 +473,6 @@ private void SetBrowserLanguage() Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCode); } - private static void CurrentStepActivity(string status) - { - var percentage = (_currentStep == null) ? _upgradeProgress : _upgradeProgress + (_currentStep.Percentage / _steps.Count); - var obj = new - { - progress = percentage, - details = status, - check0 = upgradeDatabase.Status.ToString() + (upgradeDatabase.Errors.Count == 0 ? string.Empty : " Errors " + upgradeDatabase.Errors.Count), - check1 = upgradeExtensions.Status.ToString() + (upgradeExtensions.Errors.Count == 0 ? string.Empty : " Errors " + upgradeExtensions.Errors.Count), - }; - - try - { - if (!File.Exists(StatusFile)) - { - File.CreateText(StatusFile); - } - - using (var sw = new StreamWriter(StatusFile, true)) - { - sw.WriteLine(obj.ToJson()); - sw.Close(); - } - } - catch (Exception) - { - // TODO - do something - } - } - private void CompleteUpgrade() { // Delete the status file. @@ -332,186 +506,12 @@ private void SslRequiredCheck() sslDomain = sslDomain.Substring(sslDomain.IndexOf("://") + 3); } - var sslUrl = string.Format( + var sslUrl = string.Format( "https://{0}{1}", sslDomain, this.Request.RawUrl); this.Response.Redirect(sslUrl, true); } - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Init runs when the Page is initialised. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnInit(EventArgs e) - { - base.OnInit(e); - - if (Upgrade.Upgrade.UpdateNewtonsoftVersion()) - { - this.Response.Redirect(this.Request.RawUrl, true); - } - - this.SslRequiredCheck(); - GetInstallerLocales(); - } - - /// ----------------------------------------------------------------------------- - /// - /// Page_Load runs when the Page loads. - /// - /// - /// - /// ----------------------------------------------------------------------------- - protected override void OnLoad(EventArgs e) - { - if (InstallBlocker.Instance.IsInstallInProgress()) - { - this.Response.Redirect("Install.aspx", true); - } - - base.OnLoad(e); - - this.pnlAcceptTerms.Visible = this.NeedAcceptTerms; - this.LocalizePage(); - - if (this.Request.RawUrl.EndsWith("?complete")) - { - this.CompleteUpgrade(); - } - - // Create Status Files - if (!this.Page.IsPostBack) - { - // Reset the accept terms flag - HostController.Instance.Update("AcceptDnnTerms", "N"); - if (!File.Exists(StatusFile)) - { - File.CreateText(StatusFile).Close(); - } - - Upgrade.Upgrade.RemoveInvalidAntiForgeryCookie(); - } - } - - // Ordered List of Steps (and weight in percentage) to be executed - private static IDictionary _steps = new Dictionary - { - // {new AddFcnModeStep(), 1}, - { iisVerification, 1 }, - { upgradeDatabase, 49 }, - { upgradeExtensions, 49 }, - { new InstallVersionStep(), 1 }, - }; - - static UpgradeWizard() - { - IsAuthenticated = false; - } - - [System.Web.Services.WebMethod] - public static Tuple ValidateInput(Dictionary accountInfo) - { - string errorMsg; - var result = VerifyHostUser(accountInfo, out errorMsg); - - return new Tuple(result, errorMsg); - } - - [System.Web.Services.WebMethod] - public static void RunUpgrade(Dictionary accountInfo) - { - string errorMsg; - var result = VerifyHostUser(accountInfo, out errorMsg); - - if (result == true) - { - _upgradeRunning = false; - LaunchUpgrade(); - - // DNN-8833: Must run this after all other upgrade steps are done; sequence is important. - HostController.Instance.Update("DnnImprovementProgram", accountInfo["dnnImprovementProgram"], false); - - // DNN-9355: reset the installer files check flag after each upgrade, to make sure the installer files removed. - HostController.Instance.Update("InstallerFilesRemoved", "False", true); - } - } - - [System.Web.Services.WebMethod] - public static object GetInstallationLog(int startRow) - { - if (IsAuthenticated == false) - { - return string.Empty; - } - - var data = string.Empty; - string logFile = "InstallerLog" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".resources"; - try - { - var lines = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Portals", "_default", "logs", logFile)); - var errorLogged = false; - if (lines.Length > startRow) - { - var count = lines.Length - startRow > 500 ? 500 : lines.Length - startRow; - System.Text.StringBuilder sb = new System.Text.StringBuilder(); - for (var i = startRow; i < startRow + count; i++) - { - if (lines[i].Contains("[ERROR]")) - { - sb.Append(lines[i]); - sb.Append("
    "); - errorLogged = true; - } - } - - data = sb.ToString(); - } - - if (errorLogged == false) - { - Localization.GetString("NoErrorsLogged", "~/Install/App_LocalResources/InstallWizard.aspx.resx"); - } - } - catch (Exception) - { - // ignore - } - - 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/Install/WizardUser.ascx.cs b/DNN Platform/Website/Install/WizardUser.ascx.cs index 302a2a4a71d..ca2afacd300 100644 --- a/DNN Platform/Website/Install/WizardUser.ascx.cs +++ b/DNN Platform/Website/Install/WizardUser.ascx.cs @@ -19,7 +19,7 @@ public string FirstName { return this.txtFirstName.Text; } - + set { this.txtFirstName.Text = value; @@ -32,7 +32,7 @@ public string LastName { return this.txtLastName.Text; } - + set { this.txtLastName.Text = value; @@ -45,7 +45,7 @@ public string UserName { return this.txtUserName.Text; } - + set { this.txtUserName.Text = value; @@ -58,7 +58,7 @@ public string Password { return this.txtPassword.Text; } - + set { this.txtPassword.Text = value; @@ -71,7 +71,7 @@ public string Confirm { return this.txtConfirm.Text; } - + set { this.txtConfirm.Text = value; @@ -84,7 +84,7 @@ public string Email { return this.txtEmail.Text; } - + set { this.txtEmail.Text = value; @@ -97,7 +97,7 @@ public string FirstNameLabel { return this.lblFirstName.Text; } - + set { this.lblFirstName.Text = value; @@ -110,7 +110,7 @@ public string LastNameLabel { return this.lblLastName.Text; } - + set { this.lblLastName.Text = value; @@ -123,7 +123,7 @@ public string UserNameLabel { return this.lblUserName.Text; } - + set { this.lblUserName.Text = value; @@ -136,7 +136,7 @@ public string PasswordLabel { return this.lblPassword.Text; } - + set { this.lblPassword.Text = value; @@ -149,7 +149,7 @@ public string ConfirmLabel { return this.lblConfirm.Text; } - + set { this.lblConfirm.Text = value; @@ -162,7 +162,7 @@ public string EmailLabel { return this.lblEmail.Text; } - + set { this.lblEmail.Text = value; @@ -196,7 +196,7 @@ public string Validate() { strErrorMessage = "InValidEmail"; } - + return strErrorMessage; } diff --git a/DNN Platform/Website/KeepAlive.aspx.cs b/DNN Platform/Website/KeepAlive.aspx.cs index 6f451b591f8..9634745ab59 100644 --- a/DNN Platform/Website/KeepAlive.aspx.cs +++ b/DNN Platform/Website/KeepAlive.aspx.cs @@ -21,7 +21,7 @@ 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/Portals/_default/subhost.aspx b/DNN Platform/Website/Portals/_default/subhost.aspx index 8417beb50f8..6812bfba5c3 100644 --- a/DNN Platform/Website/Portals/_default/subhost.aspx +++ b/DNN Platform/Website/Portals/_default/subhost.aspx @@ -1,7 +1,7 @@ <%@ Page Language="C#" %> ", this.ClientID, this.Target); @@ -75,6 +75,6 @@ protected override void Render(HtmlTextWriter writer) writer.RenderEndTag(); writer.RenderEndTag(); - } + } } } diff --git a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs index 0ea8bc9bd8f..c451829fda9 100644 --- a/DNN Platform/Website/admin/Containers/Visibility.ascx.cs +++ b/DNN Platform/Website/admin/Containers/Visibility.ascx.cs @@ -29,17 +29,25 @@ namespace DotNetNuke.UI.Containers /// /// ----------------------------------------------------------------------------- public partial class Visibility : SkinObjectBase - { + { private int _animationFrames = 5; private Panel _pnlModuleContent; - + + public string ResourceFile + { + get + { + return Localization.GetResourceFile(this, "Visibility.ascx"); + } + } + public int AnimationFrames { get { return this._animationFrames; } - + set { this._animationFrames = value; @@ -48,6 +56,42 @@ public int AnimationFrames public string BorderWidth { get; set; } + public bool ContentVisible + { + get + { + switch (this.ModuleControl.ModuleContext.Configuration.Visibility) + { + case VisibilityState.Maximized: + case VisibilityState.Minimized: + return DNNClientAPI.MinMaxContentVisibile( + this.cmdVisibility, + this.ModuleControl.ModuleContext.ModuleId, + this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, + DNNClientAPI.MinMaxPersistanceType.Cookie); + default: + return true; + } + } + + set + { + DNNClientAPI.MinMaxContentVisibile( + this.cmdVisibility, + this.ModuleControl.ModuleContext.ModuleId, + this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, + DNNClientAPI.MinMaxPersistanceType.Cookie, + value); + } + } + + // ReSharper disable InconsistentNaming + // TODO can this be renamed with a capital M + public string minIcon { get; set; } + + // ReSharper restore InconsistentNaming + public string MaxIcon { get; set; } + private string MinIconLoc { get @@ -86,7 +130,7 @@ private Panel ModuleContent this._pnlModuleContent = (Panel)objCtl; } } - + return this._pnlModuleContent; } } @@ -97,50 +141,6 @@ private string ModulePath { return this.ModuleControl.ModuleContext.Configuration.ContainerPath.Substring(0, this.ModuleControl.ModuleContext.Configuration.ContainerPath.LastIndexOf("/") + 1); } - } - - public bool ContentVisible - { - get - { - switch (this.ModuleControl.ModuleContext.Configuration.Visibility) - { - case VisibilityState.Maximized: - case VisibilityState.Minimized: - return DNNClientAPI.MinMaxContentVisibile( - this.cmdVisibility, - this.ModuleControl.ModuleContext.ModuleId, - this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, - DNNClientAPI.MinMaxPersistanceType.Cookie); - default: - return true; - } - } - - set - { - DNNClientAPI.MinMaxContentVisibile( - this.cmdVisibility, - this.ModuleControl.ModuleContext.ModuleId, - this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized, - DNNClientAPI.MinMaxPersistanceType.Cookie, - value); - } - } - - // ReSharper disable InconsistentNaming - // TODO can this be renamed with a capital M - public string minIcon { get; set; } - - // ReSharper restore InconsistentNaming - public string MaxIcon { get; set; } - - public string ResourceFile - { - get - { - return Localization.GetResourceFile(this, "Visibility.ascx"); - } } protected override void OnLoad(EventArgs e) @@ -158,7 +158,7 @@ protected override void OnLoad(EventArgs e) { this.cmdVisibility.BorderWidth = Unit.Parse(this.BorderWidth); } - + if (this.ModuleControl.ModuleContext.Configuration != null) { // check if Personalization is allowed @@ -167,14 +167,14 @@ protected override void OnLoad(EventArgs e) this.cmdVisibility.Enabled = false; this.cmdVisibility.Visible = false; } - + if (this.ModuleControl.ModuleContext.Configuration.Visibility == VisibilityState.Minimized) { // if visibility is set to minimized, then the client needs to set the cookie for maximized only and delete the cookie for minimized, // instead of the opposite. We need to notify the client of this ClientAPI.RegisterClientVariable(this.Page, "__dnn_" + this.ModuleControl.ModuleContext.ModuleId + ":defminimized", "true", true); } - + if (!Globals.IsAdminControl()) { if (this.cmdVisibility.Enabled) @@ -227,7 +227,7 @@ protected override void OnPreRender(EventArgs e) { case VisibilityState.Maximized: case VisibilityState.Minimized: - DNNClientAPI.EnableMinMax( + DNNClientAPI.EnableMinMax( this.cmdVisibility, this.ModuleContent, this.ModuleControl.ModuleContext.ModuleId, @@ -261,6 +261,6 @@ private void cmdVisibility_Click(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs index e97010d15d1..6983489aae1 100644 --- a/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs +++ b/DNN Platform/Website/admin/Menus/ModuleActions/ModuleActions.ascx.cs @@ -35,27 +35,27 @@ public partial class ModuleActions : ActionBase { private readonly List validIDs = new List(); - protected string AdminActionsJSON { get; set; } - protected string AdminText { get { return Localization.GetString("ModuleGenericActions.Action", Localization.GlobalResourceFile); } } - protected string CustomActionsJSON { get; set; } - protected string CustomText { get { return Localization.GetString("ModuleSpecificActions.Action", Localization.GlobalResourceFile); } } - protected bool DisplayQuickSettings { get; set; } - protected string MoveText { get { return Localization.GetString(ModuleActionType.MoveRoot, Localization.GlobalResourceFile); } } + protected string AdminActionsJSON { get; set; } + + protected string CustomActionsJSON { get; set; } + + protected bool DisplayQuickSettings { get; set; } + protected string Panes { get; set; } protected bool SupportsMove { get; set; } @@ -136,7 +136,7 @@ protected override void OnLoad(EventArgs e) { action.Icon = "~/images/" + action.Icon; } - + if (action.Icon.StartsWith("~/")) { action.Icon = Globals.ResolveUrl(action.Icon); @@ -170,7 +170,7 @@ protected override void OnLoad(EventArgs e) } } } - + this.IsShared = this.ModuleContext.Configuration.AllTabs || PortalGroupController.Instance.IsModuleShared(this.ModuleContext.ModuleId, PortalController.Instance.GetPortal(this.PortalSettings.PortalId)) || TabController.Instance.GetTabsByModuleID(this.ModuleContext.ModuleId).Count > 1; diff --git a/DNN Platform/Website/admin/Modules/Export.ascx.cs b/DNN Platform/Website/admin/Modules/Export.ascx.cs index ebdd2fc3292..a302a33c7a3 100644 --- a/DNN Platform/Website/admin/Modules/Export.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Export.ascx.cs @@ -37,14 +37,14 @@ namespace DotNetNuke.Modules.Admin.Modules 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 ModuleInfo Module { @@ -60,8 +60,8 @@ private string ReturnURL { return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -70,7 +70,7 @@ protected override void OnInit(EventArgs e) { int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); } - + if (!ModulePermissionController.HasModuleAccess(SecurityAccessLevel.Edit, "EXPORT", this.Module)) { this.Response.Redirect(Globals.AccessDeniedURL(), true); @@ -89,7 +89,7 @@ protected override void OnLoad(EventArgs e) { int.TryParse(this.Request.QueryString["moduleid"], out this.ModuleId); } - + if (!this.Page.IsPostBack) { this.cmdCancel.NavigateUrl = this.ReturnURL; @@ -108,6 +108,40 @@ protected override void OnLoad(EventArgs e) } } + protected void OnExportClick(object sender, EventArgs e) + { + try + { + IFolderInfo folder = null; + if (this.cboFolders.SelectedItem != null && !string.IsNullOrEmpty(this.txtFile.Text)) + { + folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); + } + + if (folder != null) + { + var strFile = "content." + CleanName(this.Module.DesktopModule.ModuleName) + "." + CleanName(this.txtFile.Text) + ".export"; + var strMessage = this.ExportModule(this.ModuleId, strFile, folder); + if (string.IsNullOrEmpty(strMessage)) + { + this.Response.Redirect(this.ReturnURL, true); + } + else + { + UI.Skins.Skin.AddModuleMessage(this, strMessage, ModuleMessage.ModuleMessageType.RedError); + } + } + else + { + UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); + } + } + catch (Exception exc) + { + Exceptions.ProcessModuleLoadException(this, exc); + } + } + private static string CleanName(string name) { var strName = name; @@ -118,10 +152,10 @@ private static string CleanName(string name) { strName = strName.Replace(strBadChars.Substring(intCounter, 1), string.Empty); } - + return strName; - } - + } + private string ExportModule(int moduleID, string fileName, IFolderInfo folder) { var strMessage = string.Empty; @@ -202,42 +236,8 @@ private string ExportModule(int moduleID, string fileName, IFolderInfo folder) strMessage = Localization.GetString("ExportNotSupported", this.LocalResourceFile); } } - + return strMessage; } - - protected void OnExportClick(object sender, EventArgs e) - { - try - { - IFolderInfo folder = null; - if (this.cboFolders.SelectedItem != null && !string.IsNullOrEmpty(this.txtFile.Text)) - { - folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); - } - - if (folder != null) - { - var strFile = "content." + CleanName(this.Module.DesktopModule.ModuleName) + "." + CleanName(this.txtFile.Text) + ".export"; - var strMessage = this.ExportModule(this.ModuleId, strFile, folder); - if (string.IsNullOrEmpty(strMessage)) - { - this.Response.Redirect(this.ReturnURL, true); - } - else - { - UI.Skins.Skin.AddModuleMessage(this, strMessage, ModuleMessage.ModuleMessageType.RedError); - } - } - else - { - UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("Validation", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); - } - } - catch (Exception exc) - { - Exceptions.ProcessModuleLoadException(this, exc); - } - } } } diff --git a/DNN Platform/Website/admin/Modules/Import.ascx.cs b/DNN Platform/Website/admin/Modules/Import.ascx.cs index 0bda46701c1..cf1215ceadf 100644 --- a/DNN Platform/Website/admin/Modules/Import.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Import.ascx.cs @@ -27,14 +27,14 @@ namespace DotNetNuke.Modules.Admin.Modules 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 ModuleInfo Module { @@ -50,8 +50,8 @@ private string ReturnURL { return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -90,75 +90,6 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - private string ImportModule() - { - var strMessage = string.Empty; - if (this.Module != null) - { - if (!string.IsNullOrEmpty(this.Module.DesktopModule.BusinessControllerClass) && this.Module.DesktopModule.IsPortable) - { - try - { - var objObject = Reflection.CreateObject(this.Module.DesktopModule.BusinessControllerClass, this.Module.DesktopModule.BusinessControllerClass); - if (objObject is IPortable) - { - var xmlDoc = new XmlDocument { XmlResolver = null }; - try - { - var content = XmlUtils.RemoveInvalidXmlCharacters(this.txtContent.Text); - xmlDoc.LoadXml(content); - } - catch - { - strMessage = Localization.GetString("NotValidXml", this.LocalResourceFile); - } - - if (string.IsNullOrEmpty(strMessage)) - { - var strType = xmlDoc.DocumentElement.GetAttribute("type"); - if (strType == Globals.CleanName(this.Module.DesktopModule.ModuleName) || strType == Globals.CleanName(this.Module.DesktopModule.FriendlyName)) - { - var strVersion = xmlDoc.DocumentElement.GetAttribute("version"); - - // DNN26810 if rootnode = "content", import only content(the old way) - if (xmlDoc.DocumentElement.Name.ToLowerInvariant() == "content") - { - ((IPortable)objObject).ImportModule(this.ModuleId, xmlDoc.DocumentElement.InnerXml, strVersion, this.UserInfo.UserID); - } - - // otherwise (="module") import the new way - else - { - ModuleController.DeserializeModule(xmlDoc.DocumentElement, this.Module, this.PortalId, this.TabId); - } - - this.Response.Redirect(this._navigationManager.NavigateURL(), true); - } - else - { - strMessage = Localization.GetString("NotCorrectType", this.LocalResourceFile); - } - } - } - else - { - strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); - } - } - catch - { - strMessage = Localization.GetString("Error", this.LocalResourceFile); - } - } - else - { - strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); - } - } - - return strMessage; - } protected void OnFoldersIndexChanged(object sender, EventArgs e) { @@ -168,18 +99,18 @@ protected void OnFoldersIndexChanged(object sender, EventArgs e) { return; } - + if (this.Module == null) { return; } var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); - if (folder == null) - { - return; - } - + if (folder == null) + { + return; + } + var files = Globals.GetFileList(this.PortalId, "export", false, folder.FolderPath); files.AddRange(Globals.GetFileList(this.PortalId, "xml", false, folder.FolderPath)); foreach (FileItem file in files) @@ -204,23 +135,23 @@ protected void OnFoldersIndexChanged(object sender, EventArgs e) protected void OnFilesIndexChanged(object sender, EventArgs e) { - if (this.cboFolders.SelectedItem == null) - { - return; - } - + if (this.cboFolders.SelectedItem == null) + { + return; + } + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); - if (folder == null) - { - return; - } - + if (folder == null) + { + return; + } + if (string.IsNullOrEmpty(this.cboFiles.SelectedValue) || this.cboFiles.SelectedValue == "-") { this.txtContent.Text = string.Empty; return; } - + try { var fileId = Convert.ToInt32(this.cboFiles.SelectedValue); @@ -257,6 +188,75 @@ protected void OnImportClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } + + private string ImportModule() + { + var strMessage = string.Empty; + if (this.Module != null) + { + if (!string.IsNullOrEmpty(this.Module.DesktopModule.BusinessControllerClass) && this.Module.DesktopModule.IsPortable) + { + try + { + var objObject = Reflection.CreateObject(this.Module.DesktopModule.BusinessControllerClass, this.Module.DesktopModule.BusinessControllerClass); + if (objObject is IPortable) + { + var xmlDoc = new XmlDocument { XmlResolver = null }; + try + { + var content = XmlUtils.RemoveInvalidXmlCharacters(this.txtContent.Text); + xmlDoc.LoadXml(content); + } + catch + { + strMessage = Localization.GetString("NotValidXml", this.LocalResourceFile); + } + + if (string.IsNullOrEmpty(strMessage)) + { + var strType = xmlDoc.DocumentElement.GetAttribute("type"); + if (strType == Globals.CleanName(this.Module.DesktopModule.ModuleName) || strType == Globals.CleanName(this.Module.DesktopModule.FriendlyName)) + { + var strVersion = xmlDoc.DocumentElement.GetAttribute("version"); + + // DNN26810 if rootnode = "content", import only content(the old way) + if (xmlDoc.DocumentElement.Name.ToLowerInvariant() == "content") + { + ((IPortable)objObject).ImportModule(this.ModuleId, xmlDoc.DocumentElement.InnerXml, strVersion, this.UserInfo.UserID); + } + + // otherwise (="module") import the new way + else + { + ModuleController.DeserializeModule(xmlDoc.DocumentElement, this.Module, this.PortalId, this.TabId); + } + + this.Response.Redirect(this._navigationManager.NavigateURL(), true); + } + else + { + strMessage = Localization.GetString("NotCorrectType", this.LocalResourceFile); + } + } + } + else + { + strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); + } + } + catch + { + strMessage = Localization.GetString("Error", this.LocalResourceFile); + } + } + else + { + strMessage = Localization.GetString("ImportNotSupported", this.LocalResourceFile); + } + } + + return strMessage; + } } } diff --git a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs index 1569e249e65..fb31e11186f 100644 --- a/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs +++ b/DNN Platform/Website/admin/Modules/ModulePermissions.ascx.cs @@ -29,14 +29,14 @@ namespace DotNetNuke.Modules.Admin.Modules public partial class ModulePermissions : PortalModuleBase { private readonly INavigationManager _navigationManager; - + private int _moduleId = -1; private ModuleInfo _module; - + public ModulePermissions() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } + } private ModuleInfo Module { @@ -49,8 +49,8 @@ private string ReturnURL { return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -115,6 +115,6 @@ protected void OnUpdateClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs index 9088698f048..479b273c768 100644 --- a/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs +++ b/DNN Platform/Website/admin/Modules/Modulesettings.ascx.cs @@ -138,171 +138,6 @@ protected string GetInstalledOnSite(object dataItem) return returnValue; } - private void BindData() - { - if (this.Module != null) - { - var desktopModule = DesktopModuleController.GetDesktopModule(this.Module.DesktopModuleID, this.PortalId); - this.dgPermissions.ResourceFile = Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + - Localization.LocalSharedResourceFile; - if (!this.Module.IsShared) - { - this.chkInheritPermissions.Checked = this.Module.InheritViewPermissions; - this.dgPermissions.InheritViewPermissionsFromTab = this.Module.InheritViewPermissions; - } - - this.txtFriendlyName.Text = this.Module.DesktopModule.FriendlyName; - this.txtTitle.Text = this.Module.ModuleTitle; - this.ctlIcon.Url = this.Module.IconFile; - - if (this.cboTab.FindItemByValue(this.Module.TabID.ToString()) != null) - { - this.cboTab.FindItemByValue(this.Module.TabID.ToString()).Selected = true; - } - - this.rowTab.Visible = this.cboTab.Items.Count != 1; - this.chkAllTabs.Checked = this.Module.AllTabs; - this.trnewPages.Visible = this.chkAllTabs.Checked; - this.allowIndexRow.Visible = desktopModule.IsSearchable; - this.chkAllowIndex.Checked = this.GetBooleanSetting("AllowIndex", true); - this.txtMoniker.Text = (string)this.Settings["Moniker"] ?? string.Empty; - - this.cboVisibility.SelectedIndex = (int)this.Module.Visibility; - this.chkAdminBorder.Checked = this.Settings["hideadminborder"] != null && bool.Parse(this.Settings["hideadminborder"].ToString()); - - var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(this.Module.ModuleDefID); - if (objModuleDef.DefaultCacheTime == Null.NullInteger) - { - this.cacheWarningRow.Visible = true; - this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); - } - else - { - this.cacheWarningRow.Visible = false; - this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); - } - - this.BindModuleCacheProviderList(); - - this.ShowCacheRows(); - - this.cboAlign.Items.FindByValue(this.Module.Alignment).Selected = true; - this.txtColor.Text = this.Module.Color; - this.txtBorder.Text = this.Module.Border; - - this.txtHeader.Text = this.Module.Header; - this.txtFooter.Text = this.Module.Footer; - - if (!Null.IsNull(this.Module.StartDate)) - { - this.startDatePicker.SelectedDate = this.Module.StartDate; - } - - if (!Null.IsNull(this.Module.EndDate) && this.Module.EndDate <= this.endDatePicker.MaxDate) - { - this.endDatePicker.SelectedDate = this.Module.EndDate; - } - - this.BindContainers(); - - this.chkDisplayTitle.Checked = this.Module.DisplayTitle; - this.chkDisplayPrint.Checked = this.Module.DisplayPrint; - this.chkDisplaySyndicate.Checked = this.Module.DisplaySyndicate; - - this.chkWebSlice.Checked = this.Module.IsWebSlice; - this.webSliceTitle.Visible = this.Module.IsWebSlice; - this.webSliceExpiry.Visible = this.Module.IsWebSlice; - this.webSliceTTL.Visible = this.Module.IsWebSlice; - - this.txtWebSliceTitle.Text = this.Module.WebSliceTitle; - if (!Null.IsNull(this.Module.WebSliceExpiryDate)) - { - this.diWebSliceExpiry.SelectedDate = this.Module.WebSliceExpiryDate; - } - - if (!Null.IsNull(this.Module.WebSliceTTL)) - { - this.txtWebSliceTTL.Text = this.Module.WebSliceTTL.ToString(); - } - - if (this.Module.ModuleID == PortalSettings.Current.DefaultModuleId && this.Module.TabID == PortalSettings.Current.DefaultTabId) - { - this.chkDefault.Checked = true; - } - - if (!this.Module.IsShared && this.Module.DesktopModule.Shareable != ModuleSharing.Unsupported) - { - this.isShareableCheckBox.Checked = this.Module.IsShareable; - this.isShareableViewOnlyCheckBox.Checked = this.Module.IsShareableViewOnly; - this.isShareableRow.Visible = true; - - this.chkInheritPermissions.Visible = true; - } - } - } - - private void BindContainers() - { - this.moduleContainerCombo.PortalId = this.PortalId; - this.moduleContainerCombo.RootPath = SkinController.RootContainer; - this.moduleContainerCombo.Scope = SkinScope.All; - this.moduleContainerCombo.IncludeNoneSpecificItem = true; - this.moduleContainerCombo.NoneSpecificText = "<" + Localization.GetString("None_Specified") + ">"; - this.moduleContainerCombo.SelectedValue = this.Module.ContainerSrc; - } - - private void BindModulePages() - { - var tabsByModule = TabController.Instance.GetTabsByModuleID(this._moduleId); - tabsByModule.Remove(this.TabId); - this.dgOnTabs.DataSource = tabsByModule.Values; - this.dgOnTabs.DataBind(); - } - - private void BindModuleCacheProviderList() - { - this.cboCacheProvider.DataSource = this.GetFilteredProviders(ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider"); - this.cboCacheProvider.DataBind(); - - // cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "")); - this.cboCacheProvider.InsertItem(0, Localization.GetString("None_Specified"), string.Empty); - - // if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null) - if (!string.IsNullOrEmpty(this.Module.GetEffectiveCacheMethod()) && this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()) != null) - { - // cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true; - this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()).Selected = true; - } - else - { - // select the None Specified value - this.cboCacheProvider.Items[0].Selected = true; - } - - this.lblCacheInherited.Visible = this.Module.CacheMethod != this.Module.GetEffectiveCacheMethod(); - } - - private IEnumerable GetFilteredProviders(Dictionary providerList, string keyFilter) - { - var providers = from provider in providerList let filteredkey = provider.Key.Replace(keyFilter, string.Empty) select new { filteredkey, provider.Key }; - - return providers; - } - - private void ShowCacheRows() - { - this.divCacheDuration.Visible = !string.IsNullOrEmpty(this.cboCacheProvider.SelectedValue); - } - - private bool GetBooleanSetting(string settingName, bool defaultValue) - { - var value = this.Settings[settingName]; - - return value == null - ? defaultValue - : bool.Parse(value.ToString()); - } - protected bool IsSharedViewOnly() { return this.ModuleContext.Configuration.IsShared && this.ModuleContext.Configuration.IsShareableViewOnly; @@ -759,5 +594,170 @@ protected void dgOnTabs_PageIndexChanging(object sender, System.Web.UI.WebContro this.dgOnTabs.PageIndex = e.NewPageIndex; this.BindModulePages(); } + + private void BindData() + { + if (this.Module != null) + { + var desktopModule = DesktopModuleController.GetDesktopModule(this.Module.DesktopModuleID, this.PortalId); + this.dgPermissions.ResourceFile = Globals.ApplicationPath + "/DesktopModules/" + desktopModule.FolderName + "/" + Localization.LocalResourceDirectory + "/" + + Localization.LocalSharedResourceFile; + if (!this.Module.IsShared) + { + this.chkInheritPermissions.Checked = this.Module.InheritViewPermissions; + this.dgPermissions.InheritViewPermissionsFromTab = this.Module.InheritViewPermissions; + } + + this.txtFriendlyName.Text = this.Module.DesktopModule.FriendlyName; + this.txtTitle.Text = this.Module.ModuleTitle; + this.ctlIcon.Url = this.Module.IconFile; + + if (this.cboTab.FindItemByValue(this.Module.TabID.ToString()) != null) + { + this.cboTab.FindItemByValue(this.Module.TabID.ToString()).Selected = true; + } + + this.rowTab.Visible = this.cboTab.Items.Count != 1; + this.chkAllTabs.Checked = this.Module.AllTabs; + this.trnewPages.Visible = this.chkAllTabs.Checked; + this.allowIndexRow.Visible = desktopModule.IsSearchable; + this.chkAllowIndex.Checked = this.GetBooleanSetting("AllowIndex", true); + this.txtMoniker.Text = (string)this.Settings["Moniker"] ?? string.Empty; + + this.cboVisibility.SelectedIndex = (int)this.Module.Visibility; + this.chkAdminBorder.Checked = this.Settings["hideadminborder"] != null && bool.Parse(this.Settings["hideadminborder"].ToString()); + + var objModuleDef = ModuleDefinitionController.GetModuleDefinitionByID(this.Module.ModuleDefID); + if (objModuleDef.DefaultCacheTime == Null.NullInteger) + { + this.cacheWarningRow.Visible = true; + this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); + } + else + { + this.cacheWarningRow.Visible = false; + this.txtCacheDuration.Text = this.Module.CacheTime.ToString(); + } + + this.BindModuleCacheProviderList(); + + this.ShowCacheRows(); + + this.cboAlign.Items.FindByValue(this.Module.Alignment).Selected = true; + this.txtColor.Text = this.Module.Color; + this.txtBorder.Text = this.Module.Border; + + this.txtHeader.Text = this.Module.Header; + this.txtFooter.Text = this.Module.Footer; + + if (!Null.IsNull(this.Module.StartDate)) + { + this.startDatePicker.SelectedDate = this.Module.StartDate; + } + + if (!Null.IsNull(this.Module.EndDate) && this.Module.EndDate <= this.endDatePicker.MaxDate) + { + this.endDatePicker.SelectedDate = this.Module.EndDate; + } + + this.BindContainers(); + + this.chkDisplayTitle.Checked = this.Module.DisplayTitle; + this.chkDisplayPrint.Checked = this.Module.DisplayPrint; + this.chkDisplaySyndicate.Checked = this.Module.DisplaySyndicate; + + this.chkWebSlice.Checked = this.Module.IsWebSlice; + this.webSliceTitle.Visible = this.Module.IsWebSlice; + this.webSliceExpiry.Visible = this.Module.IsWebSlice; + this.webSliceTTL.Visible = this.Module.IsWebSlice; + + this.txtWebSliceTitle.Text = this.Module.WebSliceTitle; + if (!Null.IsNull(this.Module.WebSliceExpiryDate)) + { + this.diWebSliceExpiry.SelectedDate = this.Module.WebSliceExpiryDate; + } + + if (!Null.IsNull(this.Module.WebSliceTTL)) + { + this.txtWebSliceTTL.Text = this.Module.WebSliceTTL.ToString(); + } + + if (this.Module.ModuleID == PortalSettings.Current.DefaultModuleId && this.Module.TabID == PortalSettings.Current.DefaultTabId) + { + this.chkDefault.Checked = true; + } + + if (!this.Module.IsShared && this.Module.DesktopModule.Shareable != ModuleSharing.Unsupported) + { + this.isShareableCheckBox.Checked = this.Module.IsShareable; + this.isShareableViewOnlyCheckBox.Checked = this.Module.IsShareableViewOnly; + this.isShareableRow.Visible = true; + + this.chkInheritPermissions.Visible = true; + } + } + } + + private void BindContainers() + { + this.moduleContainerCombo.PortalId = this.PortalId; + this.moduleContainerCombo.RootPath = SkinController.RootContainer; + this.moduleContainerCombo.Scope = SkinScope.All; + this.moduleContainerCombo.IncludeNoneSpecificItem = true; + this.moduleContainerCombo.NoneSpecificText = "<" + Localization.GetString("None_Specified") + ">"; + this.moduleContainerCombo.SelectedValue = this.Module.ContainerSrc; + } + + private void BindModulePages() + { + var tabsByModule = TabController.Instance.GetTabsByModuleID(this._moduleId); + tabsByModule.Remove(this.TabId); + this.dgOnTabs.DataSource = tabsByModule.Values; + this.dgOnTabs.DataBind(); + } + + private void BindModuleCacheProviderList() + { + this.cboCacheProvider.DataSource = this.GetFilteredProviders(ModuleCachingProvider.GetProviderList(), "ModuleCachingProvider"); + this.cboCacheProvider.DataBind(); + + // cboCacheProvider.Items.Insert(0, new ListItem(Localization.GetString("None_Specified"), "")); + this.cboCacheProvider.InsertItem(0, Localization.GetString("None_Specified"), string.Empty); + + // if (!string.IsNullOrEmpty(Module.GetEffectiveCacheMethod()) && cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()) != null) + if (!string.IsNullOrEmpty(this.Module.GetEffectiveCacheMethod()) && this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()) != null) + { + // cboCacheProvider.Items.FindByValue(Module.GetEffectiveCacheMethod()).Selected = true; + this.cboCacheProvider.FindItemByValue(this.Module.GetEffectiveCacheMethod()).Selected = true; + } + else + { + // select the None Specified value + this.cboCacheProvider.Items[0].Selected = true; + } + + this.lblCacheInherited.Visible = this.Module.CacheMethod != this.Module.GetEffectiveCacheMethod(); + } + + private IEnumerable GetFilteredProviders(Dictionary providerList, string keyFilter) + { + var providers = from provider in providerList let filteredkey = provider.Key.Replace(keyFilter, string.Empty) select new { filteredkey, provider.Key }; + + return providers; + } + + private void ShowCacheRows() + { + this.divCacheDuration.Visible = !string.IsNullOrEmpty(this.cboCacheProvider.SelectedValue); + } + + private bool GetBooleanSetting(string settingName, bool defaultValue) + { + var value = this.Settings[settingName]; + + return value == null + ? defaultValue + : bool.Parse(value.ToString()); + } } } diff --git a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs index 213e11bd8c2..75b050c466f 100644 --- a/DNN Platform/Website/admin/Modules/viewsource.ascx.cs +++ b/DNN Platform/Website/admin/Modules/viewsource.ascx.cs @@ -18,12 +18,12 @@ namespace DotNetNuke.Modules.Admin.Modules public partial class ViewSource : PortalModuleBase { private readonly INavigationManager _navigationManager; - + public ViewSource() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + protected bool CanEditSource { get @@ -41,7 +41,7 @@ protected int ModuleControlId { moduleControlId = int.Parse(this.Request.QueryString["ctlid"]); } - + return moduleControlId; } } @@ -52,8 +52,8 @@ private string ReturnURL { return UrlUtils.ValidReturnUrl(this.Request.Params["ReturnURL"]) ?? this._navigationManager.NavigateURL(); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -70,7 +70,7 @@ protected override void OnLoad(EventArgs e) { this.BindFiles(objModuleControl.ControlSrc); } - + if (this.Request.UrlReferrer != null) { this.ViewState["UrlReferrer"] = Convert.ToString(this.Request.UrlReferrer); @@ -80,7 +80,7 @@ protected override void OnLoad(EventArgs e) this.ViewState["UrlReferrer"] = string.Empty; } } - + this.cmdUpdate.Visible = this.CanEditSource; this.txtSource.Enabled = this.CanEditSource; } @@ -89,11 +89,11 @@ protected void OnFileIndexChanged(object sender, EventArgs e) { this.DisplayFile(); } - + private void BindFiles(string controlSrc) { this.cboFile.Items.Clear(); - + // cboFile.Items.Add(new ListItem(Localization.GetString("None_Specified"), "None")); // cboFile.Items.Add(new ListItem("User Control", "UserControl")); this.cboFile.AddItem(Localization.GetString("None_Specified"), "None"); @@ -105,7 +105,7 @@ private void BindFiles(string controlSrc) // cboFile.Items.Add(new ListItem("Code File", "CodeFile")); this.cboFile.AddItem("Code File", "CodeFile"); } - + var fileName = Path.GetFileName(srcPhysicalPath); var folder = Path.GetDirectoryName(srcPhysicalPath); if (File.Exists(folder + "\\App_LocalResources\\" + fileName + ".resx")) @@ -133,7 +133,7 @@ private string GetSourceFileName(string controlSrc) { srcFile = srcPhysicalPath + ".cs"; } - + break; case "ResourceFile": var fileName = Path.GetFileName(srcPhysicalPath); @@ -141,7 +141,7 @@ private string GetSourceFileName(string controlSrc) srcFile = folder + "\\App_LocalResources\\" + fileName + ".resx"; break; } - + return srcFile; } @@ -163,11 +163,11 @@ private void DisplayFile() this.txtSource.Text = objStreamReader.ReadToEnd(); objStreamReader.Close(); } - + this.lblSourceFile.Visible = displaySource; this.trSource.Visible = displaySource; } - } + } private void OnUpdateClick(object sender, EventArgs e) { @@ -193,7 +193,7 @@ private void OnUpdateClick(object sender, EventArgs e) objStream.Close(); } } - + this.Response.Redirect(this.ReturnURL, true); } } @@ -201,6 +201,6 @@ private void OnUpdateClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } } } diff --git a/DNN Platform/Website/admin/Portal/Message.ascx.cs b/DNN Platform/Website/admin/Portal/Message.ascx.cs index 65a2abae9f4..82e220ad897 100644 --- a/DNN Platform/Website/admin/Portal/Message.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Message.ascx.cs @@ -14,7 +14,7 @@ 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 efd08db0c6a..259fa49a8c1 100644 --- a/DNN Platform/Website/admin/Portal/NoContent.ascx.cs +++ b/DNN Platform/Website/admin/Portal/NoContent.ascx.cs @@ -15,7 +15,7 @@ protected override void OnInit(EventArgs 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 9deb5d665e0..353223398a2 100644 --- a/DNN Platform/Website/admin/Portal/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Privacy.ascx.cs @@ -18,7 +18,7 @@ namespace DotNetNuke.Common.Controls /// /// ----------------------------------------------------------------------------- public partial class Privacy : PortalModuleBase - { + { protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -49,10 +49,10 @@ 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 3127e83a9a5..1b1b3bef8f8 100644 --- a/DNN Platform/Website/admin/Portal/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Portal/Terms.ascx.cs @@ -10,11 +10,11 @@ namespace DotNetNuke.Common.Controls using DotNetNuke.Services.Localization; public partial class Terms : PortalModuleBase - { + { protected override void OnInit(EventArgs e) { base.OnInit(e); - + // CODEGEN: This method call is required by the Web Form Designer // Do not modify it using the code editor. this.InitializeComponent(); @@ -36,10 +36,10 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - - // This call is required by the Web Form Designer. + + // 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 40166311cf9..7715d4df34a 100644 --- a/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalIPN.aspx.cs @@ -36,17 +36,17 @@ protected override void OnLoad(EventArgs e) base.OnLoad(e); try { - bool blnValid = true; - - // string strTransactionID; + bool blnValid = true; + + // string strTransactionID; int intRoleID = 0; int intPortalID = this.PortalSettings.PortalId; - int intUserID = 0; - - // string strDescription; - double dblAmount = 0; - - // string strEmail; + int intUserID = 0; + + // string strDescription; + double dblAmount = 0; + + // string strEmail; bool blnCancel = false; string strPayPalID = Null.NullString; string strPost = "cmd=_notify-validate"; @@ -70,17 +70,17 @@ protected override void OnLoad(EventArgs e) blnValid = false; break; } - + break; case "payment_status": // verify the status if (strValue != "Completed") { blnValid = false; } - + 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; @@ -90,17 +90,17 @@ protected override void OnLoad(EventArgs e) break; case "item_number": // get the RoleID intRoleID = int.Parse(strValue); - + // 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; } @@ -123,7 +123,7 @@ protected override void OnLoad(EventArgs e) { strPayPalURL = "https://www.paypal.com/cgi-bin/webscr?"; } - + var objRequest = Globals.GetExternalRequest(strPayPalURL); objRequest.Method = "POST"; objRequest.ContentLength = strPost.Length; @@ -141,7 +141,7 @@ protected override void OnLoad(EventArgs e) strResponse = sr.ReadToEnd(); } } - + switch (strResponse) { case "VERIFIED": @@ -152,7 +152,7 @@ protected override void OnLoad(EventArgs e) break; } } - + if (blnValid) { int intAdministratorRoleId = 0; @@ -214,7 +214,7 @@ 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 3320a5bb366..ce393e6f658 100644 --- a/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs +++ b/DNN Platform/Website/admin/Sales/PayPalSubscription.aspx.cs @@ -43,20 +43,20 @@ protected override void OnLoad(EventArgs e) intUserID = objUserInfo.UserID; } } - + int intRoleId = -1; if (this.Request.QueryString["roleid"] != null) { intRoleId = int.Parse(this.Request.QueryString["roleid"]); } - + string strProcessorUserId = string.Empty; PortalInfo objPortalInfo = PortalController.Instance.GetPortal(this.PortalSettings.PortalId); if (objPortalInfo != null) { strProcessorUserId = objPortalInfo.ProcessorUserId; } - + Dictionary settings = PortalController.Instance.GetPortalSettings(this.PortalSettings.PortalId); string strPayPalURL; if (intUserID != -1 && intRoleId != -1 && !string.IsNullOrEmpty(strProcessorUserId)) @@ -87,7 +87,7 @@ protected override void OnLoad(EventArgs e) { intTrialPeriod = objRole.TrialPeriod; } - + int intBillingPeriod = 1; if (objRole.BillingPeriod != 0) { @@ -126,7 +126,7 @@ protected override void OnLoad(EventArgs e) strPayPalURL += "&p1=" + Globals.HTTPPOSTEncode(intTrialPeriod.ToString()); strPayPalURL += "&t1=" + Globals.HTTPPOSTEncode(objRole.TrialFrequency); } - + strPayPalURL += "&a3=" + Globals.HTTPPOSTEncode(strService); strPayPalURL += "&p3=" + Globals.HTTPPOSTEncode(intBillingPeriod.ToString()); strPayPalURL += "&t3=" + Globals.HTTPPOSTEncode(objRole.BillingFrequency); @@ -134,7 +134,7 @@ protected override void OnLoad(EventArgs e) strPayPalURL += "¤cy_code=" + Globals.HTTPPOSTEncode(this.PortalSettings.Currency); } } - + var ctlList = new ListController(); strPayPalURL += "&custom=" + Globals.HTTPPOSTEncode(intUserID.ToString()); @@ -188,7 +188,7 @@ protected override void OnLoad(EventArgs e) { strPayPalURL += "¬ify_url=" + Globals.HTTPPOSTEncode(Globals.AddHTTP(Globals.GetDomainName(this.Request)) + "/admin/Sales/PayPalIPN.aspx"); } - + strPayPalURL += "&sra=1"; // reattempt on failure } @@ -215,7 +215,7 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessPageLoadException(exc); } } - + private void InitializeComponent() { } diff --git a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs index b989b870563..e811c8115a1 100644 --- a/DNN Platform/Website/admin/Sales/Purchase.ascx.cs +++ b/DNN Platform/Website/admin/Sales/Purchase.ascx.cs @@ -54,7 +54,7 @@ protected override void OnLoad(EventArgs e) { this.RoleID = int.Parse(this.Request.QueryString["RoleID"]); } - + if (this.Page.IsPostBack == false) { if (this.RoleID != -1) @@ -68,7 +68,7 @@ protected override void OnLoad(EventArgs e) { this.lblDescription.Text = objRole.Description; } - + if (this.RoleID == this.PortalSettings.AdministratorRoleId) { if (!Null.IsNull(this.PortalSettings.HostFee)) @@ -83,14 +83,14 @@ protected override void OnLoad(EventArgs e) this.lblFee.Text = objRole.ServiceFee.ToString("#,##0.00"); } } - + if (!Null.IsNull(objRole.BillingFrequency)) { var ctlEntry = new ListController(); ListEntryInfo entry = ctlEntry.GetListEntryInfo("Frequency", objRole.BillingFrequency); this.lblFrequency.Text = entry.Text; } - + this.txtUnits.Text = "1"; if (objRole.BillingFrequency == "O") // one-time fee { @@ -113,7 +113,7 @@ protected override void OnLoad(EventArgs e) this.ViewState["UrlReferrer"] = string.Empty; } } - + if (this.RoleID == this.PortalSettings.AdministratorRoleId) { strCurrency = Host.HostCurrency; @@ -122,7 +122,7 @@ protected override void OnLoad(EventArgs e) { strCurrency = this.PortalSettings.Currency; } - + dblTotal = Convert.ToDouble(this.lblFee.Text) * Convert.ToDouble(this.txtUnits.Text); this.lblTotal.Text = dblTotal.ToString("#.##"); @@ -156,7 +156,7 @@ private void cmdPurchase_Click(object sender, EventArgs e) strProcessorUserId = objPortalInfo.ProcessorUserId; strProcessorPassword = objPortalInfo.ProcessorPassword; } - + if (strPaymentProcessor == "PayPal") { // build secure PayPal URL @@ -214,7 +214,7 @@ private double ConvertCurrency(string Amount, string FromCurrency, string ToCurr objStream.Write(strPost); objStream.Close(); } - + var objResponse = (HttpWebResponse)objRequest.GetResponse(); using (var sr = new StreamReader(objResponse.GetResponseStream())) { @@ -229,7 +229,7 @@ private double ConvertCurrency(string Amount, string FromCurrency, string ToCurr { Exceptions.ProcessModuleLoadException(this, exc); } - + return retValue; } } diff --git a/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs b/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs index a14757a2e34..1a92820175a 100644 --- a/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs +++ b/DNN Platform/Website/admin/Security/AccessDenied.ascx.cs @@ -24,7 +24,7 @@ protected override void OnLoad(EventArgs e) message = HttpUtility.HtmlEncode(DataProvider.Instance().GetRedirectMessage(messageGuid)); } - UI.Skins.Skin.AddModuleMessage( + UI.Skins.Skin.AddModuleMessage( this, !string.IsNullOrEmpty(message) ? message : Localization.GetString("AccessDenied", this.LocalResourceFile), ModuleMessage.ModuleMessageType.YellowWarning); diff --git a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs index 2e6e66abb38..d6bb4b2a8df 100644 --- a/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs +++ b/DNN Platform/Website/admin/Security/PasswordReset.ascx.cs @@ -30,14 +30,14 @@ 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 string ResetToken { @@ -45,13 +45,13 @@ private string ResetToken { return this.ViewState["ResetToken"] != null ? this.Request.QueryString["resetToken"] : string.Empty; } - + set { this.ViewState.Add("ResetToken", value); } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -69,7 +69,7 @@ protected override void OnLoad(EventArgs e) { this.Response.Redirect(this._navigationManager.NavigateURL(this.PortalSettings.LoginTabId) + this.Request.Url.Query); } - + this.cmdChangePassword.Click += this.cmdChangePassword_Click; this.hlCancel.NavigateUrl = this._navigationManager.NavigateURL(); @@ -109,14 +109,14 @@ protected override void OnLoad(EventArgs e) protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); - if (!string.IsNullOrEmpty(this.lblHelp.Text) || !string.IsNullOrEmpty(this.lblInfo.Text)) - { - this.resetMessages.Visible = true; - } - + if (!string.IsNullOrEmpty(this.lblHelp.Text) || !string.IsNullOrEmpty(this.lblInfo.Text)) + { + this.resetMessages.Visible = true; + } + var options = new DnnPaswordStrengthOptions(); var optionsAsJsonString = Json.Serialize(options); - var script = string.Format( + var script = string.Format( "dnn.initializePasswordStrength('.{0}', {1});{2}", "password-strength", optionsAsJsonString, Environment.NewLine); @@ -178,7 +178,7 @@ protected void RedirectAfterLogin() // 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) @@ -288,7 +288,7 @@ private void cmdChangePassword_Click(object sender, EventArgs e) username = testUser.Username; // we need the username of the account in order to change the password in the next step } } - + string errorMessage; string answer = string.Empty; if (MembershipProviderConfig.RequiresQuestionAndAnswer) @@ -353,10 +353,10 @@ private void LogResult(string message) log.LogTypeKey = "PASSWORD_SENT_FAILURE"; log.LogProperties.Add(new LogDetailInfo("Cause", message)); } - + log.AddProperty("IP", this._ipAddress); LogController.Instance.AddLog(log); - } + } } } diff --git a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs index cf3deabed62..7c0d0f7e24a 100644 --- a/DNN Platform/Website/admin/Security/SendPassword.ascx.cs +++ b/DNN Platform/Website/admin/Security/SendPassword.ascx.cs @@ -36,16 +36,16 @@ 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; - + private string _ipAddress; + public SendPassword() { this._navigationManager = this.DependencyProvider.GetRequiredService(); - } - + } + /// /// Gets the Redirect URL (after successful sending of password). /// @@ -62,38 +62,38 @@ 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 (string.IsNullOrEmpty(_RedirectURL)) - { - // redirect to current page - _RedirectURL = this._navigationManager.NavigateURL(); - } - } - else // redirect to after registration page - { - _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); + { + 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 (string.IsNullOrEmpty(_RedirectURL)) + { + // redirect to current page + _RedirectURL = this._navigationManager.NavigateURL(); + } + } + else // redirect to after registration page + { + _RedirectURL = this._navigationManager.NavigateURL(Convert.ToInt32(setting)); } } @@ -127,8 +127,8 @@ private bool ShowEmailField { return MembershipProviderConfig.RequiresUniqueEmail || this.UsernameDisabled; } - } - + } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -190,23 +190,6 @@ 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. @@ -272,12 +255,12 @@ protected void OnSendPasswordClick(object sender, EventArgs e) Mail.SendMail(this._user, MessageType.PasswordReminderUserIsNotApproved, this.PortalSettings); canSend = false; } - + if (MembershipProviderConfig.PasswordRetrievalEnabled || MembershipProviderConfig.PasswordResetEnabled) { UserController.ResetPasswordToken(this._user); } - + if (canSend) { if (Mail.SendMail(this._user, MessageType.PasswordReminder, this.PortalSettings) != string.Empty) @@ -320,6 +303,23 @@ protected void OnSendPasswordClick(object sender, EventArgs e) } } + 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); + } + } + private void LogSuccess() { this.LogResult(string.Empty); @@ -355,6 +355,6 @@ private void LogResult(string message) log.AddProperty("IP", this._ipAddress); LogController.Instance.AddLog(log); - } + } } } diff --git a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs index e3bf11b5cf0..6817d696359 100644 --- a/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs +++ b/DNN Platform/Website/admin/Skins/BreadCrumb.ascx.cs @@ -20,20 +20,40 @@ namespace DotNetNuke.UI.Skins.Controls public partial class BreadCrumb : SkinObjectBase { private const string UrlRegex = "(href|src)=(\\\"|'|)(.[^\\\"']*)(\\\"|'|)"; + private readonly StringBuilder _breadcrumb = new StringBuilder(""); + private readonly INavigationManager _navigationManager; private string _separator = "\"breadcrumb"; private string _cssClass = "SkinObject"; private int _rootLevel = 0; private bool _showRoot = false; - private readonly StringBuilder _breadcrumb = new StringBuilder(""); private string _homeUrl = string.Empty; private string _homeTabName = "Root"; - private readonly INavigationManager _navigationManager; - + public BreadCrumb() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } + public int ProfileUserId + { + get + { + return string.IsNullOrEmpty(this.Request.Params["UserId"]) + ? Null.NullInteger + : int.Parse(this.Request.Params["UserId"]); + } + } + + public int GroupId + { + get + { + return string.IsNullOrEmpty(this.Request.Params["GroupId"]) + ? Null.NullInteger + : int.Parse(this.Request.Params["GroupId"]); + } + } + // Separator between breadcrumb elements public string Separator { @@ -52,7 +72,7 @@ public string CssClass public string RootLevel { get { return this._rootLevel.ToString(); } - + set { this._rootLevel = int.Parse(value); @@ -71,26 +91,6 @@ public string RootLevel // Do not show when there is no breadcrumb (only has current tab) public bool HideWithNoBreadCrumb { get; set; } - public int ProfileUserId - { - get - { - return string.IsNullOrEmpty(this.Request.Params["UserId"]) - ? Null.NullInteger - : int.Parse(this.Request.Params["UserId"]); - } - } - - public int GroupId - { - get - { - return string.IsNullOrEmpty(this.Request.Params["GroupId"]) - ? Null.NullInteger - : int.Parse(this.Request.Params["GroupId"]); - } - } - protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -230,7 +230,7 @@ private void ResolveSeparatorPaths() if (changed) { - var newMatch = string.Format( + var newMatch = string.Format( "{0}={1}{2}{3}", match.Groups[1].Value, match.Groups[2].Value, diff --git a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs index f99b5903d2d..c27e8a3596f 100644 --- a/DNN Platform/Website/admin/Skins/Copyright.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Copyright.ascx.cs @@ -15,7 +15,7 @@ namespace DotNetNuke.UI.Skins.Controls public partial class Copyright : SkinObjectBase { private const string MyFileName = "Copyright.ascx"; - + public string CssClass { get; set; } protected override void OnLoad(EventArgs e) @@ -25,7 +25,7 @@ protected override void OnLoad(EventArgs e) { this.lblCopyright.CssClass = this.CssClass; } - + if (!string.IsNullOrEmpty(this.PortalSettings.FooterText)) { this.lblCopyright.Text = this.PortalSettings.FooterText.Replace("[year]", DateTime.Now.ToString("yyyy")); diff --git a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs index 90d24fa7c1e..82b28e19c1e 100644 --- a/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs +++ b/DNN Platform/Website/admin/Skins/CurrentDate.ascx.cs @@ -32,7 +32,7 @@ protected override void OnLoad(EventArgs e) { this.lblDate.CssClass = this.CssClass; } - + var user = UserController.Instance.GetCurrentUserInfo(); this.lblDate.Text = !string.IsNullOrEmpty(this.DateFormat) ? user.LocalTime().ToString(this.DateFormat) : user.LocalTime().ToLongDateString(); } diff --git a/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs index 96ac8991f07..ad0e6ff2577 100644 --- a/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnCssInclude.ascx.cs @@ -11,23 +11,23 @@ namespace DotNetNuke.UI.Skins.Controls public partial class DnnCssInclude : SkinObjectBase { public CssMediaType CssMedia { get; set; } - + public string FilePath { get; set; } - + public string PathNameAlias { get; set; } - + public int Priority { get; set; } - + public bool AddTag { get; set; } - + public string Name { get; set; } - + public string Version { get; set; } - + public bool ForceVersion { get; set; } - + public string ForceProvider { get; set; } - + public bool ForceBundle { get; set; } protected override void OnLoad(EventArgs e) diff --git a/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs b/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs index 9a774792c49..b95930c8d6a 100644 --- a/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnJsInclude.ascx.cs @@ -11,21 +11,21 @@ namespace DotNetNuke.UI.Skins.Controls public partial class DnnJsInclude : SkinObjectBase { public string FilePath { get; set; } - + public string PathNameAlias { get; set; } - + public int Priority { get; set; } - + public bool AddTag { get; set; } - + public string Name { get; set; } - + public string Version { get; set; } - + public bool ForceVersion { get; set; } - + public string ForceProvider { get; set; } - + public bool ForceBundle { get; set; } protected override void OnLoad(EventArgs e) diff --git a/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs b/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs index db50fd55cbb..2b3ee504fac 100644 --- a/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs +++ b/DNN Platform/Website/admin/Skins/DnnLink.ascx.cs @@ -16,43 +16,43 @@ namespace DotNetNuke.UI.Skins.Controls public partial class DnnLink : SkinObjectBase { private const string MyFileName = "DnnLink.ascx"; - + public string CssClass { get; set; } - + public string Target { get; set; } - + protected override void OnLoad(EventArgs e) { base.OnLoad(e); - if (!string.IsNullOrEmpty(this.CssClass)) - { - this.aDnnLink.Attributes.Add("class", this.CssClass); - } - - if (!string.IsNullOrEmpty(this.Target)) - { - this.aDnnLink.Target = this.Target; - } - - // set home page link to community URL + if (!string.IsNullOrEmpty(this.CssClass)) + { + this.aDnnLink.Attributes.Add("class", this.CssClass); + } + + if (!string.IsNullOrEmpty(this.Target)) + { + this.aDnnLink.Target = this.Target; + } + + // set home page link to community URL string url = "http://www.dnnsoftware.com/community?utm_source=dnn-install&utm_medium=web-link&utm_content=gravity-skin-link&utm_campaign=dnn-install"; string utmTerm = "&utm_term=cms-by-dnn"; string hostName = this.Request.Url.Host.ToLowerInvariant().Replace("www.", string.Empty); - int charPos = 0; + int charPos = 0; string linkText = "CMS by DNN"; if (hostName.Length > 0) { // convert first letter of hostname to int pos in alphabet charPos = char.ToUpper(hostName[0]) - 64; } - + // vary link by first letter of host name if (charPos <= 5) { linkText = "Open Source ASP.NET CMS by DNN"; utmTerm = "&utm_term=open+source+asp.net+by+dnn"; } - + if (charPos > 5 && charPos <= 10) { linkText = "DNN - .NET Open Source CMS"; @@ -76,7 +76,7 @@ protected override void OnLoad(EventArgs e) linkText = "WCM by DNN"; utmTerm = "&utm_term=wcm+by+dnn"; } - + this.aDnnLink.InnerText = linkText; this.aDnnLink.HRef = HttpUtility.HtmlEncode(url + utmTerm); } diff --git a/DNN Platform/Website/admin/Skins/Help.ascx.cs b/DNN Platform/Website/admin/Skins/Help.ascx.cs index f03efbc321c..56cb83a8b53 100644 --- a/DNN Platform/Website/admin/Skins/Help.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Help.ascx.cs @@ -35,7 +35,7 @@ protected override void OnLoad(EventArgs e) { this.hypHelp.CssClass = this.CssClass; } - + if (this.Request.IsAuthenticated) { if (TabPermissionController.CanAdminPage()) diff --git a/DNN Platform/Website/admin/Skins/HostName.ascx.cs b/DNN Platform/Website/admin/Skins/HostName.ascx.cs index ed8f381b4e4..e3f177ab4e3 100644 --- a/DNN Platform/Website/admin/Skins/HostName.ascx.cs +++ b/DNN Platform/Website/admin/Skins/HostName.ascx.cs @@ -34,7 +34,7 @@ protected override void OnLoad(EventArgs e) { this.hypHostName.CssClass = this.CssClass; } - + this.hypHostName.Text = Host.HostTitle; this.hypHostName.NavigateUrl = Globals.AddHTTP(Host.HostURL); } diff --git a/DNN Platform/Website/admin/Skins/Language.ascx.cs b/DNN Platform/Website/admin/Skins/Language.ascx.cs index f557538f847..d4bf670d5d3 100644 --- a/DNN Platform/Website/admin/Skins/Language.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Language.ascx.cs @@ -23,7 +23,7 @@ namespace DotNetNuke.UI.Skins.Controls /// /// public partial class Language : SkinObjectBase - { + { private const string MyFileName = "Language.ascx"; private string _SelectedItemTemplate; private string _alternateTemplate; @@ -35,8 +35,8 @@ public partial class Language : SkinObjectBase private string _localResourceFile; private LanguageTokenReplace _localTokenReplace; private string _separatorTemplate; - private bool _showMenu = true; - + private bool _showMenu = true; + public string AlternateTemplate { get @@ -45,10 +45,10 @@ public string AlternateTemplate { this._alternateTemplate = Localization.GetString("AlternateTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._alternateTemplate; } - + set { this._alternateTemplate = value; @@ -63,10 +63,10 @@ public string CommonFooterTemplate { this._commonFooterTemplate = Localization.GetString("CommonFooterTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._commonFooterTemplate; } - + set { this._commonFooterTemplate = value; @@ -81,10 +81,10 @@ public string CommonHeaderTemplate { this._commonHeaderTemplate = Localization.GetString("CommonHeaderTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._commonHeaderTemplate; } - + set { this._commonHeaderTemplate = value; @@ -101,10 +101,10 @@ public string FooterTemplate { this._footerTemplate = Localization.GetString("FooterTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._footerTemplate; } - + set { this._footerTemplate = value; @@ -119,10 +119,10 @@ public string HeaderTemplate { this._headerTemplate = Localization.GetString("HeaderTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._headerTemplate; } - + set { this._headerTemplate = value; @@ -137,10 +137,10 @@ public string ItemTemplate { this._itemTemplate = Localization.GetString("ItemTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._itemTemplate; } - + set { this._itemTemplate = value; @@ -155,10 +155,10 @@ public string SelectedItemTemplate { this._SelectedItemTemplate = Localization.GetString("SelectedItemTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._SelectedItemTemplate; } - + set { this._SelectedItemTemplate = value; @@ -173,10 +173,10 @@ public string SeparatorTemplate { this._separatorTemplate = Localization.GetString("SeparatorTemplate.Default", this.LocalResourceFile, this.TemplateCulture); } - + return this._separatorTemplate; } - + set { this._separatorTemplate = value; @@ -194,18 +194,18 @@ public bool ShowMenu // this is to make sure that at least one type of selector will be visible if multiple languages are enabled this._showMenu = true; } - + return this._showMenu; } - + set { this._showMenu = value; } } - public bool UseCurrentCultureForTemplate { get; set; } - + public bool UseCurrentCultureForTemplate { get; set; } + protected string CurrentCulture { get @@ -221,7 +221,7 @@ protected string TemplateCulture return this.UseCurrentCultureForTemplate ? this.CurrentCulture : "en-US"; } } - + protected string LocalResourceFile { get @@ -230,7 +230,7 @@ protected string LocalResourceFile { this._localResourceFile = Localization.GetResourceFile(this, MyFileName); } - + return this._localResourceFile; } } @@ -243,11 +243,11 @@ protected LanguageTokenReplace LocalTokenReplace { this._localTokenReplace = new LanguageTokenReplace { resourceFile = this.LocalResourceFile }; } - + return this._localTokenReplace; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -276,7 +276,7 @@ protected override void OnLoad(EventArgs e) } } } - + if (this.ShowLinks) { if (locales.Count > 1) @@ -289,14 +289,14 @@ protected override void OnLoad(EventArgs e) this.rptLanguages.Visible = false; } } - + if (this.ShowMenu) { if (!string.IsNullOrEmpty(this.CssClass)) { this.selectCulture.CssClass = this.CssClass; } - + if (!this.IsPostBack) { // select the default item @@ -310,7 +310,7 @@ protected override void OnLoad(EventArgs e) } } } - + // only show language selector if more than one language if (this.selectCulture.Items.Count <= 1) { @@ -321,7 +321,7 @@ protected override void OnLoad(EventArgs e) { this.selectCulture.Visible = false; } - + this.handleCommonTemplates(); } catch (Exception ex) @@ -358,7 +358,7 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e { strTemplate = this.ItemTemplate; } - + break; case ListItemType.Header: strTemplate = this.HeaderTemplate; @@ -370,7 +370,7 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e strTemplate = this.SeparatorTemplate; break; } - + if (string.IsNullOrEmpty(strTemplate)) { litTemplate.Visible = false; @@ -386,7 +386,7 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e { strTemplate = this.SelectedItemTemplate; } - + litTemplate.Text = this.parseTemplate(strTemplate, locale.Code); } } @@ -402,8 +402,8 @@ protected void rptLanguages_ItemDataBound(object sender, RepeaterItemEventArgs e { Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); } - } - + } + private string parseTemplate(string template, string locale) { string strReturnValue = template; @@ -427,7 +427,7 @@ private string parseTemplate(string template, string locale) { Exceptions.ProcessPageLoadException(ex, this.Request.RawUrl); } - + return strReturnValue; } @@ -441,7 +441,7 @@ private void handleCommonTemplates() { this.litCommonHeaderTemplate.Text = this.parseTemplate(this.CommonHeaderTemplate, this.CurrentCulture); } - + if (string.IsNullOrEmpty(this.CommonFooterTemplate)) { this.litCommonFooterTemplate.Visible = false; @@ -463,13 +463,13 @@ private bool LocaleIsAvailable(Locale locale) 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/LeftMenu.ascx.cs b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs index ec3b6ba6e12..184bcc76536 100644 --- a/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LeftMenu.ascx.cs @@ -19,6 +19,5 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- [Obsolete("This skin object has been expired, create empty object to compact old skin. please ask skin vendor to update the skin if it referenced to this control.. Scheduled removal in v10.0.0.")] public partial class LeftMenu : SkinObjectBase - { - } + {} } diff --git a/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs b/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs index 7bae3bb1e4b..1abe220300d 100644 --- a/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LinkToFullSite.ascx.cs @@ -36,8 +36,8 @@ private string LocalResourcesFile return this._localResourcesFile; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -53,6 +53,6 @@ protected override void OnLoad(EventArgs e) { this.Visible = false; } - } + } } } diff --git a/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs b/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs index 92472771968..f56a2210218 100644 --- a/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs +++ b/DNN Platform/Website/admin/Skins/LinkToMobileSite.ascx.cs @@ -36,8 +36,8 @@ private string LocalResourcesFile return this._localResourcesFile; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -53,6 +53,6 @@ protected override void OnLoad(EventArgs e) { this.Visible = false; } - } + } } } diff --git a/DNN Platform/Website/admin/Skins/Links.ascx.cs b/DNN Platform/Website/admin/Skins/Links.ascx.cs index 501e5b1bbbd..0c11e123252 100644 --- a/DNN Platform/Website/admin/Skins/Links.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Links.ascx.cs @@ -17,19 +17,19 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Links : SkinObjectBase { - private static readonly Regex SrcRegex = new Regex("src=[']?", RegexOptions.Compiled | RegexOptions.IgnoreCase); + private static readonly Regex SrcRegex = new Regex("src=[']?", RegexOptions.Compiled | RegexOptions.IgnoreCase); private string _alignment; private bool _forceLinks = true; private bool _includeActiveTab = true; - private string _level; - + private string _level; + public string Alignment { get { return this._alignment; } - + set { this._alignment = value.ToLowerInvariant(); @@ -44,7 +44,7 @@ public string Level { return this._level; } - + set { this._level = value.ToLowerInvariant(); @@ -61,7 +61,7 @@ public bool ForceLinks { return this._forceLinks; } - + set { this._forceLinks = value; @@ -74,13 +74,13 @@ public bool IncludeActiveTab { return this._includeActiveTab; } - + set { this._includeActiveTab = value; } - } - + } + protected override void OnLoad(EventArgs e) { base.OnLoad(e); @@ -93,7 +93,7 @@ protected override void OnLoad(EventArgs e) { strCssClass = "SkinObject"; } - + string strSeparator = string.Empty; if (!string.IsNullOrEmpty(this.Separator)) { @@ -121,10 +121,10 @@ protected override void OnLoad(EventArgs e) { strLinks = this.BuildLinks(string.Empty, strSeparator, strCssClass); } - + this.lblLinks.Text = strLinks; - } - + } + private string BuildLinks(string strLevel, string strSeparator, string strCssClass) { var sbLinks = new StringBuilder(); @@ -136,12 +136,12 @@ private string BuildLinks(string strLevel, string strSeparator, string strCssCla { sbLinks.Append(this.ProcessLink(this.ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); } - + foreach (TabInfo objTab in hostTabs) { sbLinks.Append(this.ProcessLink(this.ProcessTab(objTab, strLevel, strCssClass), sbLinks.ToString().Length)); } - + return sbLinks.ToString(); } @@ -160,32 +160,32 @@ private string ProcessTab(TabInfo objTab, string strLevel, string strCssClass) return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } } - + break; case "child": // Render the current tabs child tabs if (objTab.ParentId == this.PortalSettings.ActiveTab.TabID) { return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } - + break; case "parent": // Render the current tabs parenttab if (objTab.TabID == this.PortalSettings.ActiveTab.ParentId) { return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } - + break; case "root": // Render Root tabs if (objTab.Level == 0) { return this.AddLink(objTab.TabName, objTab.FullUrl, strCssClass); } - + break; } } - + return string.Empty; } @@ -196,7 +196,7 @@ private string ProcessLink(string sLink, int iLinksLength) { return string.Empty; } - + if (this.Alignment == "vertical") { sLink = string.Concat("
    ", this.Separator, sLink, "
    "); @@ -206,13 +206,13 @@ private string ProcessLink(string sLink, int iLinksLength) // If not vertical, then render the separator sLink = string.Concat(this.Separator, sLink); } - + return sLink; } private string AddLink(string strTabName, string strURL, string strCssClass) { return string.Format("{2}", strCssClass, strURL, strTabName); - } + } } } diff --git a/DNN Platform/Website/admin/Skins/Login.ascx.cs b/DNN Platform/Website/admin/Skins/Login.ascx.cs index 70a0c0a7e1e..83edb7959d7 100644 --- a/DNN Platform/Website/admin/Skins/Login.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Login.ascx.cs @@ -21,16 +21,16 @@ namespace DotNetNuke.UI.Skins.Controls /// ----------------------------------------------------------------------------- public partial class Login : SkinObjectBase { - private const string MyFileName = "Login.ascx"; - + private const string MyFileName = "Login.ascx"; + private readonly INavigationManager _navigationManager; - + public Login() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); this.LegacyMode = true; - } - + } + public string Text { get; set; } public string CssClass { get; set; } @@ -45,8 +45,8 @@ public Login() /// /// Gets or sets a value indicating whether set this to true to show in custom 404/500 page. /// - public bool ShowInErrorPage { get; set; } - + public bool ShowInErrorPage { get; set; } + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -88,7 +88,7 @@ protected override void OnLoad(EventArgs e) { this.LogoffText = this.LogoffText.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); } - + this.loginLink.Text = this.LogoffText; this.enhancedLoginLink.Text = this.LogoffText; } @@ -99,7 +99,7 @@ protected override void OnLoad(EventArgs e) this.loginLink.ToolTip = this.loginLink.Text; this.enhancedLoginLink.ToolTip = this.loginLink.Text; } - + this.loginLink.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Logoff"); this.enhancedLoginLink.NavigateUrl = this.loginLink.NavigateUrl; } @@ -111,7 +111,7 @@ protected override void OnLoad(EventArgs e) { this.Text = this.Text.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); } - + this.loginLink.Text = this.Text; this.enhancedLoginLink.Text = this.Text; } @@ -128,7 +128,7 @@ protected override void OnLoad(EventArgs e) { returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=")); } - + returnUrl = HttpUtility.UrlEncode(returnUrl); this.loginLink.NavigateUrl = Globals.LoginURL(returnUrl, this.Request.QueryString["override"] != null); @@ -156,6 +156,6 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - } + } } } diff --git a/DNN Platform/Website/admin/Skins/Logo.ascx.cs b/DNN Platform/Website/admin/Skins/Logo.ascx.cs index a0868da4ed8..59467fda11b 100644 --- a/DNN Platform/Website/admin/Skins/Logo.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Logo.ascx.cs @@ -27,9 +27,9 @@ public Logo() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - + public string BorderWidth { get; set; } - + public string CssClass { get; set; } protected override void OnLoad(EventArgs e) @@ -41,12 +41,12 @@ protected override void OnLoad(EventArgs e) { this.imgLogo.BorderWidth = Unit.Parse(this.BorderWidth); } - + if (!string.IsNullOrEmpty(this.CssClass)) { this.imgLogo.CssClass = this.CssClass; } - + bool logoVisible = false; if (!string.IsNullOrEmpty(this.PortalSettings.LogoFile)) { @@ -61,7 +61,7 @@ protected override void OnLoad(EventArgs e) } } } - + this.imgLogo.Visible = logoVisible; this.imgLogo.AlternateText = this.PortalSettings.PortalName; this.hypLogo.ToolTip = this.PortalSettings.PortalName; @@ -70,7 +70,7 @@ protected override void OnLoad(EventArgs e) { this.hypLogo.Attributes.Add("aria-label", this.PortalSettings.PortalName); } - + if (this.PortalSettings.HomeTabId != -1) { this.hypLogo.NavigateUrl = this._navigationManager.NavigateURL(this.PortalSettings.HomeTabId); @@ -89,7 +89,7 @@ protected override void OnLoad(EventArgs e) private IFileInfo GetLogoFileInfo() { string cacheKey = string.Format(DataCache.PortalCacheKey, this.PortalSettings.PortalId, this.PortalSettings.CultureCode) + "LogoFile"; - var file = CBO.GetCachedObject( + var file = CBO.GetCachedObject( new CacheItemArgs(cacheKey, DataCache.PortalCacheTimeOut, DataCache.PortalCachePriority), this.GetLogoFileInfoCallBack); diff --git a/DNN Platform/Website/admin/Skins/Meta.ascx.cs b/DNN Platform/Website/admin/Skins/Meta.ascx.cs index f6c596bb435..639de32148f 100644 --- a/DNN Platform/Website/admin/Skins/Meta.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Meta.ascx.cs @@ -13,6 +13,12 @@ public partial class Meta : SkinObjectBase /// Backing field for . private readonly HttpPlaceholder http = new HttpPlaceholder(); + /// Gets an object to set the property. + public HttpPlaceholder Http + { + get { return this.http; } + } + /// /// Gets or sets the name of the meta element /// Either the name or the must be set. @@ -23,12 +29,6 @@ public partial class Meta : SkinObjectBase /// Gets or sets the content of the meta element. public string Content { get; set; } - /// Gets an object to set the property. - public HttpPlaceholder Http - { - get { return this.http; } - } - /// /// Gets or sets the http-equiv attribute of the meta element. /// If specified, this is the name of the HTTP header that the diff --git a/DNN Platform/Website/admin/Skins/Nav.ascx.cs b/DNN Platform/Website/admin/Skins/Nav.ascx.cs index 26495940324..9aa465f2d36 100644 --- a/DNN Platform/Website/admin/Skins/Nav.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Nav.ascx.cs @@ -58,7 +58,7 @@ protected override void OnLoad(EventArgs e) { this.SeparatorRightHTML = this.FixImagePath(this.SeparatorRightHTML); } - + if (!string.IsNullOrEmpty(this.SeparatorLeftHTMLBreadCrumb)) { this.SeparatorLeftHTMLBreadCrumb = this.FixImagePath(this.SeparatorLeftHTMLBreadCrumb); @@ -150,7 +150,7 @@ protected override void OnLoad(EventArgs e) Exceptions.ProcessModuleLoadException(this, exc); } } - + protected override void OnInit(EventArgs e) { this.InitializeNavControl(this, "SolpartMenuNavigationProvider"); @@ -160,7 +160,7 @@ protected override void OnInit(EventArgs e) base.OnInit(e); this.InitializeComponent(); } - + private void InitializeComponent() { } @@ -191,7 +191,7 @@ private void Control_NodeClick(NavigationEventArgs args) { args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - + this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); } @@ -201,7 +201,7 @@ private void Control_PopulateOnDemand(NavigationEventArgs args) { args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - + this.BuildNodes(args.Node); } } diff --git a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs index 8532805db18..32d6f4a20d1 100644 --- a/DNN Platform/Website/admin/Skins/Privacy.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Privacy.ascx.cs @@ -26,7 +26,7 @@ public Privacy() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - + public string Text { get; set; } public string CssClass { get; set; } @@ -47,7 +47,7 @@ protected override void OnLoad(EventArgs e) { this.hypPrivacy.CssClass = this.CssClass; } - + if (!string.IsNullOrEmpty(this.Text)) { this.hypPrivacy.Text = this.Text; @@ -56,7 +56,7 @@ protected override void OnLoad(EventArgs e) { this.hypPrivacy.Text = Localization.GetString("Privacy", Localization.GetResourceFile(this, MyFileName)); } - + this.hypPrivacy.NavigateUrl = this.PortalSettings.PrivacyTabId == Null.NullInteger ? this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Privacy") : this._navigationManager.NavigateURL(this.PortalSettings.PrivacyTabId); this.hypPrivacy.Attributes["rel"] = "nofollow"; } diff --git a/DNN Platform/Website/admin/Skins/Search.ascx.cs b/DNN Platform/Website/admin/Skins/Search.ascx.cs index c1b27a0bf2d..638cc5e489b 100644 --- a/DNN Platform/Website/admin/Skins/Search.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Search.ascx.cs @@ -24,15 +24,10 @@ 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 string _siteIconURL; private string _siteText; private string _siteToolTip; @@ -40,10 +35,47 @@ public Search() private string _webIconURL; private string _webText; private string _webToolTip; - private string _webURL; + private string _webURL; private bool _enableWildSearch = true; - + + public Search() + { + this._navigationManager = Globals.DependencyProvider.GetRequiredService(); + } + + public string SeeMoreText + { + get + { + return Localization.GetSafeJSString("SeeMoreResults", Localization.GetResourceFile(this, MyFileName)); + } + } + + public string ClearQueryText + { + get + { + return Localization.GetSafeJSString("SearchClearQuery", Localization.GetResourceFile(this, MyFileName)); + } + } + + public string NoResultText + { + get + { + return Localization.GetSafeJSString("NoResult", Localization.GetResourceFile(this, MyFileName)); + } + } + + public string PlaceHolderText + { + get + { + return Localization.GetSafeJSString("Placeholder", Localization.GetResourceFile(this, MyFileName)); + } + } + /// /// Gets or sets the CSS class for the option buttons and search button. /// @@ -62,7 +94,7 @@ public bool ShowSite { return this._showSite; } - + set { this._showSite = value; @@ -80,7 +112,7 @@ public bool ShowWeb { return this._showWeb; } - + set { this._showWeb = value; @@ -102,48 +134,16 @@ public string SiteIconURL { return IconController.IconURL("DnnSearch"); } - + return this._siteIconURL; } - + set { this._siteIconURL = value; } } - public string SeeMoreText - { - get - { - return Localization.GetSafeJSString("SeeMoreResults", Localization.GetResourceFile(this, MyFileName)); - } - } - - public string ClearQueryText - { - get - { - return Localization.GetSafeJSString("SearchClearQuery", Localization.GetResourceFile(this, MyFileName)); - } - } - - public string NoResultText - { - get - { - return Localization.GetSafeJSString("NoResult", Localization.GetResourceFile(this, MyFileName)); - } - } - - public string PlaceHolderText - { - get - { - return Localization.GetSafeJSString("Placeholder", Localization.GetResourceFile(this, MyFileName)); - } - } - /// /// Gets or sets the text for the "site" radio button or option list item. /// @@ -158,10 +158,10 @@ public string SiteText { return Localization.GetString("Site", Localization.GetResourceFile(this, MyFileName)); } - + return this._siteText; } - + set { this._siteText = value; @@ -182,10 +182,10 @@ public string SiteToolTip { return Localization.GetString("Site.ToolTip", Localization.GetResourceFile(this, MyFileName)); } - + return this._siteToolTip; } - + set { this._siteToolTip = value; @@ -208,10 +208,10 @@ public string SiteURL { return Localization.GetString("URL", Localization.GetResourceFile(this, MyFileName)); } - + return this._siteURL; } - + set { this._siteURL = value; @@ -256,10 +256,10 @@ public string WebIconURL { return IconController.IconURL("GoogleSearch"); } - + return this._webIconURL; } - + set { this._webIconURL = value; @@ -280,10 +280,10 @@ public string WebText { return Localization.GetString("Web", Localization.GetResourceFile(this, MyFileName)); } - + return this._webText; } - + set { this._webText = value; @@ -304,10 +304,10 @@ public string WebToolTip { return Localization.GetString("Web.ToolTip", Localization.GetResourceFile(this, MyFileName)); } - + return this._webToolTip; } - + set { this._webToolTip = value; @@ -331,10 +331,10 @@ public string WebURL { return Localization.GetString("URL", Localization.GetResourceFile(this, MyFileName)); } - + return this._webURL; } - + set { this._webURL = value; @@ -350,21 +350,21 @@ public string WebURL /// Gets or sets the millisecond to delay trigger auto search. /// public int AutoSearchDelayInMilliSecond { get; set; } - + /// /// Gets or sets a value indicating whether disable the wild search. /// - public bool EnableWildSearch - { - get { return this._enableWildSearch; } - set { this._enableWildSearch = value; } - } + public bool EnableWildSearch + { + get { return this._enableWildSearch; } + set { this._enableWildSearch = value; } + } protected int PortalId { get; set; } protected string SearchType { get; set; } - protected string CultureCode { get; set; } + protected string CultureCode { get; set; } /// /// Executes the search. @@ -383,7 +383,7 @@ protected void ExecuteSearch(string searchText, string searchType) { return; } - + string strURL; if (!string.IsNullOrEmpty(searchText)) { @@ -412,7 +412,7 @@ protected void ExecuteSearch(string searchText, string searchType) this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId) + "&Search=" + this.Server.UrlEncode(searchText)); } } - + break; case "W": // web @@ -423,7 +423,7 @@ protected void ExecuteSearch(string searchText, string searchType) strURL = strURL.Replace("[DOMAIN]", string.Empty); UrlUtils.OpenNewWindow(this.Page, this.GetType(), strURL); } - + break; } } @@ -438,8 +438,8 @@ protected void ExecuteSearch(string searchText, string searchType) this.Response.Redirect(this._navigationManager.NavigateURL(searchTabId)); } } - } - + } + /// /// Handles the Load event of the Page control. /// @@ -451,20 +451,20 @@ protected override void OnLoad(EventArgs e) Framework.ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); ClientResourceManager.RegisterStyleSheet(this.Page, "~/Resources/Search/SearchSkinObjectPreview.css", FileOrder.Css.ModuleCss); ClientResourceManager.RegisterScript(this.Page, "~/Resources/Search/SearchSkinObjectPreview.js"); - + this.cmdSearch.Click += this.CmdSearchClick; this.cmdSearchNew.Click += this.CmdSearchNewClick; - if (this.MinCharRequired == 0) - { - this.MinCharRequired = 2; - } - - if (this.AutoSearchDelayInMilliSecond == 0) - { - this.AutoSearchDelayInMilliSecond = 400; - } - + if (this.MinCharRequired == 0) + { + this.MinCharRequired = 2; + } + + if (this.AutoSearchDelayInMilliSecond == 0) + { + this.AutoSearchDelayInMilliSecond = 400; + } + this.PortalId = this.PortalSettings.ActiveTab.IsSuperTab ? this.PortalSettings.PortalId : -1; if (!string.IsNullOrEmpty(this.Submit)) @@ -479,7 +479,7 @@ protected override void OnLoad(EventArgs e) { this.Submit = Localization.GetString("Search", Localization.GetResourceFile(this, MyFileName)); } - + this.cmdSearch.Text = this.Submit; this.cmdSearchNew.Text = this.Submit; if (!string.IsNullOrEmpty(this.CssClass)) @@ -490,31 +490,6 @@ protected override void OnLoad(EventArgs e) this.cmdSearchNew.CssClass = this.CssClass; } } - - 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; - } /// /// Handles the Click event of the cmdSearchNew control. @@ -574,7 +549,7 @@ protected override void OnPreRender(EventArgs e) this.WebRadioButton.Text = this.WebText; this.WebRadioButton.ToolTip = this.WebToolTip; } - + if (this.SiteRadioButton.Visible) { this.SiteRadioButton.Checked = true; @@ -586,7 +561,32 @@ protected override void OnPreRender(EventArgs e) this.txtSearch.Attributes.Add("autocomplete", "off"); this.txtSearch.Attributes.Add("placeholder", this.PlaceHolderText); } - } + } + + 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; + } /// /// Handles the Click event of the cmdSearch control. @@ -604,7 +604,7 @@ private void CmdSearchClick(object sender, EventArgs e) this.SearchType = "W"; } } - + this.ExecuteSearch(this.txtSearch.Text.Trim(), this.SearchType); } } diff --git a/DNN Platform/Website/admin/Skins/Styles.ascx.cs b/DNN Platform/Website/admin/Skins/Styles.ascx.cs index ac8ac324c77..519d21b16ff 100644 --- a/DNN Platform/Website/admin/Skins/Styles.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Styles.ascx.cs @@ -28,7 +28,7 @@ public bool UseSkinPath { return this._useSkinPath; } - + set { this._useSkinPath = value; @@ -58,7 +58,7 @@ protected void AddStyleSheet() { skinpath = ((Skin)this.Parent).SkinPath; } - + var objLink = new HtmlLink(); objLink.ID = Globals.CreateValidID(this.Name); objLink.Attributes["rel"] = "stylesheet"; @@ -68,7 +68,7 @@ protected void AddStyleSheet() { objLink.Attributes["media"] = this.Media; // NWS: add support for "media" attribute } - + if (this.IsFirst) { // Find the first HtmlLink @@ -80,7 +80,7 @@ protected void AddStyleSheet() break; } } - + this.AddLink(objCSS, iLink, objLink); } else diff --git a/DNN Platform/Website/admin/Skins/Terms.ascx.cs b/DNN Platform/Website/admin/Skins/Terms.ascx.cs index 2c3603def92..4203f569e18 100644 --- a/DNN Platform/Website/admin/Skins/Terms.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Terms.ascx.cs @@ -26,7 +26,7 @@ public Terms() { this._navigationManager = Globals.DependencyProvider.GetRequiredService(); } - + public string Text { get; set; } public string CssClass { get; set; } @@ -47,7 +47,7 @@ protected override void OnLoad(EventArgs e) { this.hypTerms.CssClass = this.CssClass; } - + if (!string.IsNullOrEmpty(this.Text)) { this.hypTerms.Text = this.Text; @@ -56,7 +56,7 @@ protected override void OnLoad(EventArgs e) { this.hypTerms.Text = Localization.GetString("Terms", Localization.GetResourceFile(this, MyFileName)); } - + this.hypTerms.NavigateUrl = this.PortalSettings.TermsTabId == Null.NullInteger ? this._navigationManager.NavigateURL(this.PortalSettings.ActiveTab.TabID, "Terms") : this._navigationManager.NavigateURL(this.PortalSettings.TermsTabId); this.hypTerms.Attributes["rel"] = "nofollow"; diff --git a/DNN Platform/Website/admin/Skins/Text.ascx.cs b/DNN Platform/Website/admin/Skins/Text.ascx.cs index 74709a348ec..f0a405b0825 100644 --- a/DNN Platform/Website/admin/Skins/Text.ascx.cs +++ b/DNN Platform/Website/admin/Skins/Text.ascx.cs @@ -50,7 +50,7 @@ protected override void OnLoad(EventArgs e) tr.AccessingUser = this.PortalSettings.UserInfo; strText = tr.ReplaceEnvironmentTokens(strText); } - + this.lblText.Text = strText; if (!string.IsNullOrEmpty(this.CssClass)) { diff --git a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs index 3e84895408a..2b933a70fdb 100644 --- a/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs +++ b/DNN Platform/Website/admin/Skins/TreeViewMenu.ascx.cs @@ -22,7 +22,7 @@ namespace DotNetNuke.UI.Skins.Controls /// /// ----------------------------------------------------------------------------- public partial class TreeViewMenu : NavObjectBase - { + { private const string MyFileName = "TreeViewMenu.ascx"; private string _bodyCssClass = string.Empty; private string _cssClass = string.Empty; @@ -43,23 +43,23 @@ public partial class TreeViewMenu : NavObjectBase private string _treeCssClass = string.Empty; private string _treeGoUpImage = "~/images/folderup.gif"; private int _treeIndentWidth = 10; - private string _width = "100%"; - + private string _width = "100%"; + private enum eImageType { FolderClosed = 0, FolderOpen = 1, Page = 2, GotoParent = 3, - } - + } + public string BodyCssClass { get { return this._bodyCssClass; } - + set { this._bodyCssClass = value; @@ -72,7 +72,7 @@ public string CssClass { return this._cssClass; } - + set { this._cssClass = value; @@ -85,7 +85,7 @@ public string HeaderCssClass { return this._headerCssClass; } - + set { this._headerCssClass = value; @@ -98,7 +98,7 @@ public string HeaderTextCssClass { return this._headerTextCssClass; } - + set { this._headerTextCssClass = value; @@ -111,7 +111,7 @@ public string HeaderText { return this._headerText; } - + set { this._headerText = value; @@ -124,7 +124,7 @@ public bool IncludeHeader { return this._includeHeader; } - + set { this._includeHeader = value; @@ -137,7 +137,7 @@ public string NodeChildCssClass { return this._nodeChildCssClass; } - + set { this._nodeChildCssClass = value; @@ -150,7 +150,7 @@ public string NodeClosedImage { return this._nodeClosedImage; } - + set { this._nodeClosedImage = value; @@ -163,7 +163,7 @@ public string NodeCollapseImage { return this._nodeCollapseImage; } - + set { this._nodeCollapseImage = value; @@ -176,7 +176,7 @@ public string NodeCssClass { return this._nodeCssClass; } - + set { this._nodeCssClass = value; @@ -189,7 +189,7 @@ public string NodeExpandImage { return this._nodeExpandImage; } - + set { this._nodeExpandImage = value; @@ -202,7 +202,7 @@ public string NodeLeafImage { return this._nodeLeafImage; } - + set { this._nodeLeafImage = value; @@ -215,7 +215,7 @@ public string NodeOpenImage { return this._nodeOpenImage; } - + set { this._nodeOpenImage = value; @@ -228,7 +228,7 @@ public string NodeOverCssClass { return this._nodeOverCssClass; } - + set { this._nodeOverCssClass = value; @@ -241,7 +241,7 @@ public string NodeSelectedCssClass { return this._nodeSelectedCssClass; } - + set { this._nodeSelectedCssClass = value; @@ -256,7 +256,7 @@ public string ResourceKey { return this._resourceKey; } - + set { this._resourceKey = value; @@ -269,7 +269,7 @@ public string TreeCssClass { return this._treeCssClass; } - + set { this._treeCssClass = value; @@ -282,7 +282,7 @@ public string TreeGoUpImage { return this._treeGoUpImage; } - + set { this._treeGoUpImage = value; @@ -295,7 +295,7 @@ public int TreeIndentWidth { return this._treeIndentWidth; } - + set { this._treeIndentWidth = value; @@ -308,13 +308,13 @@ public string Width { return this._width; } - + set { this._width = value; } } - + /// ----------------------------------------------------------------------------- /// /// The Page_Load server event handler on this user control is used @@ -384,7 +384,7 @@ protected override void OnLoad(EventArgs e) this.lblHeader.Text = "Site Navigation"; } } - + this.tblHeader.Visible = this.IncludeHeader; // Main Panel Properties @@ -392,7 +392,7 @@ protected override void OnLoad(EventArgs e) { this.cellBody.Attributes.Add("class", this.BodyCssClass); } - + this.cellBody.NoWrap = this.NoWrap; } } @@ -410,12 +410,12 @@ protected override void OnInit(EventArgs e) this.Control.PopulateOnDemand += this.DNNTree_PopulateOnDemand; base.OnInit(e); this.InitializeComponent(); - } + } private void InitializeComponent() { - } - + } + /// ----------------------------------------------------------------------------- /// /// The BuildTree helper method is used to build the tree. @@ -445,7 +445,7 @@ private void BuildTree(DNNNode objNode, bool blnPODRequest) { blnAddUpNode = true; } - + break; } } @@ -464,12 +464,12 @@ private void BuildTree(DNNNode objNode, bool blnPODRequest) objParentNode.ClickAction = eClickAction.PostBack; objNodes.InsertBefore(0, objParentNode); } - + foreach (DNNNode objPNode in objNodes) // clean up to do in processnodes??? { this.ProcessNodes(objPNode); } - + this.Bind(objNodes); // technically this should always be a dnntree. If using dynamic controls Nav.ascx should be used. just being safe. @@ -500,7 +500,7 @@ private void ProcessNodes(DNNNode objParent) { objParent.Image = this.ResolveUrl(this.NodeLeafImage); } - + foreach (DNNNode objNode in objParent.DNNNodes) { this.ProcessNodes(objNode); @@ -520,62 +520,62 @@ private void InitializeTree() { this.PathImage = this.PortalSettings.HomeDirectory; } - + if (string.IsNullOrEmpty(this.PathSystemImage)) { this.PathSystemImage = this.ResolveUrl("~/images/"); } - + if (string.IsNullOrEmpty(this.IndicateChildImageRoot)) { this.IndicateChildImageRoot = this.ResolveUrl(this.NodeExpandImage); } - + if (string.IsNullOrEmpty(this.IndicateChildImageSub)) { this.IndicateChildImageSub = this.ResolveUrl(this.NodeExpandImage); } - + if (string.IsNullOrEmpty(this.IndicateChildImageExpandedRoot)) { this.IndicateChildImageExpandedRoot = this.ResolveUrl(this.NodeCollapseImage); } - + if (string.IsNullOrEmpty(this.IndicateChildImageExpandedSub)) { this.IndicateChildImageExpandedSub = this.ResolveUrl(this.NodeCollapseImage); } - + if (string.IsNullOrEmpty(this.CSSNode)) { this.CSSNode = this.NodeChildCssClass; } - + if (string.IsNullOrEmpty(this.CSSNodeRoot)) { this.CSSNodeRoot = this.NodeCssClass; } - + if (string.IsNullOrEmpty(this.CSSNodeHover)) { this.CSSNodeHover = this.NodeOverCssClass; } - + if (string.IsNullOrEmpty(this.CSSNodeSelectedRoot)) { this.CSSNodeSelectedRoot = this.NodeSelectedCssClass; } - + if (string.IsNullOrEmpty(this.CSSNodeSelectedSub)) { this.CSSNodeSelectedSub = this.NodeSelectedCssClass; } - + if (string.IsNullOrEmpty(this.CSSControl)) { this.CSSControl = this.TreeCssClass; } - } + } /// ----------------------------------------------------------------------------- /// @@ -592,7 +592,7 @@ private void DNNTree_NodeClick(NavigationEventArgs args) { args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - + this.Response.Redirect(Globals.ApplicationURL(int.Parse(args.Node.Key)), true); } @@ -602,7 +602,7 @@ private void DNNTree_PopulateOnDemand(NavigationEventArgs args) { args.Node = Navigation.GetNavigationNode(args.ID, this.Control.ID); } - + this.BuildTree(args.Node, true); } } diff --git a/DNN Platform/Website/admin/Skins/User.ascx.cs b/DNN Platform/Website/admin/Skins/User.ascx.cs index 0e0727cff3d..a5482165000 100644 --- a/DNN Platform/Website/admin/Skins/User.ascx.cs +++ b/DNN Platform/Website/admin/Skins/User.ascx.cs @@ -74,15 +74,15 @@ protected override void OnLoad(EventArgs e) try { - if (this.LegacyMode) - { - this.registerGroup.Visible = false; - } - else - { - this.registerLink.Visible = false; - } - + if (this.LegacyMode) + { + this.registerGroup.Visible = false; + } + else + { + this.registerLink.Visible = false; + } + if (!string.IsNullOrEmpty(this.CssClass)) { this.registerLink.CssClass = this.CssClass; @@ -103,7 +103,7 @@ protected override void OnLoad(EventArgs e) { this.Text = this.Text.Replace("src=\"", "src=\"" + this.PortalSettings.ActiveTab.SkinPath); } - + this.registerLink.Text = this.Text; this.enhancedRegisterLink.Text = this.Text; } @@ -114,17 +114,17 @@ protected override void OnLoad(EventArgs e) this.registerLink.ToolTip = this.registerLink.Text; this.enhancedRegisterLink.ToolTip = this.registerLink.Text; } - + if (this.PortalSettings.Users < this.PortalSettings.UserQuota || this.PortalSettings.UserQuota == 0) { - if (this.LegacyMode) - { - this.registerLink.Visible = true; - } - else - { - this.enhancedRegisterLink.Visible = true; - } + if (this.LegacyMode) + { + this.registerLink.Visible = true; + } + else + { + this.enhancedRegisterLink.Visible = true; + } } else { @@ -219,12 +219,12 @@ private int GetMessageTab() { var cacheKey = string.Format("MessageCenterTab:{0}:{1}", this.PortalSettings.PortalId, this.PortalSettings.CultureCode); var messageTabId = DataCache.GetCache(cacheKey); - if (messageTabId > 0) - { - return messageTabId; - } - - // Find the Message Tab + if (messageTabId > 0) + { + return messageTabId; + } + + // Find the Message Tab messageTabId = this.FindMessageTab(); // save in cache diff --git a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs index 3091051faee..68892be0d7a 100644 --- a/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs +++ b/DNN Platform/Website/admin/Skins/UserAndLogin.ascx.cs @@ -73,7 +73,7 @@ protected string LoginUrl { returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=", StringComparison.Ordinal)); } - + returnUrl = HttpUtility.UrlEncode(returnUrl); return Globals.LoginURL(returnUrl, this.Request.QueryString["override"] != null); @@ -204,12 +204,12 @@ private int GetMessageTab() { var cacheKey = string.Format("MessageCenterTab:{0}:{1}", this.PortalSettings.PortalId, this.PortalSettings.CultureCode); var messageTabId = DataCache.GetCache(cacheKey); - if (messageTabId > 0) - { - return messageTabId; - } - - // Find the Message Tab + if (messageTabId > 0) + { + return messageTabId; + } + + // Find the Message Tab messageTabId = this.FindMessageTab(); // save in cache diff --git a/DNN Platform/Website/admin/Skins/jQuery.ascx.cs b/DNN Platform/Website/admin/Skins/jQuery.ascx.cs index 8a1b7249d1b..9ce2c463cbd 100644 --- a/DNN Platform/Website/admin/Skins/jQuery.ascx.cs +++ b/DNN Platform/Website/admin/Skins/jQuery.ascx.cs @@ -11,9 +11,9 @@ namespace DotNetNuke.UI.Skins.Controls public partial class jQuery : SkinObjectBase { public bool DnnjQueryPlugins { get; set; } - + public bool jQueryHoverIntent { get; set; } - + public bool jQueryUI { get; set; } protected override void OnInit(EventArgs e) diff --git a/DNN Platform/Website/admin/Skins/tags.ascx.cs b/DNN Platform/Website/admin/Skins/tags.ascx.cs index d5418547790..16c650d1f76 100644 --- a/DNN Platform/Website/admin/Skins/tags.ascx.cs +++ b/DNN Platform/Website/admin/Skins/tags.ascx.cs @@ -35,7 +35,7 @@ public string AddImageUrl { return this._AddImageUrl; } - + set { this._AddImageUrl = value; @@ -48,7 +48,7 @@ public bool AllowTagging { return this._AllowTagging; } - + set { this._AllowTagging = value; @@ -61,7 +61,7 @@ public string CancelImageUrl { return this._CancelImageUrl; } - + set { this._CancelImageUrl = value; @@ -76,7 +76,7 @@ public string ObjectType { return this._ObjectType; } - + set { this._ObjectType = value; @@ -89,7 +89,7 @@ public string RepeatDirection { return this._RepeatDirection; } - + set { this._RepeatDirection = value; @@ -102,7 +102,7 @@ public string SaveImageUrl { return this._SaveImageUrl; } - + set { this._SaveImageUrl = value; @@ -115,7 +115,7 @@ public string Separator { return this._Separator; } - + set { this._Separator = value; @@ -128,7 +128,7 @@ public bool ShowCategories { return this._ShowCategories; } - + set { this._ShowCategories = value; @@ -141,7 +141,7 @@ public bool ShowTags { return this._ShowTags; } - + set { this._ShowTags = value; diff --git a/DNN Platform/Website/admin/Tabs/Export.ascx.cs b/DNN Platform/Website/admin/Tabs/Export.ascx.cs index 0c4365f55d8..8905d9c1849 100644 --- a/DNN Platform/Website/admin/Tabs/Export.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Export.ascx.cs @@ -39,11 +39,11 @@ public TabInfo Tab { this._tab = TabController.Instance.GetTab(this.TabId, this.PortalId, false); } - + return this._tab; } } - + protected override void OnInit(EventArgs e) { base.OnInit(e); @@ -62,11 +62,11 @@ protected override void OnLoad(EventArgs e) try { - if (this.Page.IsPostBack) - { - return; - } - + if (this.Page.IsPostBack) + { + return; + } + this.cmdCancel.NavigateUrl = this._navigationManager.NavigateURL(); var folderPath = "Templates/"; var templateFolder = FolderManager.Instance.GetFolder(this.UserInfo.PortalID, folderPath); @@ -88,20 +88,6 @@ protected override void OnLoad(EventArgs e) } } - /// ----------------------------------------------------------------------------- - /// - /// 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 void OnExportClick(object sender, EventArgs e) { try @@ -149,7 +135,21 @@ protected void OnExportClick(object sender, EventArgs e) { Exceptions.ProcessModuleLoadException(this, exc); } - } + } + + /// ----------------------------------------------------------------------------- + /// + /// 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)); + } private bool IsAccessibleByUser(IFolderInfo folder) { diff --git a/DNN Platform/Website/admin/Tabs/Import.ascx.cs b/DNN Platform/Website/admin/Tabs/Import.ascx.cs index e843961daff..0206b902aa4 100644 --- a/DNN Platform/Website/admin/Tabs/Import.ascx.cs +++ b/DNN Platform/Website/admin/Tabs/Import.ascx.cs @@ -43,7 +43,7 @@ public TabInfo Tab { this._tab = TabController.Instance.GetTab(this.TabId, this.PortalId, false); } - + return this._tab; } } @@ -76,11 +76,11 @@ protected override void OnLoad(EventArgs e) 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; - } - + if (templateFolder != null) + { + this.cboFolders.SelectedFolder = templateFolder; + } + this.BindFiles(); this.BindTabControls(); this.DisplayNewRows(); @@ -92,64 +92,6 @@ protected override void OnLoad(EventArgs e) } } - private void BindBeforeAfterTabControls() - { - var noneSpecified = "<" + Localization.GetString("None_Specified") + ">"; - this.cboParentTab.UndefinedItem = new ListItem(noneSpecified, string.Empty); - var parentTab = this.cboParentTab.SelectedPage; - - List listTabs = parentTab != null ? TabController.Instance.GetTabsByPortal(parentTab.PortalID).WithParentId(parentTab.TabID) : TabController.Instance.GetTabsByPortal(this.PortalId).WithParentId(Null.NullInteger); - listTabs = TabController.GetPortalTabs(listTabs, Null.NullInteger, true, noneSpecified, false, false, false, false, true); - this.cboPositionTab.DataSource = listTabs; - this.cboPositionTab.DataBind(); - this.rbInsertPosition.Items.Clear(); - this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertBefore", this.LocalResourceFile), "Before")); - this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAfter", this.LocalResourceFile), "After")); - this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAtEnd", this.LocalResourceFile), "AtEnd")); - this.rbInsertPosition.SelectedValue = "After"; - } - - private void BindFiles() - { - this.cboTemplate.Items.Clear(); - if (this.cboFolders.SelectedItem != null) - { - var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); - if (folder != null) - { - // var files = Directory.GetFiles(PortalSettings.HomeDirectoryMapPath + folder.FolderPath, "*.page.template"); - var files = Globals.GetFileList(this.PortalId, "page.template", false, folder.FolderPath); - foreach (FileItem file in files) - { - this.cboTemplate.AddItem(file.Text.Replace(".page.template", string.Empty), file.Value); - } - - this.cboTemplate.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "None_Specified"); - this.cboTemplate.SelectedIndex = 0; - } - } - } - - private void BindTabControls() - { - this.BindBeforeAfterTabControls(); - this.divInsertPositionRow.Visible = this.cboPositionTab.Items.Count > 0; - this.cboParentTab.AutoPostBack = true; - if (this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)) != null) - { - this.cboPositionTab.ClearSelection(); - this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)).Selected = true; - } - } - - private void DisplayNewRows() - { - this.divTabName.Visible = this.optMode.SelectedIndex == 0; - this.divParentTab.Visible = this.optMode.SelectedIndex == 0; - this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; - this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; - } - protected void OnFolderIndexChanged(object sender, EventArgs e) { this.BindFiles(); @@ -164,24 +106,24 @@ protected void OnImportClick(object sender, EventArgs e) UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyFile", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - + if (this.optMode.SelectedIndex == -1) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("SpecifyMode", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); return; } - - if (this.cboFolders.SelectedItem == null) - { - return; - } - + + if (this.cboFolders.SelectedItem == null) + { + return; + } + var selectedFolder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); - if (selectedFolder == null) - { - return; - } - + if (selectedFolder == null) + { + return; + } + var selectedFile = Services.FileSystem.FileManager.Instance.GetFile(Convert.ToInt32(this.cboTemplate.SelectedValue)); var xmlDoc = new XmlDocument { XmlResolver = null }; using (var content = Services.FileSystem.FileManager.Instance.GetFileContent(selectedFile)) @@ -195,7 +137,7 @@ protected void OnImportClick(object sender, EventArgs e) { tabNodes.AddRange(selectSingleNode.ChildNodes.Cast()); } - + if (tabNodes.Count == 0) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("NoTabsInTemplate", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); @@ -221,7 +163,7 @@ protected void OnImportClick(object sender, EventArgs e) { objTab.ParentId = parentId; } - + objTab.TabPath = Globals.GenerateTabPath(objTab.ParentId, objTab.TabName); var tabId = TabController.GetTabByTabPath(objTab.PortalID, objTab.TabPath, Null.NullString); @@ -237,7 +179,7 @@ protected void OnImportClick(object sender, EventArgs e) { UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("TabExists", this.LocalResourceFile), ModuleMessage.ModuleMessageType.RedError); } - + return; } @@ -255,13 +197,13 @@ protected void OnImportClick(object sender, EventArgs e) { objTab.TabID = TabController.Instance.AddTab(objTab); } - + EventLogController.Instance.AddLog(objTab, this.PortalSettings, this.UserId, string.Empty, EventLogController.EventLogType.TAB_CREATED); objTab = TabController.DeserializeTab(tabNodes[0], objTab, this.PortalId, PortalTemplateModuleAction.Replace); var exceptions = string.Empty; - + // Create second tabs onwards. For firs tab, we like to use tab details from text box, for rest it'll come from template for (var tab = 1; tab < tabNodes.Count; tab++) { @@ -275,7 +217,7 @@ protected void OnImportClick(object sender, EventArgs e) exceptions += string.Format("Template Tab # {0}. Error {1}
    ", tab + 1, ex.Message); } } - + if (!string.IsNullOrEmpty(exceptions)) { UI.Skins.Skin.AddModuleMessage(this, exceptions, ModuleMessage.ModuleMessageType.RedError); @@ -287,7 +229,7 @@ protected void OnImportClick(object sender, EventArgs e) // Replace Existing Tab objTab = TabController.DeserializeTab(tabNodes[0], this.Tab, this.PortalId, PortalTemplateModuleAction.Replace); } - + switch (this.optRedirect.SelectedValue) { case "VIEW": @@ -348,5 +290,63 @@ protected void OptModeSelectedIndexChanged(object sender, EventArgs e) { this.DisplayNewRows(); } + + private void BindBeforeAfterTabControls() + { + var noneSpecified = "<" + Localization.GetString("None_Specified") + ">"; + this.cboParentTab.UndefinedItem = new ListItem(noneSpecified, string.Empty); + var parentTab = this.cboParentTab.SelectedPage; + + List listTabs = parentTab != null ? TabController.Instance.GetTabsByPortal(parentTab.PortalID).WithParentId(parentTab.TabID) : TabController.Instance.GetTabsByPortal(this.PortalId).WithParentId(Null.NullInteger); + listTabs = TabController.GetPortalTabs(listTabs, Null.NullInteger, true, noneSpecified, false, false, false, false, true); + this.cboPositionTab.DataSource = listTabs; + this.cboPositionTab.DataBind(); + this.rbInsertPosition.Items.Clear(); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertBefore", this.LocalResourceFile), "Before")); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAfter", this.LocalResourceFile), "After")); + this.rbInsertPosition.Items.Add(new ListItem(Localization.GetString("InsertAtEnd", this.LocalResourceFile), "AtEnd")); + this.rbInsertPosition.SelectedValue = "After"; + } + + private void BindFiles() + { + this.cboTemplate.Items.Clear(); + if (this.cboFolders.SelectedItem != null) + { + var folder = FolderManager.Instance.GetFolder(this.cboFolders.SelectedItemValueAsInt); + if (folder != null) + { + // var files = Directory.GetFiles(PortalSettings.HomeDirectoryMapPath + folder.FolderPath, "*.page.template"); + var files = Globals.GetFileList(this.PortalId, "page.template", false, folder.FolderPath); + foreach (FileItem file in files) + { + this.cboTemplate.AddItem(file.Text.Replace(".page.template", string.Empty), file.Value); + } + + this.cboTemplate.InsertItem(0, "<" + Localization.GetString("None_Specified") + ">", "None_Specified"); + this.cboTemplate.SelectedIndex = 0; + } + } + } + + private void BindTabControls() + { + this.BindBeforeAfterTabControls(); + this.divInsertPositionRow.Visible = this.cboPositionTab.Items.Count > 0; + this.cboParentTab.AutoPostBack = true; + if (this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)) != null) + { + this.cboPositionTab.ClearSelection(); + this.cboPositionTab.FindItemByValue(this.TabId.ToString(CultureInfo.InvariantCulture)).Selected = true; + } + } + + private void DisplayNewRows() + { + this.divTabName.Visible = this.optMode.SelectedIndex == 0; + this.divParentTab.Visible = this.optMode.SelectedIndex == 0; + this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; + this.divInsertPositionRow.Visible = this.optMode.SelectedIndex == 0; + } } } diff --git a/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs b/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs index 0c010d27a4d..941a9a61977 100644 --- a/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs +++ b/DNN Platform/Website/admin/Users/ViewProfile.ascx.cs @@ -23,7 +23,7 @@ protected override void OnInit(EventArgs e) { this.UserId = int.Parse(UrlUtils.DecryptParameter(this.Context.Request.QueryString["userticket"])); } - + this.ctlProfile.ID = "Profile"; this.ctlProfile.UserId = this.UserId; } @@ -38,7 +38,7 @@ protected override void OnLoad(EventArgs e) this.lblNoProperties.Visible = true; return; } - + this.ctlProfile.DataBind(); if (this.ctlProfile.UserProfile.ProfileProperties.Cast().Count(profProperty => profProperty.Visible) == 0) { diff --git a/DNN_Platform.sln.DotSettings b/DNN_Platform.sln.DotSettings index abf45f8c9f2..50a2c21982c 100644 --- a/DNN_Platform.sln.DotSettings +++ b/DNN_Platform.sln.DotSettings @@ -1,2 +1,144 @@  + <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"> +<TypePattern DisplayName="StyleCop Classes, Interfaces, &amp; Structs" RemoveRegions="All"> + <TypePattern.Match> + <Or> + <Kind Is="Class" /> + <Kind Is="Struct" /> + <Kind Is="Interface" /> + </Or> + </TypePattern.Match> + <Entry DisplayName="Constants"> + <Entry.Match> + <Kind Is="Constant" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Fields"> + <Entry.Match> + <Kind Is="Field" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Constructors"> + <Entry.Match> + <Kind Is="Constructor" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Destructors"> + <Entry.Match> + <Kind Is="Destructor" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Delegates"> + <Entry.Match> + <Kind Is="Delegate" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Events"> + <Entry.Match> + <Kind Is="Event" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Enums"> + <Entry.Match> + <Kind Is="Enum" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Interfaces"> + <Entry.Match> + <Kind Is="Interface" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Properties"> + <Entry.Match> + <Kind Is="Property" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Indexers"> + <Entry.Match> + <Kind Is="Indexer" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Methods"> + <Entry.Match> + <Kind Is="Method" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Structs"> + <Entry.Match> + <Kind Is="Struct" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> + <Entry DisplayName="Classes"> + <Entry.Match> + <Kind Is="Class" /> + </Entry.Match> + <Entry.SortBy> + <Access Order="Public Internal ProtectedInternal Protected Private" /> + <Static /> + <Readonly /> + </Entry.SortBy> + </Entry> +</TypePattern> +</Patterns> + False \ No newline at end of file diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs index 3a5d228f829..ede2d21c357 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Common/ControllerBase.cs @@ -13,7 +13,6 @@ namespace Dnn.PersonaBar.Prompt.Common public abstract class ControllerBase : PersonaBarApiController { - protected HttpResponseMessage OkResponse(string msg, object data = null) { return this.Request.CreateResponse(HttpStatusCode.OK, new ResponseModel(false, msg, data?.ToString() ?? "")); @@ -58,6 +57,5 @@ protected HttpResponseMessage NotImplementedResponse(string msg = "", object dat } return this.Request.CreateResponse(HttpStatusCode.NotImplemented, new ResponseModel(true, msg, data?.ToString() ?? "")); } - } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs index ad69e97b122..3fae310bd22 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/AdminLogs/AdminLogsController.cs @@ -251,8 +251,8 @@ public string EmailLogItems(string subject, string fromEmailAddress, string toEm error = Localization.GetString("EmailFailure", Constants.LocalResourcesFile); } return returnMsg; - } - + } + private XmlDocument GetExceptions(IEnumerable logIds) { var objXml = new XmlDocument { XmlResolver = null }; @@ -267,6 +267,6 @@ private XmlDocument GetExceptions(IEnumerable logIds) } } return objXml; - } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs index bd16eae1bf3..5a275953da0 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/ConfigConsole/ConfigConsoleController.cs @@ -57,8 +57,8 @@ public void MergeConfigFile(string fileContent) var merge = new DotNetNuke.Services.Installer.XmlMerge(doc, Globals.FormatVersion(app.Version), app.Description); merge.UpdateConfigs(); } - } - + } + private bool IsValidXmlMergDocument(string mergeDocText) { if (string.IsNullOrEmpty(mergeDocText.Trim())) @@ -77,6 +77,6 @@ private void ValidateFilePath(string filePath) { throw new ArgumentException("Invalid File Path"); } - } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs index 7007874d948..8cfe9e78b88 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/CreateModuleController.cs @@ -30,6 +30,7 @@ public CreateModuleController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } /// 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 4caac598c25..5105ba42def 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreateModuleDto.cs @@ -34,6 +34,5 @@ public class CreateModuleDto [JsonProperty("addPage")] public bool AddPage { get; set; } - } } 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 53c98992d36..1f7c6786216 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/CreatePackageDto.cs @@ -6,7 +6,5 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto { public class CreatePackageDto : PackageInfoDto - { - - } + {} } 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 8a7a4e6f835..8818e2d1a39 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 @@ -16,7 +16,7 @@ public AuthSystemPackageDetailDto() public AuthSystemPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { } - + [JsonProperty("authenticationType")] public string AuthenticationType { get; set; } 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 4d31029f0fb..fd946b93da2 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 @@ -18,7 +18,7 @@ public CoreLanguagePackageDetailDto() public CoreLanguagePackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { } - + [JsonProperty("locales")] public IEnumerable Locales { get; set; } 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 dcfc7cc3893..3d6b55a9080 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 @@ -16,7 +16,7 @@ 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 bfe7365723e..c24016de6b8 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 @@ -17,8 +17,8 @@ public JsLibraryPackageDetailDto() public JsLibraryPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { - } - + } + [JsonProperty("objectName")] public string ObjectName { get; set; } 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 ce8ca37ed29..42d63672b68 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 @@ -10,16 +10,16 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto.Editors public class ModulePackagePermissionsDto : PackageInfoDto { 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 a908f5e8214..cd463511992 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 @@ -16,7 +16,7 @@ public SkinObjectPackageDetailDto() public SkinObjectPackageDetailDto(int portalId, PackageInfo package) : base(portalId, package) { } - + [JsonProperty("controlKey")] public string ControlKey { get; set; } 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 9c3154799e8..642850661eb 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 @@ -16,7 +16,7 @@ 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/PackageInfoSlimDto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs index dafde6aecd6..806acf3c1a5 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageInfoSlimDto.cs @@ -37,7 +37,7 @@ public PackageInfoSlimDto(int portalId, PackageInfo package) this.ReadOnly = authService != null && authService.AuthenticationType == Constants.DnnAuthTypeName; } } - + [JsonProperty("packageId")] public int PackageId { get; set; } 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 e299ae884bd..0cd37b73375 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/PackageManifestDto.cs @@ -12,13 +12,13 @@ namespace Dnn.PersonaBar.Extensions.Components.Dto public class PackageManifestDto : PackageInfoDto { public PackageManifestDto() - { + { } public PackageManifestDto(int portalId, PackageInfo package) : base(portalId, package) - { + { } - + [JsonProperty("archiveName")] public string ArchiveName { get; set; } 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 e3dc21a2531..67d88ebc606 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Dto/ParseResultDto.cs @@ -23,7 +23,7 @@ public ParseResultDto() public ParseResultDto(PackageInfo package) : base(Null.NullInteger, package) { } - + [JsonProperty("success")] public bool Success { get; set; } = true; 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 79901e44950..cbf8866d11f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/AuthSystemPackageEditor.cs @@ -21,8 +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(); - + private static readonly INavigationManager NavigationManager = Globals.DependencyProvider.GetRequiredService(); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var authSystem = AuthenticationController.GetAuthenticationServiceByPackageID(package.PackageID); @@ -93,8 +93,8 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } - + } + private static string GetSettingUrl(int portalId, int authSystemPackageId) { return NavigationManager.NavigateURL(PortalSettings.Current.ActiveTab.TabID, PortalSettings.Current, "EditExtension", @@ -170,6 +170,6 @@ private static void SaveCustomSettings(PackageSettingsDto packageSettings) break; } } - } + } } } 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 f97f17ef188..a6b2390c956 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/CoreLanguagePackageEditor.cs @@ -20,10 +20,12 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class CoreLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); + 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 fabb3230d98..cec68d4bcd6 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ExtensionLanguagePackageEditor.cs @@ -20,11 +20,12 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class ExtensionLanguagePackageEditor : IPackageEditor { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); + 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 8d0b62d7473..4c6d83f0e6b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/JsLibraryPackageEditor.cs @@ -16,11 +16,11 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class JsLibraryPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(JsLibraryPackageEditor)); - + 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); @@ -72,6 +72,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } + } } } 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 a88d43efdb3..d89b01f6703 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/ModulePackageEditor.cs @@ -24,8 +24,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class ModulePackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(ModulePackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var desktopModule = DesktopModuleController.GetDesktopModuleByPackageID(package.PackageID); @@ -33,8 +33,8 @@ public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) if (desktopModule == null) { return new PackageInfoDto(portalId, package); - } - + } + var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; var detail = isHostUser ? new ModulePackageDetailDto(portalId, package, desktopModule) @@ -125,7 +125,7 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } + } private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) { @@ -134,7 +134,37 @@ private static void UnassignPortals(DesktopModuleInfo desktopModule, IList portals) + { + foreach (var portal in portals) + { + DesktopModuleController.AddDesktopModuleToPortal(portal.Id, desktopModule.DesktopModuleID, true, true); + } + } + + private static void SaveModuleDefinition(ModuleDefinitionDto definitionDto) + { + var moduleDefinition = definitionDto.ToModuleDefinitionInfo(); + ModuleDefinitionController.SaveModuleDefinition(moduleDefinition, false, true); + } + + private static void DeleteModuleDefinition(int defId) + { + new ModuleDefinitionController().DeleteModuleDefinition(defId); + } + + private static void SaveModuleControl(ModuleControlDto moduleControlDto) + { + var moduleControl = moduleControlDto.ToModuleControlInfo(); + ModuleControlController.SaveModuleControl(moduleControl, true); + } + + private static void DeleteModuleControl(int controlId) + { + ModuleControlController.DeleteModuleControl(controlId); + } + private PermissionsDto GetPermissionsData(int portalId, int desktopModuleId) { var permissions = new PermissionsDto(true); @@ -227,7 +257,7 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD } } } - + //add user permissions if (permissions.UserPermissions != null) { @@ -261,35 +291,5 @@ private void UpdatePermissions(DesktopModuleInfo desktopModule, PackageSettingsD } DataCache.RemoveCache(string.Format(DataCache.PortalDesktopModuleCacheKey, portalSettings.PortalId)); } - - private static void AssignPortals(DesktopModuleInfo desktopModule, IList portals) - { - foreach (var portal in portals) - { - DesktopModuleController.AddDesktopModuleToPortal(portal.Id, desktopModule.DesktopModuleID, true, true); - } - } - - private static void SaveModuleDefinition(ModuleDefinitionDto definitionDto) - { - var moduleDefinition = definitionDto.ToModuleDefinitionInfo(); - ModuleDefinitionController.SaveModuleDefinition(moduleDefinition, false, true); - } - - private static void DeleteModuleDefinition(int defId) - { - new ModuleDefinitionController().DeleteModuleDefinition(defId); - } - - private static void SaveModuleControl(ModuleControlDto moduleControlDto) - { - var moduleControl = moduleControlDto.ToModuleControlInfo(); - ModuleControlController.SaveModuleControl(moduleControl, true); - } - - private static void DeleteModuleControl(int controlId) - { - ModuleControlController.DeleteModuleControl(controlId); - } } } 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 96441b935ac..1404460963e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinObjectPackageEditor.cs @@ -15,8 +15,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class SkinObjectPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinObjectPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var skinControl = SkinControlController.GetSkinControlByPackageID(package.PackageID); @@ -26,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; } @@ -67,6 +67,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } + } } } 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 e495362bcb3..c298fd48113 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Editors/SkinPackageEditor.cs @@ -15,8 +15,8 @@ namespace Dnn.PersonaBar.Extensions.Components.Editors public class SkinPackageEditor : IPackageEditor { - private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); - + private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SkinPackageEditor)); + public PackageInfoDto GetPackageDetail(int portalId, PackageInfo package) { var isHostUser = UserController.Instance.GetCurrentUserInfo().IsSuperUser; @@ -59,6 +59,6 @@ public bool SavePackageSettings(PackageSettingsDto packageSettings, out string e errorMessage = ex.Message; return false; } - } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs index c51115e76dc..f9a6d1cf13f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/ExtensionsController.cs @@ -28,10 +28,12 @@ namespace Dnn.PersonaBar.Extensions.Components public class ExtensionsController { private const string OwnerUpdateService = "DotNetNuke Update Service"; + public ExtensionsController() { this.NavigationManager = Globals.DependencyProvider.GetRequiredService(); } + protected INavigationManager NavigationManager { get; } public IDictionary GetPackageTypes() @@ -158,80 +160,6 @@ public List GetPackageUsage(int portalId, int packageId) return null; } - private void GetAvaialableLanguagePacks(IDictionary validPackages) - { - try - { - StreamReader myResponseReader = UpdateService.GetLanguageList(); - var xmlDoc = new XmlDocument { XmlResolver = null }; - xmlDoc.Load(myResponseReader); - XmlNodeList languages = xmlDoc.SelectNodes("available/language"); - - if (languages != null) - { - var installedPackages = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack"); - var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList(); - foreach (XmlNode language in languages) - { - string cultureCode = ""; - string version = ""; - foreach (XmlNode child in language.ChildNodes) - { - if (child.Name == "culturecode") - { - cultureCode = child.InnerText; - } - - if (child.Name == "version") - { - version = child.InnerText; - } - } - if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6) - { - var myCIintl = new CultureInfo(cultureCode, true); - version = version.Insert(4, ".").Insert(2, "."); - var package = new PackageInfo { Owner = OwnerUpdateService, Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName }; - package.Name = myCIintl.NativeName; - package.PackageType = "CoreLanguagePack"; - package.Description = cultureCode; - Version ver = null; - Version.TryParse(version, out ver); - package.Version = ver; - - if ( - installedLanguages.Any( - l => - LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant()) - && installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver)) - { - continue; - } - - if (validPackages.Values.Any(p => p.Name == package.Name)) - { - var existPackage = validPackages.Values.First(p => p.Name == package.Name); - if (package.Version > existPackage.Version) - { - existPackage.Version = package.Version; - } - } - else - { - validPackages.Add(cultureCode, package); - } - } - } - } - } - catch (Exception) - { - //suppress for now - need to decide what to do when webservice is unreachable - //throw; - //same problem happens in InstallWizard.aspx.cs in BindLanguageList method - } - } - public string GetFormattedTabLink(int portalId, TabInfo tab) { var returnValue = new StringBuilder(); @@ -263,7 +191,7 @@ public string GetFormattedTabLink(int portalId, TabInfo tab) } return returnValue.ToString(); - } + } internal static string IsPackageInUse(PackageInfo packageInfo, int portalId) { @@ -285,16 +213,6 @@ 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) { @@ -346,6 +264,16 @@ internal static IDictionary GetPackagesInUse(bool forHost) return PackageController.GetModulePackagesInUse(PortalController.Instance.GetCurrentPortalSettings().PortalId, forHost); } + 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); + } + private static string FixIconUrl(string url) { return !string.IsNullOrEmpty(Globals.ApplicationPath) @@ -398,6 +326,80 @@ private static bool IconExists(string imagePath) return false; } - } + } + + private void GetAvaialableLanguagePacks(IDictionary validPackages) + { + try + { + StreamReader myResponseReader = UpdateService.GetLanguageList(); + var xmlDoc = new XmlDocument { XmlResolver = null }; + xmlDoc.Load(myResponseReader); + XmlNodeList languages = xmlDoc.SelectNodes("available/language"); + + if (languages != null) + { + var installedPackages = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack"); + var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList(); + foreach (XmlNode language in languages) + { + string cultureCode = ""; + string version = ""; + foreach (XmlNode child in language.ChildNodes) + { + if (child.Name == "culturecode") + { + cultureCode = child.InnerText; + } + + if (child.Name == "version") + { + version = child.InnerText; + } + } + if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6) + { + var myCIintl = new CultureInfo(cultureCode, true); + version = version.Insert(4, ".").Insert(2, "."); + var package = new PackageInfo { Owner = OwnerUpdateService, Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName }; + package.Name = myCIintl.NativeName; + package.PackageType = "CoreLanguagePack"; + package.Description = cultureCode; + Version ver = null; + Version.TryParse(version, out ver); + package.Version = ver; + + if ( + installedLanguages.Any( + l => + LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant()) + && installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver)) + { + continue; + } + + if (validPackages.Values.Any(p => p.Name == package.Name)) + { + var existPackage = validPackages.Values.First(p => p.Name == package.Name); + if (package.Version > existPackage.Version) + { + existPackage.Version = package.Version; + } + } + else + { + validPackages.Add(cultureCode, package); + } + } + } + } + } + catch (Exception) + { + //suppress for now - need to decide what to do when webservice is unreachable + //throw; + //same problem happens in InstallWizard.aspx.cs in BindLanguageList method + } + } } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs index 1431b4dbbc5..35a74dc3f80 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/InstallController.cs @@ -89,11 +89,6 @@ 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(); @@ -159,6 +154,11 @@ public InstallResultDto InstallPackage(PortalSettings portalSettings, UserInfo u return installResult; } + protected override Func GetFactory() + { + return () => new InstallController(); + } + private static Installer GetInstaller(Stream stream, string fileName, int portalId, string legacySkin = null, bool isPortalPackage = false) { var installer = new Installer(stream, Globals.ApplicationMapPath, false, false); @@ -226,8 +226,8 @@ private static void DeleteInstallFile(string installerFile) try { if (File.Exists(installerFile)) - { - File.SetAttributes(installerFile, FileAttributes.Normal); + { + File.SetAttributes(installerFile, FileAttributes.Normal); File.Delete(installerFile); } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs index 612ce37ed8a..b760ca1208e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Extensions/Utility.cs @@ -14,7 +14,6 @@ namespace Dnn.PersonaBar.Extensions.Components public static class Utility { - public static IEnumerable GetAllLanguagesList() { var locales = LocaleController.Instance.GetLocales(Null.NullInteger).Values; @@ -33,6 +32,5 @@ public static IEnumerable GetAllPackagesListExceptLangPacks() } return packages.OrderBy(p => p.Name); } - } } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs index d18a9995b8d..ce762638b2a 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/BulkPagesController.cs @@ -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); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs index a12b3e1108f..53c59f72b9e 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Converters.cs @@ -28,6 +28,7 @@ namespace Dnn.PersonaBar.Pages.Components public static class Converters { private static readonly INavigationManager _navigationManager = Globals.DependencyProvider.GetRequiredService(); + public static T ConvertToPageItem(TabInfo tab, IEnumerable portalTabs) where T : PageItem, new() { return new T 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 8b8092f0fce..595c51aa9bd 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/BulkPagesException.cs @@ -12,7 +12,7 @@ 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/PageModuleNotFoundException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs index 02c8d081b82..d98f6d6ee27 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageModuleNotFoundException.cs @@ -7,6 +7,5 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions using System; public class PageModuleNotFoundException : Exception - { - } + {} } diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs index 747fc2a21bb..f37e7085096 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageNotFoundException.cs @@ -7,6 +7,5 @@ namespace Dnn.PersonaBar.Pages.Components.Exceptions using System; public class PageNotFoundException : Exception - { - } + {} } 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 1a99c6cef95..41b91091920 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Exceptions/PageValidationException.cs @@ -12,7 +12,7 @@ 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/FriendlyUrlWrapper.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/FriendlyUrlWrapper.cs index c1e210691f7..68d690c6a2d 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/IPagesController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/IPagesController.cs index a818e69be8f..4a594810535 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); @@ -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 9b0f46888a6..1b5e04ea242 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageManagementController.cs @@ -22,8 +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 ee31b7bdd07..68aba659c4b 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PageUrlsController.cs @@ -22,12 +22,12 @@ 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, } protected IEnumerable> StatusCodes @@ -43,7 +43,7 @@ protected IEnumerable> StatusCodes } 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(); @@ -75,7 +75,7 @@ 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"), @@ -87,7 +87,7 @@ 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"), @@ -98,7 +98,7 @@ 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") @@ -285,7 +285,7 @@ public PageUrlResult UpdateCustomUrl(SaveUrlDto dto, TabInfo tab) TabController.Instance.SaveTabUrl(tabUrl, portalSettings.PortalId, true); } } - + return new PageUrlResult { Success = true @@ -482,6 +482,7 @@ private void AddUrlToList(List tabs, int portalId, int id, PortalAliasInfo UserName = userName }); } + private string GetCleanPath(string path, FriendlyUrlSettings friendlyUrlSettings) { if (string.IsNullOrEmpty(path)) @@ -494,6 +495,7 @@ private string GetCleanPath(string path, FriendlyUrlSettings friendlyUrlSettings return string.Format("/{0}", urlPath); } + public class KeyValuePairComparer : IComparer> { public int Compare(KeyValuePair pair1, KeyValuePair pair2) diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs index a210d9ace2e..b8c933871c5 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/PagesControllerImpl.cs @@ -38,7 +38,8 @@ namespace Dnn.PersonaBar.Pages.Components public class PagesControllerImpl : IPagesController { public const string PageTagsVocabulary = "PageTags"; - + + private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; private readonly ITabController _tabController; private readonly IModuleController _moduleController; private readonly IPageUrlsController _pageUrlsController; @@ -49,7 +50,6 @@ public class PagesControllerImpl : IPagesController private readonly IFriendlyUrlWrapper _friendlyUrlWrapper; private readonly IContentVerifier _contentVerifier; private readonly IPortalController _portalController; - private static readonly IList TabSettingKeys = new List { "CustomStylesheet" }; public PagesControllerImpl() : this( @@ -89,10 +89,11 @@ 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(); @@ -166,7 +167,7 @@ public List GetPageHierarchy(int pageId) return paths; } - + public TabInfo MovePage(PageMoveRequest request) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); @@ -332,32 +333,6 @@ public IEnumerable GetPageList(PortalSettings settings, int parentId = 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) - { - return false; - } - - if (tabId == parentId) - { - return true; - } - - var tab = TabController.Instance.GetTab(parentId, portalId); - while (tab != null && tab.ParentId != Null.NullInteger) - { - if (tab.ParentId == tabId) - { - return true; - } - - tab = TabController.Instance.GetTab(tab.ParentId, portalId); - } - - return false; - } - 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) { @@ -504,110 +479,6 @@ public bool ValidatePageUrlSettings(PortalSettings portalSettings, PageSettings return true; } - private TabInfo GetPageDetails(int pageId) - { - var portalSettings = this._portalController.GetCurrentPortalSettings(); - var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); - if (tab == null) - { - throw new PageNotFoundException(); - } - - return tab; - } - - protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, out string invalidField, out string errorMessage) - { - errorMessage = string.Empty; - invalidField = string.Empty; - - var isValid = !string.IsNullOrEmpty(pageSettings.Name) && TabController.IsValidTabName(pageSettings.Name, out errorMessage); - if (!isValid) - { - invalidField = pageSettings.PageType == "template" ? "templateName" : "name"; - if (string.IsNullOrEmpty(errorMessage)) - { - errorMessage = Localization.GetString("EmptyTabName"); - } - else if (errorMessage.Equals("InvalidTabName", StringComparison.OrdinalIgnoreCase)) - { - errorMessage = string.Format(Localization.GetString("InvalidTabName"), pageSettings.Name); - } - else - { - errorMessage = Localization.GetString(errorMessage); - } - return false; - } - - var parentId = pageSettings.ParentId ?? tab?.ParentId ?? Null.NullInteger; - - if (pageSettings.PageType == "template") - { - parentId = this.GetTemplateParentId(tab?.PortalID ?? portalSettings.PortalId); - } - - isValid = this.IsValidTabPath(tab, Globals.GenerateTabPath(parentId, pageSettings.Name), pageSettings.Name, out errorMessage); - if (!isValid) - { - invalidField = pageSettings.PageType == "template" ? "templateName" : "name"; - errorMessage = (pageSettings.PageType == "template" ? "templates_" : "") + errorMessage; - return false; - } - - if (pageSettings.StartDate.HasValue && pageSettings.EndDate.HasValue && pageSettings.StartDate > pageSettings.EndDate) - { - errorMessage = Localization.GetString("StartDateAfterEndDate"); - invalidField = "endDate"; - return false; - } - switch (pageSettings.PageType) - { - case "tab": - var existingTabRedirectionId = 0; - int.TryParse(pageSettings.ExistingTabRedirection, out existingTabRedirectionId); - if (existingTabRedirectionId <= 0) - { - errorMessage = Localization.GetString("TabToRedirectIsRequired"); - invalidField = "ExistingTabRedirection"; - return false; - } - if (!TabPermissionController.CanViewPage(TabController.Instance.GetTab(existingTabRedirectionId, - portalSettings.PortalId))) - { - errorMessage = Localization.GetString("NoPermissionViewRedirectPage"); - invalidField = "ExistingTabRedirection"; - return false; - } - break; - case "url": - if (string.IsNullOrEmpty(pageSettings.ExternalRedirection)) - { - errorMessage = Localization.GetString("ExternalRedirectionUrlRequired"); - invalidField = "ExternalRedirection"; - return false; - } - break; - case "file": - var fileIdRedirectionId = pageSettings.FileIdRedirection ?? 0; - var file = pageSettings.FileIdRedirection != null ? FileManager.Instance.GetFile(pageSettings.FileIdRedirection.Value) : null; - if (fileIdRedirectionId <= 0 || file == null) - { - errorMessage = Localization.GetString("ValidFileIsRequired"); - invalidField = "FileIdRedirection"; - return false; - } - break; - } - - return this.ValidatePageUrlSettings(portalSettings, pageSettings, tab, ref invalidField, ref errorMessage); - } - - protected virtual int GetTemplateParentId(int portalId) - { - return Null.NullInteger; - } - public virtual int AddTab(PortalSettings settings, PageSettings pageSettings) { var portalSettings = settings ?? PortalController.Instance.GetCurrentPortalSettings(); @@ -727,7 +598,7 @@ public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) 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)) { @@ -746,82 +617,502 @@ public void SaveTabUrl(TabInfo tab, PageSettings pageSettings) } } - protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings pageSettings) + public string CleanTabUrl(string url) { - tab.TabName = pageSettings.Name; - tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); - tab.Title = pageSettings.Title; - tab.Description = this.GetTabDescription(pageSettings); - tab.KeyWords = this.GetKeyWords(pageSettings); - tab.IsVisible = pageSettings.IncludeInMenu; - tab.DisableLink = pageSettings.DisableLink; + if (string.IsNullOrEmpty(url)) + { + return url; + } - tab.StartDate = pageSettings.StartDate ?? Null.NullDate; - tab.EndDate = pageSettings.EndDate ?? Null.NullDate; + var urlPath = url.TrimStart('/'); + bool modified; - tab.IsSecure = pageSettings.IsSecure; - tab.TabSettings["AllowIndex"] = pageSettings.AllowIndex; + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); + urlPath = UrlRewriterUtils.CleanExtension(urlPath, friendlyUrlSettings, string.Empty); - tab.SiteMapPriority = pageSettings.SiteMapPriority; - tab.PageHeadText = pageSettings.PageHeadText; + //Clean Url + var options = UrlRewriterUtils.ExtendOptionsForCustomURLs(UrlRewriterUtils.GetOptionsFromSettings(friendlyUrlSettings)); + urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); - tab.PermanentRedirect = pageSettings.PermanentRedirect; - tab.Url = this.GetInternalUrl(pageSettings); + return '/' + urlPath; + } - tab.TabSettings["CacheProvider"] = pageSettings.CacheProvider; - if (pageSettings.CacheProvider != null) + public void CopyThemeToDescendantPages(int pageId, Theme theme) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalId = portalSettings.PortalId; + var tab = this._tabController.GetTab(pageId, portalId, false); + if (tab == null) { - tab.TabSettings["CacheDuration"] = pageSettings.CacheDuration; - if (pageSettings.CacheIncludeExclude.HasValue) - { - if (pageSettings.CacheIncludeExclude.Value) - { - tab.TabSettings["CacheIncludeExclude"] = "1"; - tab.TabSettings["IncludeVaryBy"] = null; - tab.TabSettings["ExcludeVaryBy"] = pageSettings.CacheExcludeVaryBy; - } - else - { - tab.TabSettings["CacheIncludeExclude"] = "0"; - tab.TabSettings["IncludeVaryBy"] = pageSettings.CacheIncludeVaryBy; - tab.TabSettings["ExcludeVaryBy"] = null; - } - tab.TabSettings["MaxVaryByCount"] = pageSettings.CacheMaxVaryByCount; - } + throw new PageNotFoundException(); } - else + TabController.CopyDesignToChildren(tab, theme.SkinSrc, theme.ContainerSrc); + } + + public void CopyPermissionsToDescendantPages(int pageId) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalId = portalSettings.PortalId; + var tab = this._tabController.GetTab(pageId, portalId, false); + if (tab == null) { - tab.TabSettings["CacheDuration"] = null; - tab.TabSettings["CacheIncludeExclude"] = null; - tab.TabSettings["IncludeVaryBy"] = null; - tab.TabSettings["ExcludeVaryBy"] = null; - tab.TabSettings["MaxVaryByCount"] = null; + throw new PageNotFoundException(); } - tab.TabSettings["LinkNewWindow"] = pageSettings.LinkNewWindow.ToString(); - tab.TabSettings["CustomStylesheet"] = pageSettings.PageStyleSheet; + if (!TabPermissionController.CanManagePage(tab) || tab.IsSuperTab) + { + throw new PermissionsNotMetException(tab.TabID, Localization.GetString("CannotCopyPermissionsToDescendantPages")); + } - // Tab Skin - tab.SkinSrc = this.GetSkinSrc(pageSettings); - tab.ContainerSrc = this.GetContainerSrc(pageSettings); + TabController.CopyPermissionsToChildren(tab, tab.TabPermissions); + } - if (pageSettings.PageType == "template") + public IEnumerable GetPageUrls(int tabId) + { + var tab = this.GetPageDetails(tabId); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var portalId = portalSettings.PortalId; + return this._pageUrlsController.GetPageUrls(tab, portalId); + } + + public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSettings = null) + { + var tab = this.GetPageDetails(pageId); + + var portalSettings = requestPortalSettings ?? this._portalController.GetCurrentPortalSettings(); + + if (!this._contentVerifier.IsContentExistsForRequestedPortal(tab.PortalID, portalSettings)) { - tab.ParentId = this.GetTemplateParentId(tab.PortalID); - tab.IsSystem = true; + throw new PageNotFoundException(); } - tab.Terms.Clear(); - if (!string.IsNullOrEmpty(pageSettings.Tags)) + var page = Converters.ConvertToPageSettings(tab); + page.Modules = this.GetModules(page.TabId).Select(Converters.ConvertToModuleItem); + page.PageUrls = this.GetPageUrls(page.TabId); + page.Permissions = this.GetPermissionsData(pageId); + page.SiteAliases = this.GetSiteAliases(portalSettings.PortalId); + page.PrimaryAliasId = this.GetPrimaryAliasId(portalSettings.PortalId, portalSettings.CultureCode); + page.Locales = this.GetLocales(portalSettings.PortalId); + page.HasParent = tab.ParentId > -1; + + // icons + var iconFile = string.IsNullOrEmpty(tab.IconFile) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileRaw); + if (iconFile != null) + { + page.IconFile = new FileDto + { + fileId = iconFile.FileId, + fileName = iconFile.FileName, + folderId = iconFile.FolderId, + folderPath = iconFile.Folder + }; + } + var iconFileLarge = string.IsNullOrEmpty(tab.IconFileLarge) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileLargeRaw); + if (iconFileLarge != null) + { + page.IconFileLarge = new FileDto + { + fileId = iconFileLarge.FileId, + fileName = iconFileLarge.FileName, + folderId = iconFileLarge.FolderId, + folderPath = iconFileLarge.Folder + }; + } + + return page; + } + + public PageUrlResult CreateCustomUrl(SeoUrl dto) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this._pageUrlsController.CreateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); + } + + public PageUrlResult UpdateCustomUrl(SeoUrl dto) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this._pageUrlsController.UpdateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); + } + + public PageUrlResult DeleteCustomUrl(UrlIdDto dto) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return this._pageUrlsController.DeleteCustomUrl(dto.Id, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); + } + + public void CreateOrUpdateContentItem(TabInfo tab) + { + var contentController = Util.GetContentController(); + tab.Content = String.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; + tab.Indexed = false; + + if (tab.ContentItemId != Null.NullInteger) + { + contentController.UpdateContentItem(tab); + return; + } + + var typeController = new ContentTypeController(); + var contentType = + (from t in typeController.GetContentTypes() + where t.ContentType == "Tab" + select t).SingleOrDefault(); + + if (contentType != null) + { + tab.ContentTypeId = contentType.ContentTypeId; + } + contentController.AddContentItem(tab); + } + + public int UpdateTab(TabInfo tab, PageSettings pageSettings) + { + this.UpdateTabInfoFromPageSettings(tab, pageSettings); + this.SavePagePermissions(tab, pageSettings.Permissions); + + this._tabController.UpdateTab(tab); + + this.CreateOrUpdateContentItem(tab); + + this.SaveTabUrl(tab, pageSettings); + + this.MovePageIfNeeded(pageSettings, tab); + + return tab.TabID; + } + + public void SavePagePermissions(TabInfo tab, PagePermissions permissions) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + + tab.TabPermissions.Clear(); + + //add default permissions for administrators if needed + if (!HasAdminPermissions(permissions)) + { + //add default permissions + var permissionsList = PermissionController.GetPermissionsByTab(); + foreach (var permissionInfo in permissionsList) + { + var editPermisison = (PermissionInfo)permissionInfo; + var permission = new TabPermissionInfo(editPermisison) + { + RoleID = portalSettings.AdministratorRoleId, + AllowAccess = true, + RoleName = portalSettings.AdministratorRoleName + }; + tab.TabPermissions.Add(permission); + } + } + + //add role permissions + if (permissions.RolePermissions != null) + { + foreach (var rolePermission in permissions.RolePermissions.Where(NoLocked())) + { + if (rolePermission.RoleId.ToString() == Globals.glbRoleAllUsers || + RoleController.Instance.GetRoleById(portalSettings.PortalId, rolePermission.RoleId) != null) + { + foreach (var permission in rolePermission.Permissions) + { + tab.TabPermissions.Add(new TabPermissionInfo + { + PermissionID = permission.PermissionId, + RoleID = rolePermission.RoleId, + UserID = Null.NullInteger, + AllowAccess = permission.AllowAccess + }); + } + } + } + } + + //add user permissions + if (permissions.UserPermissions != null) + { + foreach (var userPermission in permissions.UserPermissions) + { + var user = UserController.Instance.GetUserById(portalSettings.PortalId, userPermission.UserId); + if (user != null) + { + int roleId; + int.TryParse(Globals.glbRoleNothing, out roleId); + foreach (var permission in userPermission.Permissions) + { + tab.TabPermissions.Add(new TabPermissionInfo + { + PermissionID = permission.PermissionId, + RoleID = roleId, + UserID = userPermission.UserId, + AllowAccess = permission.AllowAccess + }); + } + } + } + } + } + + public virtual PageSettings GetDefaultSettings(int pageId = 0) + { + var pageSettings = new PageSettings + { + Templates = this._templateController.GetTemplates(), + Permissions = this.GetPermissionsData(pageId) + }; + + pageSettings.TemplateId = this._templateController.GetDefaultTemplateId(pageSettings.Templates); + + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + if (PortalController.GetPortalSettingAsBoolean("SSLEnabled", portalSettings.PortalId, false) && + PortalController.GetPortalSettingAsBoolean("SSLEnforced", portalSettings.PortalId, false)) + { + pageSettings.IsSecure = true; + } + + return pageSettings; + } + + public PagePermissions GetPermissionsData(int pageId) + { + var permissions = new PagePermissions(true); + if (pageId > 0) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var tab = TabController.Instance.GetTab(pageId, portalSettings.PortalId); + if (tab != null) + { + foreach (TabPermissionInfo permission in tab.TabPermissions) + { + if (permission.UserID != Null.NullInteger) + { + permissions.AddUserPermission(permission); + } + else + { + permissions.AddRolePermission(permission); + } + } + + permissions.RolePermissions = + permissions.RolePermissions.OrderByDescending(p => p.Locked) + .ThenByDescending(p => p.IsDefault) + .ThenBy(p => p.RoleName) + .ToList(); + permissions.UserPermissions = permissions.UserPermissions.OrderBy(p => p.DisplayName).ToList(); + } + } + + return permissions; + } + + public void DeleteTabModule(int pageId, int moduleId) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); + if (tab == null) + { + throw new PageModuleNotFoundException(); + } + + var tabModule = this._moduleController.GetModule(moduleId, pageId, false); + if (tabModule == null) + { + throw new PageModuleNotFoundException(); + } + + if (!TabPermissionController.CanAddContentToPage(tab)) + { + throw new SecurityException("You do not have permission to delete module on this page"); + } + + 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); + if (sourceTab == null || sourceTab.IsDeleted) + { + return; + } + //Copy Properties + this.CopySourceTabProperties(tab, sourceTab); + + //Copy Modules + this.CopyModulesFromSourceTab(tab, sourceTab, includedModules); + } + + protected virtual bool ValidatePageSettingsData(PortalSettings portalSettings, PageSettings pageSettings, TabInfo tab, out string invalidField, out string errorMessage) + { + errorMessage = string.Empty; + invalidField = string.Empty; + + var isValid = !string.IsNullOrEmpty(pageSettings.Name) && TabController.IsValidTabName(pageSettings.Name, out errorMessage); + if (!isValid) + { + invalidField = pageSettings.PageType == "template" ? "templateName" : "name"; + if (string.IsNullOrEmpty(errorMessage)) + { + errorMessage = Localization.GetString("EmptyTabName"); + } + else if (errorMessage.Equals("InvalidTabName", StringComparison.OrdinalIgnoreCase)) + { + errorMessage = string.Format(Localization.GetString("InvalidTabName"), pageSettings.Name); + } + else + { + errorMessage = Localization.GetString(errorMessage); + } + return false; + } + + var parentId = pageSettings.ParentId ?? tab?.ParentId ?? Null.NullInteger; + + if (pageSettings.PageType == "template") + { + parentId = this.GetTemplateParentId(tab?.PortalID ?? portalSettings.PortalId); + } + + isValid = this.IsValidTabPath(tab, Globals.GenerateTabPath(parentId, pageSettings.Name), pageSettings.Name, out errorMessage); + if (!isValid) + { + invalidField = pageSettings.PageType == "template" ? "templateName" : "name"; + errorMessage = (pageSettings.PageType == "template" ? "templates_" : "") + errorMessage; + return false; + } + + if (pageSettings.StartDate.HasValue && pageSettings.EndDate.HasValue && pageSettings.StartDate > pageSettings.EndDate) + { + errorMessage = Localization.GetString("StartDateAfterEndDate"); + invalidField = "endDate"; + return false; + } + switch (pageSettings.PageType) + { + case "tab": + var existingTabRedirectionId = 0; + int.TryParse(pageSettings.ExistingTabRedirection, out existingTabRedirectionId); + if (existingTabRedirectionId <= 0) + { + errorMessage = Localization.GetString("TabToRedirectIsRequired"); + invalidField = "ExistingTabRedirection"; + return false; + } + if (!TabPermissionController.CanViewPage(TabController.Instance.GetTab(existingTabRedirectionId, + portalSettings.PortalId))) + { + errorMessage = Localization.GetString("NoPermissionViewRedirectPage"); + invalidField = "ExistingTabRedirection"; + return false; + } + break; + case "url": + if (string.IsNullOrEmpty(pageSettings.ExternalRedirection)) + { + errorMessage = Localization.GetString("ExternalRedirectionUrlRequired"); + invalidField = "ExternalRedirection"; + return false; + } + break; + case "file": + var fileIdRedirectionId = pageSettings.FileIdRedirection ?? 0; + var file = pageSettings.FileIdRedirection != null ? FileManager.Instance.GetFile(pageSettings.FileIdRedirection.Value) : null; + if (fileIdRedirectionId <= 0 || file == null) + { + errorMessage = Localization.GetString("ValidFileIsRequired"); + invalidField = "FileIdRedirection"; + return false; + } + break; + } + + return this.ValidatePageUrlSettings(portalSettings, pageSettings, tab, ref invalidField, ref errorMessage); + } + + protected virtual int GetTemplateParentId(int portalId) + { + return Null.NullInteger; + } + + protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings pageSettings) + { + tab.TabName = pageSettings.Name; + tab.TabPath = Globals.GenerateTabPath(tab.ParentId, tab.TabName); + tab.Title = pageSettings.Title; + tab.Description = this.GetTabDescription(pageSettings); + tab.KeyWords = this.GetKeyWords(pageSettings); + tab.IsVisible = pageSettings.IncludeInMenu; + tab.DisableLink = pageSettings.DisableLink; + + tab.StartDate = pageSettings.StartDate ?? Null.NullDate; + tab.EndDate = pageSettings.EndDate ?? Null.NullDate; + + tab.IsSecure = pageSettings.IsSecure; + tab.TabSettings["AllowIndex"] = pageSettings.AllowIndex; + + tab.SiteMapPriority = pageSettings.SiteMapPriority; + tab.PageHeadText = pageSettings.PageHeadText; + + tab.PermanentRedirect = pageSettings.PermanentRedirect; + tab.Url = this.GetInternalUrl(pageSettings); + + tab.TabSettings["CacheProvider"] = pageSettings.CacheProvider; + if (pageSettings.CacheProvider != null) + { + tab.TabSettings["CacheDuration"] = pageSettings.CacheDuration; + if (pageSettings.CacheIncludeExclude.HasValue) + { + if (pageSettings.CacheIncludeExclude.Value) + { + tab.TabSettings["CacheIncludeExclude"] = "1"; + tab.TabSettings["IncludeVaryBy"] = null; + tab.TabSettings["ExcludeVaryBy"] = pageSettings.CacheExcludeVaryBy; + } + else + { + tab.TabSettings["CacheIncludeExclude"] = "0"; + tab.TabSettings["IncludeVaryBy"] = pageSettings.CacheIncludeVaryBy; + tab.TabSettings["ExcludeVaryBy"] = null; + } + tab.TabSettings["MaxVaryByCount"] = pageSettings.CacheMaxVaryByCount; + } + } + + else + { + tab.TabSettings["CacheDuration"] = null; + tab.TabSettings["CacheIncludeExclude"] = null; + tab.TabSettings["IncludeVaryBy"] = null; + tab.TabSettings["ExcludeVaryBy"] = null; + tab.TabSettings["MaxVaryByCount"] = null; + } + + tab.TabSettings["LinkNewWindow"] = pageSettings.LinkNewWindow.ToString(); + tab.TabSettings["CustomStylesheet"] = pageSettings.PageStyleSheet; + + // Tab Skin + tab.SkinSrc = this.GetSkinSrc(pageSettings); + tab.ContainerSrc = this.GetContainerSrc(pageSettings); + + if (pageSettings.PageType == "template") + { + tab.ParentId = this.GetTemplateParentId(tab.PortalID); + tab.IsSystem = true; + } + + tab.Terms.Clear(); + if (!string.IsNullOrEmpty(pageSettings.Tags)) { tab.Terms.Clear(); var termController = new TermController(); var vocabularyController = Util.GetVocabularyController(); var vocabulary = (vocabularyController.GetVocabularies() - .Cast() - .Where(v => v.Name == PageTagsVocabulary && v.ScopeId == tab.PortalID)) - .SingleOrDefault(); + .Cast() + .Where(v => v.Name == PageTagsVocabulary && v.ScopeId == tab.PortalID)) + .SingleOrDefault(); int vocabularyId; if (vocabulary == null) @@ -847,8 +1138,8 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p //get all terms info var allTerms = new List(); var vocabularies = from v in vocabularyController.GetVocabularies() - where (v.ScopeType.ScopeType == "Portal" && v.ScopeId == tab.PortalID && !v.Name.Equals("Tags", StringComparison.OrdinalIgnoreCase)) - select v; + where (v.ScopeType.ScopeType == "Portal" && v.ScopeId == tab.PortalID && !v.Name.Equals("Tags", StringComparison.OrdinalIgnoreCase)) + select v; foreach (var v in vocabularies) { allTerms.AddRange(termController.GetTermsByVocabulary(v.VocabularyId)); @@ -883,257 +1174,19 @@ protected virtual void UpdateTabInfoFromPageSettings(TabInfo tab, PageSettings p { tab.IconFileLarge = FileManager.Instance.GetFile(pageSettings.IconFileLarge.fileId).RelativePath; } - 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) - { - var defaultContainer = this._defaultPortalThemeController.GetDefaultPortalContainer(); - if (pageSettings.ContainerSrc != null && - pageSettings.ContainerSrc.Equals(defaultContainer, - StringComparison.OrdinalIgnoreCase)) - { - return null; - } - return pageSettings.ContainerSrc; - } - - private string GetSkinSrc(PageSettings pageSettings) - { - var defaultSkin = this._defaultPortalThemeController.GetDefaultPortalLayout(); - if (pageSettings.SkinSrc != null && - pageSettings.SkinSrc.Equals(defaultSkin, - StringComparison.OrdinalIgnoreCase)) - { - return null; - } - return pageSettings.SkinSrc; - } - - private string GetInternalUrl(PageSettings pageSettings) - { - switch (pageSettings.PageType) - { - case "tab": - return pageSettings.ExistingTabRedirection; - case "url": - return GetExternalUrlRedirection(pageSettings.ExternalRedirection); - case "file": - return pageSettings.FileIdRedirection.HasValue ? "FileId=" + pageSettings.FileIdRedirection : null; - default: - return null; - } - } - - /// - /// If the tab description is equal to the portal description - /// we store null so the system will serve the portal description instead. - /// - /// - /// Tab Description value to be stored. - private string GetTabDescription(PageSettings pageSettings) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return pageSettings.Description != portalSettings.Description - ? pageSettings.Description : null; - } - - /// - /// If the tab keywords is equal to the portal keywords - /// we store null so the system will serve the portal keywords instead. - /// - /// - /// Tab Keywords value to be stored. - private string GetKeyWords(PageSettings pageSettings) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return pageSettings.Keywords != portalSettings.KeyWords - ? pageSettings.Keywords : null; - } - - public string CleanTabUrl(string url) - { - if (string.IsNullOrEmpty(url)) - { - return url; - } - - var urlPath = url.TrimStart('/'); - bool modified; - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var friendlyUrlSettings = new FriendlyUrlSettings(portalSettings.PortalId); - urlPath = UrlRewriterUtils.CleanExtension(urlPath, friendlyUrlSettings, string.Empty); - - //Clean Url - var options = UrlRewriterUtils.ExtendOptionsForCustomURLs(UrlRewriterUtils.GetOptionsFromSettings(friendlyUrlSettings)); - urlPath = FriendlyUrlController.CleanNameForUrl(urlPath, options, out modified); - - return '/' + urlPath; - } - - public void CopyThemeToDescendantPages(int pageId, Theme theme) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var portalId = portalSettings.PortalId; - var tab = this._tabController.GetTab(pageId, portalId, false); - if (tab == null) - { - throw new PageNotFoundException(); - } - - TabController.CopyDesignToChildren(tab, theme.SkinSrc, theme.ContainerSrc); - } - - public void CopyPermissionsToDescendantPages(int pageId) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var portalId = portalSettings.PortalId; - var tab = this._tabController.GetTab(pageId, portalId, false); - if (tab == null) - { - throw new PageNotFoundException(); - } - - if (!TabPermissionController.CanManagePage(tab) || tab.IsSuperTab) - { - throw new PermissionsNotMetException(tab.TabID, Localization.GetString("CannotCopyPermissionsToDescendantPages")); - } - - TabController.CopyPermissionsToChildren(tab, tab.TabPermissions); - } - - public IEnumerable GetPageUrls(int tabId) - { - var tab = this.GetPageDetails(tabId); - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var portalId = portalSettings.PortalId; - return this._pageUrlsController.GetPageUrls(tab, portalId); - } - - public PageSettings GetPageSettings(int pageId, PortalSettings requestPortalSettings = null) - { - var tab = this.GetPageDetails(pageId); - - var portalSettings = requestPortalSettings ?? this._portalController.GetCurrentPortalSettings(); - - 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); - page.Permissions = this.GetPermissionsData(pageId); - page.SiteAliases = this.GetSiteAliases(portalSettings.PortalId); - page.PrimaryAliasId = this.GetPrimaryAliasId(portalSettings.PortalId, portalSettings.CultureCode); - page.Locales = this.GetLocales(portalSettings.PortalId); - page.HasParent = tab.ParentId > -1; - - // icons - var iconFile = string.IsNullOrEmpty(tab.IconFile) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileRaw); - if (iconFile != null) - { - page.IconFile = new FileDto - { - fileId = iconFile.FileId, - fileName = iconFile.FileName, - folderId = iconFile.FolderId, - folderPath = iconFile.Folder - }; - } - var iconFileLarge = string.IsNullOrEmpty(tab.IconFileLarge) ? null : FileManager.Instance.GetFile(tab.PortalID, tab.IconFileLargeRaw); - if (iconFileLarge != null) - { - page.IconFileLarge = new FileDto - { - fileId = iconFileLarge.FileId, - fileName = iconFileLarge.FileName, - folderId = iconFileLarge.FolderId, - folderPath = iconFileLarge.Folder - }; - } - - return page; - } - - public PageUrlResult CreateCustomUrl(SeoUrl dto) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this._pageUrlsController.CreateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); - } - - public PageUrlResult UpdateCustomUrl(SeoUrl dto) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this._pageUrlsController.UpdateCustomUrl(dto.SaveUrl, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); - } - - public PageUrlResult DeleteCustomUrl(UrlIdDto dto) - { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return this._pageUrlsController.DeleteCustomUrl(dto.Id, this._tabController.GetTab(dto.TabId, portalSettings.PortalId, false)); - } - public void CreateOrUpdateContentItem(TabInfo tab) - { - var contentController = Util.GetContentController(); - tab.Content = String.IsNullOrEmpty(tab.Title) ? tab.TabName : tab.Title; - tab.Indexed = false; - - if (tab.ContentItemId != Null.NullInteger) - { - contentController.UpdateContentItem(tab); - return; - } - - var typeController = new ContentTypeController(); - var contentType = - (from t in typeController.GetContentTypes() - where t.ContentType == "Tab" - select t).SingleOrDefault(); - - if (contentType != null) + else { - tab.ContentTypeId = contentType.ContentTypeId; + tab.IconFileLarge = null; } - 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); @@ -1144,207 +1197,157 @@ protected IEnumerable> GetSiteAliases(int portalId) { 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(); + && (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) + private static string GetExternalUrlRedirection(string url) { - this.UpdateTabInfoFromPageSettings(tab, pageSettings); - this.SavePagePermissions(tab, pageSettings.Permissions); - - this._tabController.UpdateTab(tab); - - this.CreateOrUpdateContentItem(tab); - - this.SaveTabUrl(tab, pageSettings); + if (url == null) + { + return null; + } - this.MovePageIfNeeded(pageSettings, tab); + return url.ToLower() == "http://" ? "" : Globals.AddHTTP(url); + } - return tab.TabID; + private static Func NoLocked() + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); } - public void SavePagePermissions(TabInfo tab, PagePermissions permissions) + 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); + } - tab.TabPermissions.Clear(); + private static bool HasTags(string tags, IEnumerable terms) + { + return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); + } - //add default permissions for administrators if needed - if (!HasAdminPermissions(permissions)) + private bool IsChild(int portalId, int tabId, int parentId) + { + if (parentId == Null.NullInteger) { - //add default permissions - var permissionsList = PermissionController.GetPermissionsByTab(); - foreach (var permissionInfo in permissionsList) - { - var editPermisison = (PermissionInfo)permissionInfo; - var permission = new TabPermissionInfo(editPermisison) - { - RoleID = portalSettings.AdministratorRoleId, - AllowAccess = true, - RoleName = portalSettings.AdministratorRoleName - }; - tab.TabPermissions.Add(permission); - } + return false; } - //add role permissions - if (permissions.RolePermissions != null) + if (tabId == parentId) { - foreach (var rolePermission in permissions.RolePermissions.Where(NoLocked())) - { - if (rolePermission.RoleId.ToString() == Globals.glbRoleAllUsers || - RoleController.Instance.GetRoleById(portalSettings.PortalId, rolePermission.RoleId) != null) - { - foreach (var permission in rolePermission.Permissions) - { - tab.TabPermissions.Add(new TabPermissionInfo - { - PermissionID = permission.PermissionId, - RoleID = rolePermission.RoleId, - UserID = Null.NullInteger, - AllowAccess = permission.AllowAccess - }); - } - } - } + return true; } - - //add user permissions - if (permissions.UserPermissions != null) + + var tab = TabController.Instance.GetTab(parentId, portalId); + while (tab != null && tab.ParentId != Null.NullInteger) { - foreach (var userPermission in permissions.UserPermissions) + if (tab.ParentId == tabId) { - var user = UserController.Instance.GetUserById(portalSettings.PortalId, userPermission.UserId); - if (user != null) - { - int roleId; - int.TryParse(Globals.glbRoleNothing, out roleId); - foreach (var permission in userPermission.Permissions) - { - tab.TabPermissions.Add(new TabPermissionInfo - { - PermissionID = permission.PermissionId, - RoleID = roleId, - UserID = userPermission.UserId, - AllowAccess = permission.AllowAccess - }); - } - } + return true; } - } - } - public virtual PageSettings GetDefaultSettings(int pageId = 0) - { - var pageSettings = new PageSettings - { - Templates = this._templateController.GetTemplates(), - Permissions = this.GetPermissionsData(pageId) - }; - - pageSettings.TemplateId = this._templateController.GetDefaultTemplateId(pageSettings.Templates); - - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - if (PortalController.GetPortalSettingAsBoolean("SSLEnabled", portalSettings.PortalId, false) && - PortalController.GetPortalSettingAsBoolean("SSLEnforced", portalSettings.PortalId, false)) - { - pageSettings.IsSecure = true; + tab = TabController.Instance.GetTab(tab.ParentId, portalId); } - return pageSettings; + return false; } - private static Func NoLocked() + private TabInfo GetPageDetails(int pageId) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - return r => !(r.Locked && r.RoleId != portalSettings.AdministratorRoleId); - } + var portalSettings = this._portalController.GetCurrentPortalSettings(); + var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); + if (tab == null) + { + throw new PageNotFoundException(); + } - 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); + return tab; } - public PagePermissions GetPermissionsData(int pageId) + private void MovePageIfNeeded(PageSettings pageSettings, TabInfo tab) { - var permissions = new PagePermissions(true); - if (pageId > 0) + if (pageSettings.ParentId.HasValue && pageSettings.ParentId.Value != tab.ParentId) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var tab = TabController.Instance.GetTab(pageId, portalSettings.PortalId); - if (tab != null) + var request = new PageMoveRequest { - foreach (TabPermissionInfo permission in tab.TabPermissions) - { - if (permission.UserID != Null.NullInteger) - { - permissions.AddUserPermission(permission); - } - else - { - permissions.AddRolePermission(permission); - } - } + Action = "parent", + PageId = tab.TabID, + ParentId = pageSettings.ParentId.Value + }; - permissions.RolePermissions = - permissions.RolePermissions.OrderByDescending(p => p.Locked) - .ThenByDescending(p => p.IsDefault) - .ThenBy(p => p.RoleName) - .ToList(); - permissions.UserPermissions = permissions.UserPermissions.OrderBy(p => p.DisplayName).ToList(); - } + this.MovePage(request); } - - return permissions; } - public void DeleteTabModule(int pageId, int moduleId) + private string GetContainerSrc(PageSettings pageSettings) { - var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); - var tab = this._tabController.GetTab(pageId, portalSettings.PortalId); - if (tab == null) - { - throw new PageModuleNotFoundException(); - } - - var tabModule = this._moduleController.GetModule(moduleId, pageId, false); - if (tabModule == null) + var defaultContainer = this._defaultPortalThemeController.GetDefaultPortalContainer(); + if (pageSettings.ContainerSrc != null && + pageSettings.ContainerSrc.Equals(defaultContainer, + StringComparison.OrdinalIgnoreCase)) { - throw new PageModuleNotFoundException(); + return null; } + return pageSettings.ContainerSrc; + } - if (!TabPermissionController.CanAddContentToPage(tab)) + private string GetSkinSrc(PageSettings pageSettings) + { + var defaultSkin = this._defaultPortalThemeController.GetDefaultPortalLayout(); + if (pageSettings.SkinSrc != null && + pageSettings.SkinSrc.Equals(defaultSkin, + StringComparison.OrdinalIgnoreCase)) { - throw new SecurityException("You do not have permission to delete module on this page"); + return null; } - - this._moduleController.DeleteTabModule(pageId, moduleId, true); - this._moduleController.ClearCache(pageId); + return pageSettings.SkinSrc; } - - public void CopyContentFromSourceTab(TabInfo tab, int sourceTabId, IEnumerable includedModules) + + private string GetInternalUrl(PageSettings pageSettings) { - var sourceTab = this._tabController.GetTab(sourceTabId, tab.PortalID); - if (sourceTab == null || sourceTab.IsDeleted) + switch (pageSettings.PageType) { - return; + case "tab": + return pageSettings.ExistingTabRedirection; + case "url": + return GetExternalUrlRedirection(pageSettings.ExternalRedirection); + case "file": + return pageSettings.FileIdRedirection.HasValue ? "FileId=" + pageSettings.FileIdRedirection : null; + default: + return null; } - //Copy Properties - this.CopySourceTabProperties(tab, sourceTab); + } - //Copy Modules - this.CopyModulesFromSourceTab(tab, sourceTab, includedModules); + /// + /// If the tab description is equal to the portal description + /// we store null so the system will serve the portal description instead. + /// + /// + /// Tab Description value to be stored. + private string GetTabDescription(PageSettings pageSettings) + { + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return pageSettings.Description != portalSettings.Description + ? pageSettings.Description : null; } - private static bool HasTags(string tags, IEnumerable terms) + /// + /// If the tab keywords is equal to the portal keywords + /// we store null so the system will serve the portal keywords instead. + /// + /// + /// Tab Keywords value to be stored. + private string GetKeyWords(PageSettings pageSettings) { - return tags.Split(',').All(tag => terms.Any(t => string.Compare(t.Name, tag, StringComparison.CurrentCultureIgnoreCase) == 0)); + var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); + return pageSettings.Keywords != portalSettings.KeyWords + ? pageSettings.Keywords : null; } private string GetLocalPath(string url) 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 11756291362..e942ee86dc0 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 @@ -19,7 +19,7 @@ public class DeletePage : ConsoleCommandBase { [FlagParameter("name", "Prompt_DeletePage_FlagName", "String")] private const string FlagName = "name"; - + [FlagParameter("id", "Prompt_DeletePage_FlagId", "Integer")] private const string FlagId = "id"; @@ -35,7 +35,7 @@ public class DeletePage : ConsoleCommandBase 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 187acec3242..fdaa24b45ae 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 @@ -21,12 +21,13 @@ public class GetPage : ConsoleCommandBase { [FlagParameter("name", "Prompt_GetPage_FlagName", "String")] private const string FlagName = "name"; + [FlagParameter("id", "Prompt_GetPage_FlagId", "Integer")] private const string FlagId = "id"; + [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; @@ -36,21 +37,23 @@ public GetPage() : { } - private int PageId { get; set; } = -1; - private string PageName { get; set; } - private int ParentId { get; set; } = -1; - public GetPage( ITabController tabController, ISecurityService securityService, IContentVerifier contentVerifier - ) + ) { this._tabController = tabController; this._securityService = securityService; this._contentVerifier = contentVerifier; } + 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) { diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs index 7a9297c9617..930422afb5f 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Prompt/Commands/Goto.cs @@ -17,8 +17,10 @@ public class Goto : ConsoleCommandBase { [FlagParameter("name", "Prompt_Goto_FlagName", "String")] private const string FlagName = "name"; + [FlagParameter("id", "Prompt_Goto_FlagId", "Integer")] private const string FlagId = "id"; + [FlagParameter("parentid", "Prompt_Goto_FlagParentId", "Integer")] private const string FlagParentId = "parentid"; @@ -28,8 +30,8 @@ public class Goto : ConsoleCommandBase 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); 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 7ad3fd39cbe..6b58cfcd2b2 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 @@ -43,7 +43,7 @@ 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; 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 5fbe6fbf6a0..7ee9e3d8370 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 @@ -39,7 +39,7 @@ 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; } @@ -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 74d013d24ce..7fcbe291fe3 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 @@ -42,7 +42,7 @@ 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; } @@ -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 af7ed662341..9d20826dfd5 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 @@ -9,7 +9,7 @@ public class PageModel : PageModelBase public PageModel() { } - + public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab) : base(tab) { this.Container = tab.ContainerSrc; @@ -17,6 +17,7 @@ public PageModel(DotNetNuke.Entities.Tabs.TabInfo tab) : base(tab) this.Keywords = tab.KeyWords; this.Description = tab.Description; } + public string Container { get; set; } public string Url { get; set; } public string Keywords { 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 a4b489f9b42..9cb8ce247df 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 @@ -9,23 +9,7 @@ public class PageModelBase public PageModelBase() { } - - public int TabId { get; set; } - public string Name { get; set; } - public string Title { get; set; } - public int ParentId { get; set; } - public string Skin { get; set; } - public string Path { get; set; } - public bool IncludeInMenu { get; set; } - 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")}"; public PageModelBase(DotNetNuke.Entities.Tabs.TabInfo tab) { this.Name = tab.TabName; @@ -36,6 +20,23 @@ public PageModelBase(DotNetNuke.Entities.Tabs.TabInfo tab) this.Title = tab.Title; this.IncludeInMenu = tab.IsVisible; this.IsDeleted = tab.IsDeleted; - } + } + + 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")}"; + + public int TabId { get; set; } + public string Name { get; set; } + public string Title { get; set; } + public int ParentId { get; set; } + public string Skin { get; set; } + public string Path { get; set; } + public bool IncludeInMenu { get; set; } + public bool IsDeleted { get; set; } } } 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 df330e9705d..a54d6ef90b7 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/Security/SecurityService.cs @@ -71,18 +71,6 @@ 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 @@ -171,6 +159,18 @@ public virtual bool IsAdminHostSystemPage() PortalSettings.Current.ActiveTab.ParentId == PortalSettings.Current.AdminTabId || PortalSettings.Current.ActiveTab.TabID == PortalSettings.Current.AdminTabId; } + private bool IsPageAdmin() + { + return //TabPermissionController.CanAddContentToPage() || + TabPermissionController.CanAddPage() + || TabPermissionController.CanAdminPage() + || TabPermissionController.CanCopyPage() + || TabPermissionController.CanDeletePage() + || TabPermissionController.CanExportPage() + || TabPermissionController.CanImportPage() + || TabPermissionController.CanManagePage(); + } + private TabInfo GetTabById(int pageId) { var portalSettings = PortalController.Instance.GetCurrentPortalSettings(); diff --git a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs index 2fdf72b23be..7b7e439968c 100644 --- a/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs +++ b/Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Pages/TemplateController.cs @@ -38,7 +38,7 @@ public TemplateController() public string SaveAsTemplate(PageTemplate template) { string filename; - try + try { var folder = GetTemplateFolder(); @@ -61,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"); @@ -80,14 +80,15 @@ public string SaveAsTemplate(PageTemplate template) return filename; } + public IEnumerable